code
stringlengths 13
6.09M
| order_type
stringclasses 2
values | original_example
dict | step_ids
listlengths 1
5
|
|---|---|---|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 2 18:52:27 2021
@author: burak
"""
import veriler
import gorsel
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
neighbors = np.arange(1,13)
train_accuracy = np.empty(len(neighbors))
test_accuracy = np.empty(len(neighbors))
for n, k in enumerate(neighbors):
knn = KNeighborsClassifier(n_neighbors=k, metric='minkowski')
knn.fit(veriler.X_train, veriler.y_train.ravel())
train_accuracy[n] = knn.score(veriler.X_train, veriler.y_train)
test_accuracy[n] = knn.score(veriler.X_test, veriler.y_test)
gorsel.plot_show('K-NN Degisen Komsu Sayisi', neighbors, test_accuracy, train_accuracy, 'Test Dogrulugu', 'Egitim Dogrulugu', 'Komsu Sayisi', 'Dogruluk')
#Yukardaki verileri inceleyerek n_neighbors=9 verirsek
knn = KNeighborsClassifier(n_neighbors=9, metric='minkowski')
knn.fit(veriler.X_train, veriler.y_train.ravel())
accuracy = knn.score(veriler.X_test, veriler.y_test)
gorsel.plot_confusion_matrix_show(knn, veriler.X_test, veriler.y_test, str(accuracy))
|
normal
|
{
"blob_id": "133bd0b2affc3d29390edeab51299d294dafb709",
"index": 4188,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor n, k in enumerate(neighbors):\n knn = KNeighborsClassifier(n_neighbors=k, metric='minkowski')\n knn.fit(veriler.X_train, veriler.y_train.ravel())\n train_accuracy[n] = knn.score(veriler.X_train, veriler.y_train)\n test_accuracy[n] = knn.score(veriler.X_test, veriler.y_test)\ngorsel.plot_show('K-NN Degisen Komsu Sayisi', neighbors, test_accuracy,\n train_accuracy, 'Test Dogrulugu', 'Egitim Dogrulugu', 'Komsu Sayisi',\n 'Dogruluk')\n<mask token>\nknn.fit(veriler.X_train, veriler.y_train.ravel())\n<mask token>\ngorsel.plot_confusion_matrix_show(knn, veriler.X_test, veriler.y_test, str(\n accuracy))\n",
"step-3": "<mask token>\nneighbors = np.arange(1, 13)\ntrain_accuracy = np.empty(len(neighbors))\ntest_accuracy = np.empty(len(neighbors))\nfor n, k in enumerate(neighbors):\n knn = KNeighborsClassifier(n_neighbors=k, metric='minkowski')\n knn.fit(veriler.X_train, veriler.y_train.ravel())\n train_accuracy[n] = knn.score(veriler.X_train, veriler.y_train)\n test_accuracy[n] = knn.score(veriler.X_test, veriler.y_test)\ngorsel.plot_show('K-NN Degisen Komsu Sayisi', neighbors, test_accuracy,\n train_accuracy, 'Test Dogrulugu', 'Egitim Dogrulugu', 'Komsu Sayisi',\n 'Dogruluk')\nknn = KNeighborsClassifier(n_neighbors=9, metric='minkowski')\nknn.fit(veriler.X_train, veriler.y_train.ravel())\naccuracy = knn.score(veriler.X_test, veriler.y_test)\ngorsel.plot_confusion_matrix_show(knn, veriler.X_test, veriler.y_test, str(\n accuracy))\n",
"step-4": "<mask token>\nimport veriler\nimport gorsel\nimport numpy as np\nfrom sklearn.neighbors import KNeighborsClassifier\nneighbors = np.arange(1, 13)\ntrain_accuracy = np.empty(len(neighbors))\ntest_accuracy = np.empty(len(neighbors))\nfor n, k in enumerate(neighbors):\n knn = KNeighborsClassifier(n_neighbors=k, metric='minkowski')\n knn.fit(veriler.X_train, veriler.y_train.ravel())\n train_accuracy[n] = knn.score(veriler.X_train, veriler.y_train)\n test_accuracy[n] = knn.score(veriler.X_test, veriler.y_test)\ngorsel.plot_show('K-NN Degisen Komsu Sayisi', neighbors, test_accuracy,\n train_accuracy, 'Test Dogrulugu', 'Egitim Dogrulugu', 'Komsu Sayisi',\n 'Dogruluk')\nknn = KNeighborsClassifier(n_neighbors=9, metric='minkowski')\nknn.fit(veriler.X_train, veriler.y_train.ravel())\naccuracy = knn.score(veriler.X_test, veriler.y_test)\ngorsel.plot_confusion_matrix_show(knn, veriler.X_test, veriler.y_test, str(\n accuracy))\n",
"step-5": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 2 18:52:27 2021\n\n@author: burak\n\"\"\"\n\nimport veriler\nimport gorsel\nimport numpy as np\nfrom sklearn.neighbors import KNeighborsClassifier\n\nneighbors = np.arange(1,13)\ntrain_accuracy = np.empty(len(neighbors))\ntest_accuracy = np.empty(len(neighbors))\n\nfor n, k in enumerate(neighbors):\n knn = KNeighborsClassifier(n_neighbors=k, metric='minkowski') \n knn.fit(veriler.X_train, veriler.y_train.ravel()) \n train_accuracy[n] = knn.score(veriler.X_train, veriler.y_train) \n test_accuracy[n] = knn.score(veriler.X_test, veriler.y_test)\n\ngorsel.plot_show('K-NN Degisen Komsu Sayisi', neighbors, test_accuracy, train_accuracy, 'Test Dogrulugu', 'Egitim Dogrulugu', 'Komsu Sayisi', 'Dogruluk')\n\n\n#Yukardaki verileri inceleyerek n_neighbors=9 verirsek\nknn = KNeighborsClassifier(n_neighbors=9, metric='minkowski') \nknn.fit(veriler.X_train, veriler.y_train.ravel())\naccuracy = knn.score(veriler.X_test, veriler.y_test)\ngorsel.plot_confusion_matrix_show(knn, veriler.X_test, veriler.y_test, str(accuracy))",
"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('the original DNA sequence is', dnaSequence)
print('the first fragment is', firstFragment, 'and is', firstFragmentLen,
'letters long')
print('the second fragment is', secondFragment, 'and is', secondFragmentLen,
'letters long')
<|reserved_special_token_1|>
dnaSequence = 'ACTGATCGATTACGTATAGTAGAATTCTATCATACATATATATCGATGCGTTCAT'
firstFragment = 'ACTGATCGATTACGTATAGTAGAATTCTATCATACATATATATCGATGCGTTCAT'[0:22]
secondFragment = 'ACTGATCGATTACGTATAGTAGAATTCTATCATACATATATATCGATGCGTTCAT'[
23:100]
firstFragmentLen = len(firstFragment)
secondFragmentLen = len(secondFragment)
print('the original DNA sequence is', dnaSequence)
print('the first fragment is', firstFragment, 'and is', firstFragmentLen,
'letters long')
print('the second fragment is', secondFragment, 'and is', secondFragmentLen,
'letters long')
<|reserved_special_token_1|>
#the initial DNA sequence
dnaSequence = 'ACTGATCGATTACGTATAGTAGAATTCTATCATACATATATATCGATGCGTTCAT'
#seperating the DNA sequence at the specified location
firstFragment = 'ACTGATCGATTACGTATAGTAGAATTCTATCATACATATATATCGATGCGTTCAT' [0:22]
secondFragment = 'ACTGATCGATTACGTATAGTAGAATTCTATCATACATATATATCGATGCGTTCAT' [23:100]
#finsing the length of the 2 fragments
firstFragmentLen = len(firstFragment)
secondFragmentLen = len(secondFragment)
#printing the original and the split DNA sequence
print("the original DNA sequence is", dnaSequence)
print("the first fragment is", firstFragment, "and is", firstFragmentLen ,"letters long")
print("the second fragment is", secondFragment, "and is", secondFragmentLen,"letters long")
|
flexible
|
{
"blob_id": "7dc99d33023dbb13938ac413af7d3e9471fdbc3d",
"index": 126,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('the original DNA sequence is', dnaSequence)\nprint('the first fragment is', firstFragment, 'and is', firstFragmentLen,\n 'letters long')\nprint('the second fragment is', secondFragment, 'and is', secondFragmentLen,\n 'letters long')\n",
"step-3": "dnaSequence = 'ACTGATCGATTACGTATAGTAGAATTCTATCATACATATATATCGATGCGTTCAT'\nfirstFragment = 'ACTGATCGATTACGTATAGTAGAATTCTATCATACATATATATCGATGCGTTCAT'[0:22]\nsecondFragment = 'ACTGATCGATTACGTATAGTAGAATTCTATCATACATATATATCGATGCGTTCAT'[\n 23:100]\nfirstFragmentLen = len(firstFragment)\nsecondFragmentLen = len(secondFragment)\nprint('the original DNA sequence is', dnaSequence)\nprint('the first fragment is', firstFragment, 'and is', firstFragmentLen,\n 'letters long')\nprint('the second fragment is', secondFragment, 'and is', secondFragmentLen,\n 'letters long')\n",
"step-4": "#the initial DNA sequence\ndnaSequence = 'ACTGATCGATTACGTATAGTAGAATTCTATCATACATATATATCGATGCGTTCAT'\n\n#seperating the DNA sequence at the specified location\nfirstFragment = 'ACTGATCGATTACGTATAGTAGAATTCTATCATACATATATATCGATGCGTTCAT' [0:22]\nsecondFragment = 'ACTGATCGATTACGTATAGTAGAATTCTATCATACATATATATCGATGCGTTCAT' [23:100]\n\n#finsing the length of the 2 fragments\nfirstFragmentLen = len(firstFragment)\nsecondFragmentLen = len(secondFragment)\n\n#printing the original and the split DNA sequence\nprint(\"the original DNA sequence is\", dnaSequence)\nprint(\"the first fragment is\", firstFragment, \"and is\", firstFragmentLen ,\"letters long\")\nprint(\"the second fragment is\", secondFragment, \"and is\", secondFragmentLen,\"letters long\")\n\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
def main():
args = ['./input']
print('./input', end='')
for x in range(99):
print(' AA', end='')
args.append('AA')
print(args)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def main():
args = ['./input']
print('./input', end='')
for x in range(99):
print(' AA', end='')
args.append('AA')
print(args)
<|reserved_special_token_0|>
if __name__ == '__main__':
main()
<|reserved_special_token_1|>
<|reserved_special_token_0|>
hostname = 'pwnable.kr'
portnum = 2222
username = 'input2'
passwd = 'guest'
def main():
args = ['./input']
print('./input', end='')
for x in range(99):
print(' AA', end='')
args.append('AA')
print(args)
<|reserved_special_token_0|>
if __name__ == '__main__':
main()
<|reserved_special_token_1|>
from pwn import *
hostname = 'pwnable.kr'
portnum = 2222
username = 'input2'
passwd = 'guest'
def main():
args = ['./input']
print('./input', end='')
for x in range(99):
print(' AA', end='')
args.append('AA')
print(args)
<|reserved_special_token_0|>
if __name__ == '__main__':
main()
<|reserved_special_token_1|>
from pwn import *
hostname = "pwnable.kr"
portnum = 2222
username = "input2"
passwd = "guest"
def main():
args = ["./input"]
print("./input", end="")
for x in range(99):
print(" AA", end="")
args.append("AA")
print(args)
'''
s = ssh(host=hostname,
port=portnum,
user=username,
password=passwd)
p = s.process(args)
p.interactive()
'''
if __name__ == "__main__":
main()
|
flexible
|
{
"blob_id": "9184779731d6102498934d77b6d3c0283fc594d9",
"index": 7498,
"step-1": "<mask token>\n\n\ndef main():\n args = ['./input']\n print('./input', end='')\n for x in range(99):\n print(' AA', end='')\n args.append('AA')\n print(args)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef main():\n args = ['./input']\n print('./input', end='')\n for x in range(99):\n print(' AA', end='')\n args.append('AA')\n print(args)\n\n\n<mask token>\nif __name__ == '__main__':\n main()\n",
"step-3": "<mask token>\nhostname = 'pwnable.kr'\nportnum = 2222\nusername = 'input2'\npasswd = 'guest'\n\n\ndef main():\n args = ['./input']\n print('./input', end='')\n for x in range(99):\n print(' AA', end='')\n args.append('AA')\n print(args)\n\n\n<mask token>\nif __name__ == '__main__':\n main()\n",
"step-4": "from pwn import *\nhostname = 'pwnable.kr'\nportnum = 2222\nusername = 'input2'\npasswd = 'guest'\n\n\ndef main():\n args = ['./input']\n print('./input', end='')\n for x in range(99):\n print(' AA', end='')\n args.append('AA')\n print(args)\n\n\n<mask token>\nif __name__ == '__main__':\n main()\n",
"step-5": "from pwn import *\n\nhostname = \"pwnable.kr\"\nportnum = 2222\nusername = \"input2\"\npasswd = \"guest\"\n\ndef main():\n\n args = [\"./input\"]\n print(\"./input\", end=\"\")\n for x in range(99):\n print(\" AA\", end=\"\")\n args.append(\"AA\")\n\n print(args)\n\n'''\n s = ssh(host=hostname,\n port=portnum,\n user=username,\n password=passwd)\n p = s.process(args)\n\n p.interactive()\n'''\n\nif __name__ == \"__main__\":\n main()\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
L = "chaine de caractere"
print("parcours par élément")
for e in L :
print("caractere : *"+e+"*")
|
normal
|
{
"blob_id": "cdc9bc97332a3914415b16f00bc098acc7a02863",
"index": 5020,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('parcours par élément')\nfor e in L:\n print('caractere : *' + e + '*')\n",
"step-3": "L = 'chaine de caractere'\nprint('parcours par élément')\nfor e in L:\n print('caractere : *' + e + '*')\n",
"step-4": "L = \"chaine de caractere\"\nprint(\"parcours par élément\")\nfor e in L :\n print(\"caractere : *\"+e+\"*\")\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class LinkedInGrabber(PageGrabber):
def get_info(self, email):
client = requests.Session()
print('[' + bc.CPRP + '?' + bc.CEND + '] ' + bc.CCYN + 'LinkedIn' +
bc.CEND)
HOMEPAGE_URL = 'https://www.linkedin.com'
LOGIN_URL = 'https://www.linkedin.com/uas/login-submit'
LOGOUT_URL = 'https://www.linkedin.com/m/logout'
source = client.get(HOMEPAGE_URL).content
soup = self.get_dom(source)
csrf = soup.find(id='loginCsrfParam-login')['value']
try:
with open('./storage/fb_login', 'r') as fbinfo:
login_information = json.loads(fbinfo.read())
login_information['loginCsrfParam'] = csrf
except:
login_information = {'session_key': '', 'session_password': '',
'loginCsrfParam': ''}
pass
if not login_information['session_key']:
if login_information['session_password'] == '':
print(' [' + bc.CRED + 'ATTENTION' + bc.CEND + '] ' + bc.
CYLW +
""" This module requires authentication to use it properly.
It will store Credential pairs in plain-text."""
+ bc.CEND)
print(' [' + bc.CRED + 'ATTENTION' + bc.CEND + '] ' + bc.
CYLW +
'This could produce a trail and identify the used account.'
+ bc.CEND)
print()
savecreds = raw_input(
'[{}?{}] {}Would you like to save credentials now? {}(Y/n){}]: '
.format(bc.CRED, bc.CEND, bc.CRED, bc.CYLW, bc.CEND))
print()
luser = raw_input(' [' + bc.CRED + '?' + bc.CEND + '] ' +
bc.CYLW + 'What is your throw-away linkedin username: ' +
bc.CEND)
lpass = raw_input(' [' + bc.CRED + '?' + bc.CEND + '] ' +
bc.CYLW + 'What is your throw-away linkedin password: ' +
bc.CEND)
login_information = {'session_key': luser,
'session_password': lpass, 'loginCsrfParam': csrf}
if str(savecreds).lower() in ['y', 'yes']:
try:
with open('./storage/fb_login', 'w') as fbinfo:
fbinfo.write(json.dumps(login_information))
except Exception as failedtowrite:
print('Failed to write fbinfo to file: %s' %
failedtowrite)
try:
client.post(LOGIN_URL, data=login_information)
results = client.get(
'https://linkedin.com/sales/gmail/profile/viewByEmail/' +
str(email)).text
except Exception as failedlinkedinauth:
print((' [' + bc.CRED + 'X' + bc.CEND + '] ' + bc.CYLW +
'This module did not properly authenticate: %s' + bc.CEND) %
failedlinkedinauth)
soup = self.get_dom(results)
self.get_source(LOGOUT_URL)
try:
profile = soup.find('a', attrs={'class':
'li-hover-under li-txt-black-85'})['href']
print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +
'Profile: ' + bc.CEND + str(profile))
except:
print(' [' + bc.CRED + 'X' + bc.CEND + '] ' + bc.CYLW +
"""No LinkedIn account found.
""" + bc.CEND)
return
try:
fname = soup.find('span', attrs={'id': 'li-profile-name'})[
'data-fname']
lname = soup.find('span', attrs={'id': 'li-profile-name'})[
'data-lname']
name = str(fname) + ' ' + str(lname)
print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +
'Name: ' + bc.CEND + str(fname) + ' ' + str(lname))
except:
name = ''
pass
try:
company = soup.find('span', {'class': 'li-user-title-company'}
).get_text()
print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +
'Company: ' + bc.CEND + str(company))
except:
company = ''
pass
try:
title = soup.find('div', {'class': 'li-user-title'}).get_text()
print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +
'Title: ' + bc.CEND + str(title))
except:
title = ''
pass
try:
location = soup.find('div', {'class': 'li-user-location'}
).get_text()
print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +
'Location: ' + bc.CEND + str(location))
except:
location = ''
pass
try:
email = soup.find('span', {'id': 'email'}).get_text()
print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +
'Email: ' + bc.CEND + str(email))
except:
email = ''
pass
self.info_dict.update({'profile': profile, 'name': name, 'location':
location, 'company': company, 'title': title, 'email': email})
bi.outdata['linkedin'] = self.info_dict
print()
return
<|reserved_special_token_1|>
<|reserved_special_token_0|>
try:
import __builtin__ as bi
except:
import builtins as bi
class LinkedInGrabber(PageGrabber):
def get_info(self, email):
client = requests.Session()
print('[' + bc.CPRP + '?' + bc.CEND + '] ' + bc.CCYN + 'LinkedIn' +
bc.CEND)
HOMEPAGE_URL = 'https://www.linkedin.com'
LOGIN_URL = 'https://www.linkedin.com/uas/login-submit'
LOGOUT_URL = 'https://www.linkedin.com/m/logout'
source = client.get(HOMEPAGE_URL).content
soup = self.get_dom(source)
csrf = soup.find(id='loginCsrfParam-login')['value']
try:
with open('./storage/fb_login', 'r') as fbinfo:
login_information = json.loads(fbinfo.read())
login_information['loginCsrfParam'] = csrf
except:
login_information = {'session_key': '', 'session_password': '',
'loginCsrfParam': ''}
pass
if not login_information['session_key']:
if login_information['session_password'] == '':
print(' [' + bc.CRED + 'ATTENTION' + bc.CEND + '] ' + bc.
CYLW +
""" This module requires authentication to use it properly.
It will store Credential pairs in plain-text."""
+ bc.CEND)
print(' [' + bc.CRED + 'ATTENTION' + bc.CEND + '] ' + bc.
CYLW +
'This could produce a trail and identify the used account.'
+ bc.CEND)
print()
savecreds = raw_input(
'[{}?{}] {}Would you like to save credentials now? {}(Y/n){}]: '
.format(bc.CRED, bc.CEND, bc.CRED, bc.CYLW, bc.CEND))
print()
luser = raw_input(' [' + bc.CRED + '?' + bc.CEND + '] ' +
bc.CYLW + 'What is your throw-away linkedin username: ' +
bc.CEND)
lpass = raw_input(' [' + bc.CRED + '?' + bc.CEND + '] ' +
bc.CYLW + 'What is your throw-away linkedin password: ' +
bc.CEND)
login_information = {'session_key': luser,
'session_password': lpass, 'loginCsrfParam': csrf}
if str(savecreds).lower() in ['y', 'yes']:
try:
with open('./storage/fb_login', 'w') as fbinfo:
fbinfo.write(json.dumps(login_information))
except Exception as failedtowrite:
print('Failed to write fbinfo to file: %s' %
failedtowrite)
try:
client.post(LOGIN_URL, data=login_information)
results = client.get(
'https://linkedin.com/sales/gmail/profile/viewByEmail/' +
str(email)).text
except Exception as failedlinkedinauth:
print((' [' + bc.CRED + 'X' + bc.CEND + '] ' + bc.CYLW +
'This module did not properly authenticate: %s' + bc.CEND) %
failedlinkedinauth)
soup = self.get_dom(results)
self.get_source(LOGOUT_URL)
try:
profile = soup.find('a', attrs={'class':
'li-hover-under li-txt-black-85'})['href']
print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +
'Profile: ' + bc.CEND + str(profile))
except:
print(' [' + bc.CRED + 'X' + bc.CEND + '] ' + bc.CYLW +
"""No LinkedIn account found.
""" + bc.CEND)
return
try:
fname = soup.find('span', attrs={'id': 'li-profile-name'})[
'data-fname']
lname = soup.find('span', attrs={'id': 'li-profile-name'})[
'data-lname']
name = str(fname) + ' ' + str(lname)
print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +
'Name: ' + bc.CEND + str(fname) + ' ' + str(lname))
except:
name = ''
pass
try:
company = soup.find('span', {'class': 'li-user-title-company'}
).get_text()
print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +
'Company: ' + bc.CEND + str(company))
except:
company = ''
pass
try:
title = soup.find('div', {'class': 'li-user-title'}).get_text()
print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +
'Title: ' + bc.CEND + str(title))
except:
title = ''
pass
try:
location = soup.find('div', {'class': 'li-user-location'}
).get_text()
print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +
'Location: ' + bc.CEND + str(location))
except:
location = ''
pass
try:
email = soup.find('span', {'id': 'email'}).get_text()
print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +
'Email: ' + bc.CEND + str(email))
except:
email = ''
pass
self.info_dict.update({'profile': profile, 'name': name, 'location':
location, 'company': company, 'title': title, 'email': email})
bi.outdata['linkedin'] = self.info_dict
print()
return
<|reserved_special_token_1|>
from __future__ import print_function
from __future__ import absolute_import
import requests
from bs4 import BeautifulSoup
import logging
from plugins.base import PageGrabber
from plugins.colors import BodyColors as bc
import json
try:
import __builtin__ as bi
except:
import builtins as bi
class LinkedInGrabber(PageGrabber):
def get_info(self, email):
client = requests.Session()
print('[' + bc.CPRP + '?' + bc.CEND + '] ' + bc.CCYN + 'LinkedIn' +
bc.CEND)
HOMEPAGE_URL = 'https://www.linkedin.com'
LOGIN_URL = 'https://www.linkedin.com/uas/login-submit'
LOGOUT_URL = 'https://www.linkedin.com/m/logout'
source = client.get(HOMEPAGE_URL).content
soup = self.get_dom(source)
csrf = soup.find(id='loginCsrfParam-login')['value']
try:
with open('./storage/fb_login', 'r') as fbinfo:
login_information = json.loads(fbinfo.read())
login_information['loginCsrfParam'] = csrf
except:
login_information = {'session_key': '', 'session_password': '',
'loginCsrfParam': ''}
pass
if not login_information['session_key']:
if login_information['session_password'] == '':
print(' [' + bc.CRED + 'ATTENTION' + bc.CEND + '] ' + bc.
CYLW +
""" This module requires authentication to use it properly.
It will store Credential pairs in plain-text."""
+ bc.CEND)
print(' [' + bc.CRED + 'ATTENTION' + bc.CEND + '] ' + bc.
CYLW +
'This could produce a trail and identify the used account.'
+ bc.CEND)
print()
savecreds = raw_input(
'[{}?{}] {}Would you like to save credentials now? {}(Y/n){}]: '
.format(bc.CRED, bc.CEND, bc.CRED, bc.CYLW, bc.CEND))
print()
luser = raw_input(' [' + bc.CRED + '?' + bc.CEND + '] ' +
bc.CYLW + 'What is your throw-away linkedin username: ' +
bc.CEND)
lpass = raw_input(' [' + bc.CRED + '?' + bc.CEND + '] ' +
bc.CYLW + 'What is your throw-away linkedin password: ' +
bc.CEND)
login_information = {'session_key': luser,
'session_password': lpass, 'loginCsrfParam': csrf}
if str(savecreds).lower() in ['y', 'yes']:
try:
with open('./storage/fb_login', 'w') as fbinfo:
fbinfo.write(json.dumps(login_information))
except Exception as failedtowrite:
print('Failed to write fbinfo to file: %s' %
failedtowrite)
try:
client.post(LOGIN_URL, data=login_information)
results = client.get(
'https://linkedin.com/sales/gmail/profile/viewByEmail/' +
str(email)).text
except Exception as failedlinkedinauth:
print((' [' + bc.CRED + 'X' + bc.CEND + '] ' + bc.CYLW +
'This module did not properly authenticate: %s' + bc.CEND) %
failedlinkedinauth)
soup = self.get_dom(results)
self.get_source(LOGOUT_URL)
try:
profile = soup.find('a', attrs={'class':
'li-hover-under li-txt-black-85'})['href']
print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +
'Profile: ' + bc.CEND + str(profile))
except:
print(' [' + bc.CRED + 'X' + bc.CEND + '] ' + bc.CYLW +
"""No LinkedIn account found.
""" + bc.CEND)
return
try:
fname = soup.find('span', attrs={'id': 'li-profile-name'})[
'data-fname']
lname = soup.find('span', attrs={'id': 'li-profile-name'})[
'data-lname']
name = str(fname) + ' ' + str(lname)
print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +
'Name: ' + bc.CEND + str(fname) + ' ' + str(lname))
except:
name = ''
pass
try:
company = soup.find('span', {'class': 'li-user-title-company'}
).get_text()
print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +
'Company: ' + bc.CEND + str(company))
except:
company = ''
pass
try:
title = soup.find('div', {'class': 'li-user-title'}).get_text()
print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +
'Title: ' + bc.CEND + str(title))
except:
title = ''
pass
try:
location = soup.find('div', {'class': 'li-user-location'}
).get_text()
print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +
'Location: ' + bc.CEND + str(location))
except:
location = ''
pass
try:
email = soup.find('span', {'id': 'email'}).get_text()
print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +
'Email: ' + bc.CEND + str(email))
except:
email = ''
pass
self.info_dict.update({'profile': profile, 'name': name, 'location':
location, 'company': company, 'title': title, 'email': email})
bi.outdata['linkedin'] = self.info_dict
print()
return
<|reserved_special_token_1|>
from __future__ import print_function
from __future__ import absolute_import
#
# LinkedIn Sales Module
#
import requests
from bs4 import BeautifulSoup
import logging
from plugins.base import PageGrabber
from plugins.colors import BodyColors as bc
import json
try:
import __builtin__ as bi
except:
import builtins as bi
class LinkedInGrabber(PageGrabber): # LinkedIN.com sales scraper for email lookups
def get_info(self,email): # Requires AUTH, login and request AUTHENTICATED pages from linkedin
client = requests.Session() # Establish the session()
print("["+bc.CPRP+"?"+bc.CEND+"] "+bc.CCYN + "LinkedIn" + bc.CEND)
HOMEPAGE_URL = 'https://www.linkedin.com' # Set homepage for linkedin
LOGIN_URL = 'https://www.linkedin.com/uas/login-submit' # Set login page for linkedin
LOGOUT_URL = 'https://www.linkedin.com/m/logout'
source = client.get(HOMEPAGE_URL).content # Request source
soup = self.get_dom(source) # BS DOM
csrf = soup.find(id="loginCsrfParam-login")['value']
#
# ATTENTION:: YOU MUST POPULATE THE FOLLOWING WITH YOUR REAL CREDENTIALS
#
# ATTENTION:: THIS WILL NOT WORK PROPRLY OTHERWISE
#
# session_key = email session_password = your password
#
try:
with open('./storage/fb_login', 'r') as fbinfo:
login_information = json.loads(fbinfo.read())
#print(json.loads(login_information))
login_information['loginCsrfParam'] = csrf
except:
login_information = {
'session_key':'',
'session_password':'',
'loginCsrfParam': '',
}
pass
if not login_information['session_key']:
if login_information['session_password'] == '': # If no modifications of default u/p, print error, return
print (" ["+bc.CRED+"ATTENTION"+bc.CEND+"] " + \
bc.CYLW+"\tThis module requires authentication to use it properly.\n\tIt will store Credential pairs in plain-text."+bc.CEND)
print (" ["+bc.CRED+"ATTENTION"+bc.CEND+"] " + \
bc.CYLW + "This could produce a trail and identify the used account."+bc.CEND)
print()
savecreds = raw_input("[{}?{}] {}Would you like to save credentials now? {}(Y/n){}]: ".format(bc.CRED,bc.CEND,bc.CRED,bc.CYLW,bc.CEND))
print()
luser = raw_input(" ["+bc.CRED+"?"+bc.CEND+"] " + \
bc.CYLW+"What is your throw-away linkedin username: "+bc.CEND)
lpass = raw_input(" ["+bc.CRED+"?"+bc.CEND+"] " + \
bc.CYLW+"What is your throw-away linkedin password: "+bc.CEND)
login_information = {
'session_key':luser,
'session_password':lpass,
'loginCsrfParam': csrf,
}
if str(savecreds).lower() in ['y','yes']:
try:
with open('./storage/fb_login','w') as fbinfo:
fbinfo.write(json.dumps(login_information))
except Exception as failedtowrite:
print(("Failed to write fbinfo to file: %s") % failedtowrite)
try:
client.post(LOGIN_URL, data=login_information)
results = client.get('https://linkedin.com/sales/gmail/profile/viewByEmail/'+str(email)).text
except Exception as failedlinkedinauth:
print((" ["+bc.CRED+"X"+bc.CEND+"] " + \
bc.CYLW+"This module did not properly authenticate: %s" + \
bc.CEND) % failedlinkedinauth)
soup = self.get_dom(results)
self.get_source(LOGOUT_URL) # Log out of LinkedIn, kills sessionID
try: # Search and set from results
profile = soup.find('a',attrs={'class': 'li-hover-under li-txt-black-85'})['href']
print(" ["+bc.CGRN+"+"+bc.CEND+"] "+ \
bc.CRED+"Profile: "+bc.CEND + \
str(profile)
)
except:
print(" ["+bc.CRED+"X"+bc.CEND+"] " + \
bc.CYLW+"No LinkedIn account found.\n" + \
bc.CEND
)
return
try:
fname = soup.find('span',attrs={'id': 'li-profile-name'})['data-fname']
lname = soup.find('span',attrs={'id': 'li-profile-name'})['data-lname']
name = str(fname) + " " + str(lname)
print(" ["+bc.CGRN+"+"+bc.CEND+"] " + \
bc.CRED+"Name: " + \
bc.CEND+ str(fname) + \
" " + \
str(lname)
)
except:
name = ""
pass # print (" ["+bc.CRED+"X"+bc.CEND+"] "+bc.CYLW+"No username can be found.\n"+bc.CEND)
try:
company = soup.find('span',{'class': 'li-user-title-company'}).get_text()
print(" ["+bc.CGRN+"+"+bc.CEND+"] " + \
bc.CRED+"Company: " + \
bc.CEND + str(company)
)
except:
company = ""
pass # print (" ["+bc.CRED+"X"+bc.CEND+"] "+bc.CYLW+"No Company can be found.\n"+bc.CEND)
try:
title = soup.find('div',{'class':'li-user-title'}).get_text()
print(" ["+bc.CGRN+"+"+bc.CEND+"] " + \
bc.CRED+"Title: " + \
bc.CEND+\
str(title)
)
except:
title = ""
pass #print (" ["+bc.CRED+"X"+bc.CEND+"] "+bc.CYLW+"No Job Title can be found.\n"+bc.CEND)
try:
location = soup.find('div', {'class':'li-user-location'}).get_text()
print(" ["+bc.CGRN+"+"+bc.CEND+"] "+bc.CRED+"Location: "+bc.CEND+ str(location))
except:
location = ""
pass #print (" ["+bc.CRED+"X"+bc.CEND+"] "+bc.CYLW+"No Location can be found.\n"+bc.CEND)
try:
email = soup.find('span', {'id':'email'}).get_text()
print(" ["+bc.CGRN+"+"+bc.CEND+"] "+bc.CRED+"Email: "+bc.CEND+ str(email))
except:
email =""
pass #print (" ["+bc.CRED+"X"+bc.CEND+"] "+bc.CYLW+"No Email account found.\n"+bc.CEND)
self.info_dict.update({
"profile": profile,
"name": name,
"location": location,
"company": company,
"title":title,
"email":email
})
bi.outdata['linkedin'] = self.info_dict
print()
return
|
flexible
|
{
"blob_id": "570e0d46aa1ea88d1784447e8f693199e3c3b6ad",
"index": 9488,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass LinkedInGrabber(PageGrabber):\n\n def get_info(self, email):\n client = requests.Session()\n print('[' + bc.CPRP + '?' + bc.CEND + '] ' + bc.CCYN + 'LinkedIn' +\n bc.CEND)\n HOMEPAGE_URL = 'https://www.linkedin.com'\n LOGIN_URL = 'https://www.linkedin.com/uas/login-submit'\n LOGOUT_URL = 'https://www.linkedin.com/m/logout'\n source = client.get(HOMEPAGE_URL).content\n soup = self.get_dom(source)\n csrf = soup.find(id='loginCsrfParam-login')['value']\n try:\n with open('./storage/fb_login', 'r') as fbinfo:\n login_information = json.loads(fbinfo.read())\n login_information['loginCsrfParam'] = csrf\n except:\n login_information = {'session_key': '', 'session_password': '',\n 'loginCsrfParam': ''}\n pass\n if not login_information['session_key']:\n if login_information['session_password'] == '':\n print(' [' + bc.CRED + 'ATTENTION' + bc.CEND + '] ' + bc.\n CYLW +\n \"\"\"\tThis module requires authentication to use it properly.\n\tIt will store Credential pairs in plain-text.\"\"\"\n + bc.CEND)\n print(' [' + bc.CRED + 'ATTENTION' + bc.CEND + '] ' + bc.\n CYLW +\n 'This could produce a trail and identify the used account.'\n + bc.CEND)\n print()\n savecreds = raw_input(\n '[{}?{}] {}Would you like to save credentials now? {}(Y/n){}]: '\n .format(bc.CRED, bc.CEND, bc.CRED, bc.CYLW, bc.CEND))\n print()\n luser = raw_input(' [' + bc.CRED + '?' + bc.CEND + '] ' +\n bc.CYLW + 'What is your throw-away linkedin username: ' +\n bc.CEND)\n lpass = raw_input(' [' + bc.CRED + '?' + bc.CEND + '] ' +\n bc.CYLW + 'What is your throw-away linkedin password: ' +\n bc.CEND)\n login_information = {'session_key': luser,\n 'session_password': lpass, 'loginCsrfParam': csrf}\n if str(savecreds).lower() in ['y', 'yes']:\n try:\n with open('./storage/fb_login', 'w') as fbinfo:\n fbinfo.write(json.dumps(login_information))\n except Exception as failedtowrite:\n print('Failed to write fbinfo to file: %s' %\n failedtowrite)\n try:\n client.post(LOGIN_URL, data=login_information)\n results = client.get(\n 'https://linkedin.com/sales/gmail/profile/viewByEmail/' +\n str(email)).text\n except Exception as failedlinkedinauth:\n print((' [' + bc.CRED + 'X' + bc.CEND + '] ' + bc.CYLW +\n 'This module did not properly authenticate: %s' + bc.CEND) %\n failedlinkedinauth)\n soup = self.get_dom(results)\n self.get_source(LOGOUT_URL)\n try:\n profile = soup.find('a', attrs={'class':\n 'li-hover-under li-txt-black-85'})['href']\n print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +\n 'Profile: ' + bc.CEND + str(profile))\n except:\n print(' [' + bc.CRED + 'X' + bc.CEND + '] ' + bc.CYLW +\n \"\"\"No LinkedIn account found.\n\"\"\" + bc.CEND)\n return\n try:\n fname = soup.find('span', attrs={'id': 'li-profile-name'})[\n 'data-fname']\n lname = soup.find('span', attrs={'id': 'li-profile-name'})[\n 'data-lname']\n name = str(fname) + ' ' + str(lname)\n print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +\n 'Name: ' + bc.CEND + str(fname) + ' ' + str(lname))\n except:\n name = ''\n pass\n try:\n company = soup.find('span', {'class': 'li-user-title-company'}\n ).get_text()\n print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +\n 'Company: ' + bc.CEND + str(company))\n except:\n company = ''\n pass\n try:\n title = soup.find('div', {'class': 'li-user-title'}).get_text()\n print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +\n 'Title: ' + bc.CEND + str(title))\n except:\n title = ''\n pass\n try:\n location = soup.find('div', {'class': 'li-user-location'}\n ).get_text()\n print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +\n 'Location: ' + bc.CEND + str(location))\n except:\n location = ''\n pass\n try:\n email = soup.find('span', {'id': 'email'}).get_text()\n print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +\n 'Email: ' + bc.CEND + str(email))\n except:\n email = ''\n pass\n self.info_dict.update({'profile': profile, 'name': name, 'location':\n location, 'company': company, 'title': title, 'email': email})\n bi.outdata['linkedin'] = self.info_dict\n print()\n return\n",
"step-3": "<mask token>\ntry:\n import __builtin__ as bi\nexcept:\n import builtins as bi\n\n\nclass LinkedInGrabber(PageGrabber):\n\n def get_info(self, email):\n client = requests.Session()\n print('[' + bc.CPRP + '?' + bc.CEND + '] ' + bc.CCYN + 'LinkedIn' +\n bc.CEND)\n HOMEPAGE_URL = 'https://www.linkedin.com'\n LOGIN_URL = 'https://www.linkedin.com/uas/login-submit'\n LOGOUT_URL = 'https://www.linkedin.com/m/logout'\n source = client.get(HOMEPAGE_URL).content\n soup = self.get_dom(source)\n csrf = soup.find(id='loginCsrfParam-login')['value']\n try:\n with open('./storage/fb_login', 'r') as fbinfo:\n login_information = json.loads(fbinfo.read())\n login_information['loginCsrfParam'] = csrf\n except:\n login_information = {'session_key': '', 'session_password': '',\n 'loginCsrfParam': ''}\n pass\n if not login_information['session_key']:\n if login_information['session_password'] == '':\n print(' [' + bc.CRED + 'ATTENTION' + bc.CEND + '] ' + bc.\n CYLW +\n \"\"\"\tThis module requires authentication to use it properly.\n\tIt will store Credential pairs in plain-text.\"\"\"\n + bc.CEND)\n print(' [' + bc.CRED + 'ATTENTION' + bc.CEND + '] ' + bc.\n CYLW +\n 'This could produce a trail and identify the used account.'\n + bc.CEND)\n print()\n savecreds = raw_input(\n '[{}?{}] {}Would you like to save credentials now? {}(Y/n){}]: '\n .format(bc.CRED, bc.CEND, bc.CRED, bc.CYLW, bc.CEND))\n print()\n luser = raw_input(' [' + bc.CRED + '?' + bc.CEND + '] ' +\n bc.CYLW + 'What is your throw-away linkedin username: ' +\n bc.CEND)\n lpass = raw_input(' [' + bc.CRED + '?' + bc.CEND + '] ' +\n bc.CYLW + 'What is your throw-away linkedin password: ' +\n bc.CEND)\n login_information = {'session_key': luser,\n 'session_password': lpass, 'loginCsrfParam': csrf}\n if str(savecreds).lower() in ['y', 'yes']:\n try:\n with open('./storage/fb_login', 'w') as fbinfo:\n fbinfo.write(json.dumps(login_information))\n except Exception as failedtowrite:\n print('Failed to write fbinfo to file: %s' %\n failedtowrite)\n try:\n client.post(LOGIN_URL, data=login_information)\n results = client.get(\n 'https://linkedin.com/sales/gmail/profile/viewByEmail/' +\n str(email)).text\n except Exception as failedlinkedinauth:\n print((' [' + bc.CRED + 'X' + bc.CEND + '] ' + bc.CYLW +\n 'This module did not properly authenticate: %s' + bc.CEND) %\n failedlinkedinauth)\n soup = self.get_dom(results)\n self.get_source(LOGOUT_URL)\n try:\n profile = soup.find('a', attrs={'class':\n 'li-hover-under li-txt-black-85'})['href']\n print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +\n 'Profile: ' + bc.CEND + str(profile))\n except:\n print(' [' + bc.CRED + 'X' + bc.CEND + '] ' + bc.CYLW +\n \"\"\"No LinkedIn account found.\n\"\"\" + bc.CEND)\n return\n try:\n fname = soup.find('span', attrs={'id': 'li-profile-name'})[\n 'data-fname']\n lname = soup.find('span', attrs={'id': 'li-profile-name'})[\n 'data-lname']\n name = str(fname) + ' ' + str(lname)\n print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +\n 'Name: ' + bc.CEND + str(fname) + ' ' + str(lname))\n except:\n name = ''\n pass\n try:\n company = soup.find('span', {'class': 'li-user-title-company'}\n ).get_text()\n print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +\n 'Company: ' + bc.CEND + str(company))\n except:\n company = ''\n pass\n try:\n title = soup.find('div', {'class': 'li-user-title'}).get_text()\n print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +\n 'Title: ' + bc.CEND + str(title))\n except:\n title = ''\n pass\n try:\n location = soup.find('div', {'class': 'li-user-location'}\n ).get_text()\n print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +\n 'Location: ' + bc.CEND + str(location))\n except:\n location = ''\n pass\n try:\n email = soup.find('span', {'id': 'email'}).get_text()\n print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +\n 'Email: ' + bc.CEND + str(email))\n except:\n email = ''\n pass\n self.info_dict.update({'profile': profile, 'name': name, 'location':\n location, 'company': company, 'title': title, 'email': email})\n bi.outdata['linkedin'] = self.info_dict\n print()\n return\n",
"step-4": "from __future__ import print_function\nfrom __future__ import absolute_import\nimport requests\nfrom bs4 import BeautifulSoup\nimport logging\nfrom plugins.base import PageGrabber\nfrom plugins.colors import BodyColors as bc\nimport json\ntry:\n import __builtin__ as bi\nexcept:\n import builtins as bi\n\n\nclass LinkedInGrabber(PageGrabber):\n\n def get_info(self, email):\n client = requests.Session()\n print('[' + bc.CPRP + '?' + bc.CEND + '] ' + bc.CCYN + 'LinkedIn' +\n bc.CEND)\n HOMEPAGE_URL = 'https://www.linkedin.com'\n LOGIN_URL = 'https://www.linkedin.com/uas/login-submit'\n LOGOUT_URL = 'https://www.linkedin.com/m/logout'\n source = client.get(HOMEPAGE_URL).content\n soup = self.get_dom(source)\n csrf = soup.find(id='loginCsrfParam-login')['value']\n try:\n with open('./storage/fb_login', 'r') as fbinfo:\n login_information = json.loads(fbinfo.read())\n login_information['loginCsrfParam'] = csrf\n except:\n login_information = {'session_key': '', 'session_password': '',\n 'loginCsrfParam': ''}\n pass\n if not login_information['session_key']:\n if login_information['session_password'] == '':\n print(' [' + bc.CRED + 'ATTENTION' + bc.CEND + '] ' + bc.\n CYLW +\n \"\"\"\tThis module requires authentication to use it properly.\n\tIt will store Credential pairs in plain-text.\"\"\"\n + bc.CEND)\n print(' [' + bc.CRED + 'ATTENTION' + bc.CEND + '] ' + bc.\n CYLW +\n 'This could produce a trail and identify the used account.'\n + bc.CEND)\n print()\n savecreds = raw_input(\n '[{}?{}] {}Would you like to save credentials now? {}(Y/n){}]: '\n .format(bc.CRED, bc.CEND, bc.CRED, bc.CYLW, bc.CEND))\n print()\n luser = raw_input(' [' + bc.CRED + '?' + bc.CEND + '] ' +\n bc.CYLW + 'What is your throw-away linkedin username: ' +\n bc.CEND)\n lpass = raw_input(' [' + bc.CRED + '?' + bc.CEND + '] ' +\n bc.CYLW + 'What is your throw-away linkedin password: ' +\n bc.CEND)\n login_information = {'session_key': luser,\n 'session_password': lpass, 'loginCsrfParam': csrf}\n if str(savecreds).lower() in ['y', 'yes']:\n try:\n with open('./storage/fb_login', 'w') as fbinfo:\n fbinfo.write(json.dumps(login_information))\n except Exception as failedtowrite:\n print('Failed to write fbinfo to file: %s' %\n failedtowrite)\n try:\n client.post(LOGIN_URL, data=login_information)\n results = client.get(\n 'https://linkedin.com/sales/gmail/profile/viewByEmail/' +\n str(email)).text\n except Exception as failedlinkedinauth:\n print((' [' + bc.CRED + 'X' + bc.CEND + '] ' + bc.CYLW +\n 'This module did not properly authenticate: %s' + bc.CEND) %\n failedlinkedinauth)\n soup = self.get_dom(results)\n self.get_source(LOGOUT_URL)\n try:\n profile = soup.find('a', attrs={'class':\n 'li-hover-under li-txt-black-85'})['href']\n print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +\n 'Profile: ' + bc.CEND + str(profile))\n except:\n print(' [' + bc.CRED + 'X' + bc.CEND + '] ' + bc.CYLW +\n \"\"\"No LinkedIn account found.\n\"\"\" + bc.CEND)\n return\n try:\n fname = soup.find('span', attrs={'id': 'li-profile-name'})[\n 'data-fname']\n lname = soup.find('span', attrs={'id': 'li-profile-name'})[\n 'data-lname']\n name = str(fname) + ' ' + str(lname)\n print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +\n 'Name: ' + bc.CEND + str(fname) + ' ' + str(lname))\n except:\n name = ''\n pass\n try:\n company = soup.find('span', {'class': 'li-user-title-company'}\n ).get_text()\n print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +\n 'Company: ' + bc.CEND + str(company))\n except:\n company = ''\n pass\n try:\n title = soup.find('div', {'class': 'li-user-title'}).get_text()\n print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +\n 'Title: ' + bc.CEND + str(title))\n except:\n title = ''\n pass\n try:\n location = soup.find('div', {'class': 'li-user-location'}\n ).get_text()\n print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +\n 'Location: ' + bc.CEND + str(location))\n except:\n location = ''\n pass\n try:\n email = soup.find('span', {'id': 'email'}).get_text()\n print(' [' + bc.CGRN + '+' + bc.CEND + '] ' + bc.CRED +\n 'Email: ' + bc.CEND + str(email))\n except:\n email = ''\n pass\n self.info_dict.update({'profile': profile, 'name': name, 'location':\n location, 'company': company, 'title': title, 'email': email})\n bi.outdata['linkedin'] = self.info_dict\n print()\n return\n",
"step-5": "from __future__ import print_function\nfrom __future__ import absolute_import\n#\n# LinkedIn Sales Module\n#\nimport requests\nfrom bs4 import BeautifulSoup\nimport logging\nfrom plugins.base import PageGrabber\nfrom plugins.colors import BodyColors as bc\nimport json\ntry:\n import __builtin__ as bi\nexcept:\n import builtins as bi\n\n\nclass LinkedInGrabber(PageGrabber): # LinkedIN.com sales scraper for email lookups\n def get_info(self,email): # Requires AUTH, login and request AUTHENTICATED pages from linkedin\n client = requests.Session() # Establish the session()\n print(\"[\"+bc.CPRP+\"?\"+bc.CEND+\"] \"+bc.CCYN + \"LinkedIn\" + bc.CEND)\n HOMEPAGE_URL = 'https://www.linkedin.com' # Set homepage for linkedin\n LOGIN_URL = 'https://www.linkedin.com/uas/login-submit' # Set login page for linkedin\n LOGOUT_URL = 'https://www.linkedin.com/m/logout'\n source = client.get(HOMEPAGE_URL).content # Request source\n soup = self.get_dom(source) # BS DOM\n csrf = soup.find(id=\"loginCsrfParam-login\")['value']\n #\n # ATTENTION:: YOU MUST POPULATE THE FOLLOWING WITH YOUR REAL CREDENTIALS\n #\n # ATTENTION:: THIS WILL NOT WORK PROPRLY OTHERWISE\n #\n # session_key = email session_password = your password\n #\n try:\n with open('./storage/fb_login', 'r') as fbinfo:\n login_information = json.loads(fbinfo.read())\n #print(json.loads(login_information))\n login_information['loginCsrfParam'] = csrf\n except:\n login_information = {\n 'session_key':'',\n 'session_password':'',\n 'loginCsrfParam': '',\n }\n pass\n if not login_information['session_key']:\n if login_information['session_password'] == '': # If no modifications of default u/p, print error, return\n print (\" [\"+bc.CRED+\"ATTENTION\"+bc.CEND+\"] \" + \\\n bc.CYLW+\"\\tThis module requires authentication to use it properly.\\n\\tIt will store Credential pairs in plain-text.\"+bc.CEND)\n print (\" [\"+bc.CRED+\"ATTENTION\"+bc.CEND+\"] \" + \\\n bc.CYLW + \"This could produce a trail and identify the used account.\"+bc.CEND)\n print()\n savecreds = raw_input(\"[{}?{}] {}Would you like to save credentials now? {}(Y/n){}]: \".format(bc.CRED,bc.CEND,bc.CRED,bc.CYLW,bc.CEND))\n print()\n luser = raw_input(\" [\"+bc.CRED+\"?\"+bc.CEND+\"] \" + \\\n bc.CYLW+\"What is your throw-away linkedin username: \"+bc.CEND)\n lpass = raw_input(\" [\"+bc.CRED+\"?\"+bc.CEND+\"] \" + \\\n bc.CYLW+\"What is your throw-away linkedin password: \"+bc.CEND)\n login_information = {\n 'session_key':luser,\n 'session_password':lpass,\n 'loginCsrfParam': csrf,\n }\n if str(savecreds).lower() in ['y','yes']:\n try:\n with open('./storage/fb_login','w') as fbinfo:\n fbinfo.write(json.dumps(login_information))\n except Exception as failedtowrite:\n print((\"Failed to write fbinfo to file: %s\") % failedtowrite)\n try:\n client.post(LOGIN_URL, data=login_information)\n results = client.get('https://linkedin.com/sales/gmail/profile/viewByEmail/'+str(email)).text\n except Exception as failedlinkedinauth:\n print((\" [\"+bc.CRED+\"X\"+bc.CEND+\"] \" + \\\n bc.CYLW+\"This module did not properly authenticate: %s\" + \\\n bc.CEND) % failedlinkedinauth)\n soup = self.get_dom(results)\n self.get_source(LOGOUT_URL) # Log out of LinkedIn, kills sessionID\n try: # Search and set from results\n profile = soup.find('a',attrs={'class': 'li-hover-under li-txt-black-85'})['href']\n print(\" [\"+bc.CGRN+\"+\"+bc.CEND+\"] \"+ \\\n bc.CRED+\"Profile: \"+bc.CEND + \\\n str(profile)\n )\n except:\n print(\" [\"+bc.CRED+\"X\"+bc.CEND+\"] \" + \\\n bc.CYLW+\"No LinkedIn account found.\\n\" + \\\n bc.CEND\n )\n return\n try:\n fname = soup.find('span',attrs={'id': 'li-profile-name'})['data-fname']\n lname = soup.find('span',attrs={'id': 'li-profile-name'})['data-lname']\n name = str(fname) + \" \" + str(lname)\n print(\" [\"+bc.CGRN+\"+\"+bc.CEND+\"] \" + \\\n bc.CRED+\"Name: \" + \\\n bc.CEND+ str(fname) + \\\n \" \" + \\\n str(lname)\n )\n except:\n name = \"\"\n pass # print (\" [\"+bc.CRED+\"X\"+bc.CEND+\"] \"+bc.CYLW+\"No username can be found.\\n\"+bc.CEND)\n try:\n company = soup.find('span',{'class': 'li-user-title-company'}).get_text()\n print(\" [\"+bc.CGRN+\"+\"+bc.CEND+\"] \" + \\\n bc.CRED+\"Company: \" + \\\n bc.CEND + str(company)\n )\n except:\n company = \"\"\n pass # print (\" [\"+bc.CRED+\"X\"+bc.CEND+\"] \"+bc.CYLW+\"No Company can be found.\\n\"+bc.CEND)\n try:\n title = soup.find('div',{'class':'li-user-title'}).get_text()\n print(\" [\"+bc.CGRN+\"+\"+bc.CEND+\"] \" + \\\n bc.CRED+\"Title: \" + \\\n bc.CEND+\\\n str(title)\n )\n except:\n title = \"\"\n pass #print (\" [\"+bc.CRED+\"X\"+bc.CEND+\"] \"+bc.CYLW+\"No Job Title can be found.\\n\"+bc.CEND)\n try:\n location = soup.find('div', {'class':'li-user-location'}).get_text()\n print(\" [\"+bc.CGRN+\"+\"+bc.CEND+\"] \"+bc.CRED+\"Location: \"+bc.CEND+ str(location))\n except:\n location = \"\"\n pass #print (\" [\"+bc.CRED+\"X\"+bc.CEND+\"] \"+bc.CYLW+\"No Location can be found.\\n\"+bc.CEND)\n try:\n email = soup.find('span', {'id':'email'}).get_text()\n print(\" [\"+bc.CGRN+\"+\"+bc.CEND+\"] \"+bc.CRED+\"Email: \"+bc.CEND+ str(email))\n except:\n email =\"\"\n pass #print (\" [\"+bc.CRED+\"X\"+bc.CEND+\"] \"+bc.CYLW+\"No Email account found.\\n\"+bc.CEND)\n self.info_dict.update({\n \"profile\": profile,\n \"name\": name,\n \"location\": location,\n \"company\": company,\n \"title\":title,\n \"email\":email\n })\n bi.outdata['linkedin'] = self.info_dict\n print()\n return\n",
"step-ids": [
0,
2,
3,
4,
5
]
}
|
[
0,
2,
3,
4,
5
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def start():
image_file = 'sample.png'
top_left_corner = [100, 100]
bottom_right_corner = [200, 200]
img = Image.open(image_file)
top_left_x = top_left_corner[0]
top_left_y = top_left_corner[1]
bottom_right_x = bottom_right_corner[0]
bottom_right_y = bottom_right_corner[1]
draw = ImageDraw.Draw(img)
draw.rectangle((top_left_x, top_left_y, bottom_right_x, bottom_right_y),
outline=255)
img.save('preview.png')
grayscale_image = Image.open(image_file).convert('L')
pixel_array = numpy.array(grayscale_image) / 255.0
print(f'Image file: {image_file} , height x width : {pixel_array.shape}')
sub_section = pixel_array[top_left_x:bottom_right_x, top_left_y:
bottom_right_y]
deviation = numpy.std(sub_section)
print(f'Deviation: {deviation}')
print('Done')
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def start():
image_file = 'sample.png'
top_left_corner = [100, 100]
bottom_right_corner = [200, 200]
img = Image.open(image_file)
top_left_x = top_left_corner[0]
top_left_y = top_left_corner[1]
bottom_right_x = bottom_right_corner[0]
bottom_right_y = bottom_right_corner[1]
draw = ImageDraw.Draw(img)
draw.rectangle((top_left_x, top_left_y, bottom_right_x, bottom_right_y),
outline=255)
img.save('preview.png')
grayscale_image = Image.open(image_file).convert('L')
pixel_array = numpy.array(grayscale_image) / 255.0
print(f'Image file: {image_file} , height x width : {pixel_array.shape}')
sub_section = pixel_array[top_left_x:bottom_right_x, top_left_y:
bottom_right_y]
deviation = numpy.std(sub_section)
print(f'Deviation: {deviation}')
print('Done')
if __name__ == '__main__':
start()
<|reserved_special_token_1|>
import numpy
from PIL import Image, ImageDraw
def start():
image_file = 'sample.png'
top_left_corner = [100, 100]
bottom_right_corner = [200, 200]
img = Image.open(image_file)
top_left_x = top_left_corner[0]
top_left_y = top_left_corner[1]
bottom_right_x = bottom_right_corner[0]
bottom_right_y = bottom_right_corner[1]
draw = ImageDraw.Draw(img)
draw.rectangle((top_left_x, top_left_y, bottom_right_x, bottom_right_y),
outline=255)
img.save('preview.png')
grayscale_image = Image.open(image_file).convert('L')
pixel_array = numpy.array(grayscale_image) / 255.0
print(f'Image file: {image_file} , height x width : {pixel_array.shape}')
sub_section = pixel_array[top_left_x:bottom_right_x, top_left_y:
bottom_right_y]
deviation = numpy.std(sub_section)
print(f'Deviation: {deviation}')
print('Done')
if __name__ == '__main__':
start()
<|reserved_special_token_1|>
import numpy
from PIL import Image, ImageDraw
def start():
# ----------------------------
# Set values
# ----------------------------
image_file = 'sample.png'
# Coordinates, where [0,0] is top left corner
top_left_corner = [100, 100] # [x, y]
bottom_right_corner = [200, 200] # [x, y]
# ----------------------------
# ----------------------------
# Preview area
# ----------------------------
img = Image.open(image_file)
top_left_x = top_left_corner[0]
top_left_y = top_left_corner[1]
bottom_right_x = bottom_right_corner[0]
bottom_right_y = bottom_right_corner[1]
draw = ImageDraw.Draw(img)
draw.rectangle((top_left_x, top_left_y, bottom_right_x, bottom_right_y), outline=255)
img.save('preview.png')
# ----------------------------
# ----------------------------
# Calculate deviation
# ----------------------------
grayscale_image = Image.open(image_file).convert('L')
pixel_array = numpy.array(grayscale_image) / 255.0 # normalize
print(f"Image file: {image_file} , height x width : {pixel_array.shape}")
sub_section = pixel_array[top_left_x:bottom_right_x, top_left_y:bottom_right_y]
deviation = numpy.std(sub_section)
print(f"Deviation: {deviation}")
print('Done')
if __name__ == '__main__':
start()
|
flexible
|
{
"blob_id": "84476e1793242bf3bae51263c2db28ff555c25d7",
"index": 1104,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef start():\n image_file = 'sample.png'\n top_left_corner = [100, 100]\n bottom_right_corner = [200, 200]\n img = Image.open(image_file)\n top_left_x = top_left_corner[0]\n top_left_y = top_left_corner[1]\n bottom_right_x = bottom_right_corner[0]\n bottom_right_y = bottom_right_corner[1]\n draw = ImageDraw.Draw(img)\n draw.rectangle((top_left_x, top_left_y, bottom_right_x, bottom_right_y),\n outline=255)\n img.save('preview.png')\n grayscale_image = Image.open(image_file).convert('L')\n pixel_array = numpy.array(grayscale_image) / 255.0\n print(f'Image file: {image_file} , height x width : {pixel_array.shape}')\n sub_section = pixel_array[top_left_x:bottom_right_x, top_left_y:\n bottom_right_y]\n deviation = numpy.std(sub_section)\n print(f'Deviation: {deviation}')\n print('Done')\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef start():\n image_file = 'sample.png'\n top_left_corner = [100, 100]\n bottom_right_corner = [200, 200]\n img = Image.open(image_file)\n top_left_x = top_left_corner[0]\n top_left_y = top_left_corner[1]\n bottom_right_x = bottom_right_corner[0]\n bottom_right_y = bottom_right_corner[1]\n draw = ImageDraw.Draw(img)\n draw.rectangle((top_left_x, top_left_y, bottom_right_x, bottom_right_y),\n outline=255)\n img.save('preview.png')\n grayscale_image = Image.open(image_file).convert('L')\n pixel_array = numpy.array(grayscale_image) / 255.0\n print(f'Image file: {image_file} , height x width : {pixel_array.shape}')\n sub_section = pixel_array[top_left_x:bottom_right_x, top_left_y:\n bottom_right_y]\n deviation = numpy.std(sub_section)\n print(f'Deviation: {deviation}')\n print('Done')\n\n\nif __name__ == '__main__':\n start()\n",
"step-4": "import numpy\nfrom PIL import Image, ImageDraw\n\n\ndef start():\n image_file = 'sample.png'\n top_left_corner = [100, 100]\n bottom_right_corner = [200, 200]\n img = Image.open(image_file)\n top_left_x = top_left_corner[0]\n top_left_y = top_left_corner[1]\n bottom_right_x = bottom_right_corner[0]\n bottom_right_y = bottom_right_corner[1]\n draw = ImageDraw.Draw(img)\n draw.rectangle((top_left_x, top_left_y, bottom_right_x, bottom_right_y),\n outline=255)\n img.save('preview.png')\n grayscale_image = Image.open(image_file).convert('L')\n pixel_array = numpy.array(grayscale_image) / 255.0\n print(f'Image file: {image_file} , height x width : {pixel_array.shape}')\n sub_section = pixel_array[top_left_x:bottom_right_x, top_left_y:\n bottom_right_y]\n deviation = numpy.std(sub_section)\n print(f'Deviation: {deviation}')\n print('Done')\n\n\nif __name__ == '__main__':\n start()\n",
"step-5": "import numpy\nfrom PIL import Image, ImageDraw\n\n\ndef start():\n # ----------------------------\n # Set values\n # ----------------------------\n image_file = 'sample.png'\n # Coordinates, where [0,0] is top left corner\n top_left_corner = [100, 100] # [x, y]\n bottom_right_corner = [200, 200] # [x, y]\n # ----------------------------\n\n # ----------------------------\n # Preview area\n # ----------------------------\n img = Image.open(image_file)\n\n top_left_x = top_left_corner[0]\n top_left_y = top_left_corner[1]\n bottom_right_x = bottom_right_corner[0]\n bottom_right_y = bottom_right_corner[1]\n\n draw = ImageDraw.Draw(img)\n draw.rectangle((top_left_x, top_left_y, bottom_right_x, bottom_right_y), outline=255)\n img.save('preview.png')\n # ----------------------------\n\n # ----------------------------\n # Calculate deviation\n # ----------------------------\n grayscale_image = Image.open(image_file).convert('L')\n pixel_array = numpy.array(grayscale_image) / 255.0 # normalize\n print(f\"Image file: {image_file} , height x width : {pixel_array.shape}\")\n\n sub_section = pixel_array[top_left_x:bottom_right_x, top_left_y:bottom_right_y]\n\n deviation = numpy.std(sub_section)\n\n print(f\"Deviation: {deviation}\")\n\n print('Done')\n\n\nif __name__ == '__main__':\n start()\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
class Table(models.Model):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
class Price(models.Model):
price = models.FloatField(null=True)
class Marketdata(models.Model):
price_change_24h = models.FloatField(null=True)
price_change_percentage_24h = models.FloatField(null=True)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Table(models.Model):
name = models.CharField(max_length=30)
coinid = models.CharField(max_length=30)
symbol = models.CharField(max_length=20)
img = models.CharField(max_length=50)
image = models.CharField(max_length=50)
class Price(models.Model):
price = models.FloatField(null=True)
class Marketdata(models.Model):
price_change_24h = models.FloatField(null=True)
price_change_percentage_24h = models.FloatField(null=True)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class converter(models.Model):
name = models.CharField(max_length=20)
class MainTable(models.Model):
rank = models.IntegerField(null=True)
coinid = models.CharField(max_length=30, null=True)
symbol = models.CharField(max_length=10)
name = models.CharField(max_length=30)
thumbimg = models.CharField(max_length=30)
marketcap = models.FloatField(null=True)
totalvolume = models.FloatField(null=True)
price_change = models.FloatField(null=True)
pricechangepercentage = models.FloatField(null=True)
onehourchange = models.FloatField(null=True)
sevendaychange = models.FloatField(null=True)
circulating_supply = models.FloatField(null=True)
class Table(models.Model):
name = models.CharField(max_length=30)
coinid = models.CharField(max_length=30)
symbol = models.CharField(max_length=20)
img = models.CharField(max_length=50)
image = models.CharField(max_length=50)
class Price(models.Model):
price = models.FloatField(null=True)
class Marketdata(models.Model):
price_change_24h = models.FloatField(null=True)
price_change_percentage_24h = models.FloatField(null=True)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class crontab(models.Model):
name = models.CharField(max_length=20)
class converter(models.Model):
name = models.CharField(max_length=20)
class MainTable(models.Model):
rank = models.IntegerField(null=True)
coinid = models.CharField(max_length=30, null=True)
symbol = models.CharField(max_length=10)
name = models.CharField(max_length=30)
thumbimg = models.CharField(max_length=30)
marketcap = models.FloatField(null=True)
totalvolume = models.FloatField(null=True)
price_change = models.FloatField(null=True)
pricechangepercentage = models.FloatField(null=True)
onehourchange = models.FloatField(null=True)
sevendaychange = models.FloatField(null=True)
circulating_supply = models.FloatField(null=True)
class Table(models.Model):
name = models.CharField(max_length=30)
coinid = models.CharField(max_length=30)
symbol = models.CharField(max_length=20)
img = models.CharField(max_length=50)
image = models.CharField(max_length=50)
class Price(models.Model):
price = models.FloatField(null=True)
class Marketdata(models.Model):
price_change_24h = models.FloatField(null=True)
price_change_percentage_24h = models.FloatField(null=True)
<|reserved_special_token_1|>
from django.db import models
class crontab(models.Model):
name = models.CharField(max_length=20)
class converter(models.Model):
name = models.CharField(max_length=20)
class MainTable(models.Model):
rank = models.IntegerField(null=True)
coinid = models.CharField(max_length=30,null=True)
symbol = models.CharField(max_length=10)
name = models.CharField(max_length=30)
thumbimg = models.CharField(max_length=30)
marketcap = models.FloatField(null=True)
totalvolume = models.FloatField(null=True)
price_change = models.FloatField(null=True)
pricechangepercentage = models.FloatField(null=True)
onehourchange = models.FloatField(null=True)
sevendaychange = models.FloatField(null=True)
circulating_supply = models.FloatField(null=True)
class Table(models.Model):
name = models.CharField(max_length=30)
coinid = models.CharField(max_length=30)
symbol = models.CharField(max_length=20)
img = models.CharField(max_length=50)
image = models.CharField(max_length=50)
class Price(models.Model):
price = models.FloatField(null=True)
class Marketdata(models.Model):
price_change_24h = models.FloatField(null=True)
price_change_percentage_24h = models.FloatField(null=True)
|
flexible
|
{
"blob_id": "0054921928838d9aee63cf58f50a0a01ee12635d",
"index": 6049,
"step-1": "<mask token>\n\n\nclass Table(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Price(models.Model):\n price = models.FloatField(null=True)\n\n\nclass Marketdata(models.Model):\n price_change_24h = models.FloatField(null=True)\n price_change_percentage_24h = models.FloatField(null=True)\n",
"step-2": "<mask token>\n\n\nclass Table(models.Model):\n name = models.CharField(max_length=30)\n coinid = models.CharField(max_length=30)\n symbol = models.CharField(max_length=20)\n img = models.CharField(max_length=50)\n image = models.CharField(max_length=50)\n\n\nclass Price(models.Model):\n price = models.FloatField(null=True)\n\n\nclass Marketdata(models.Model):\n price_change_24h = models.FloatField(null=True)\n price_change_percentage_24h = models.FloatField(null=True)\n",
"step-3": "<mask token>\n\n\nclass converter(models.Model):\n name = models.CharField(max_length=20)\n\n\nclass MainTable(models.Model):\n rank = models.IntegerField(null=True)\n coinid = models.CharField(max_length=30, null=True)\n symbol = models.CharField(max_length=10)\n name = models.CharField(max_length=30)\n thumbimg = models.CharField(max_length=30)\n marketcap = models.FloatField(null=True)\n totalvolume = models.FloatField(null=True)\n price_change = models.FloatField(null=True)\n pricechangepercentage = models.FloatField(null=True)\n onehourchange = models.FloatField(null=True)\n sevendaychange = models.FloatField(null=True)\n circulating_supply = models.FloatField(null=True)\n\n\nclass Table(models.Model):\n name = models.CharField(max_length=30)\n coinid = models.CharField(max_length=30)\n symbol = models.CharField(max_length=20)\n img = models.CharField(max_length=50)\n image = models.CharField(max_length=50)\n\n\nclass Price(models.Model):\n price = models.FloatField(null=True)\n\n\nclass Marketdata(models.Model):\n price_change_24h = models.FloatField(null=True)\n price_change_percentage_24h = models.FloatField(null=True)\n",
"step-4": "<mask token>\n\n\nclass crontab(models.Model):\n name = models.CharField(max_length=20)\n\n\nclass converter(models.Model):\n name = models.CharField(max_length=20)\n\n\nclass MainTable(models.Model):\n rank = models.IntegerField(null=True)\n coinid = models.CharField(max_length=30, null=True)\n symbol = models.CharField(max_length=10)\n name = models.CharField(max_length=30)\n thumbimg = models.CharField(max_length=30)\n marketcap = models.FloatField(null=True)\n totalvolume = models.FloatField(null=True)\n price_change = models.FloatField(null=True)\n pricechangepercentage = models.FloatField(null=True)\n onehourchange = models.FloatField(null=True)\n sevendaychange = models.FloatField(null=True)\n circulating_supply = models.FloatField(null=True)\n\n\nclass Table(models.Model):\n name = models.CharField(max_length=30)\n coinid = models.CharField(max_length=30)\n symbol = models.CharField(max_length=20)\n img = models.CharField(max_length=50)\n image = models.CharField(max_length=50)\n\n\nclass Price(models.Model):\n price = models.FloatField(null=True)\n\n\nclass Marketdata(models.Model):\n price_change_24h = models.FloatField(null=True)\n price_change_percentage_24h = models.FloatField(null=True)\n",
"step-5": "from django.db import models\n\nclass crontab(models.Model):\n name = models.CharField(max_length=20)\n\n\nclass converter(models.Model):\n name = models.CharField(max_length=20)\n\nclass MainTable(models.Model):\n rank = models.IntegerField(null=True)\n coinid = models.CharField(max_length=30,null=True)\n symbol = models.CharField(max_length=10)\n name = models.CharField(max_length=30)\n thumbimg = models.CharField(max_length=30)\n marketcap = models.FloatField(null=True)\n totalvolume = models.FloatField(null=True)\n price_change = models.FloatField(null=True)\n pricechangepercentage = models.FloatField(null=True)\n onehourchange = models.FloatField(null=True)\n sevendaychange = models.FloatField(null=True)\n circulating_supply = models.FloatField(null=True)\n\nclass Table(models.Model):\n name = models.CharField(max_length=30)\n coinid = models.CharField(max_length=30)\n symbol = models.CharField(max_length=20)\n img = models.CharField(max_length=50)\n image = models.CharField(max_length=50)\n\nclass Price(models.Model):\n price = models.FloatField(null=True)\n\nclass Marketdata(models.Model):\n price_change_24h = models.FloatField(null=True)\n price_change_percentage_24h = models.FloatField(null=True)",
"step-ids": [
5,
6,
10,
12,
14
]
}
|
[
5,
6,
10,
12,
14
] |
class Pwm:
def __init__(self, number, path, features):
self.id = number
self.path = path + 'pwm' + number
self.features = features
self.duty = self.get_feature('')
self.enable = self.get_feature('_enable')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
class Pwm:
def __init__(self, number, path, features):
self.id = number
self.path = path + 'pwm' + number
self.features = features
self.duty = self.get_feature('')
self.enable = self.get_feature('_enable')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def __str__(self):
return 'pwm{}'.format(self.id)
<|reserved_special_token_1|>
class Pwm:
def __init__(self, number, path, features):
self.id = number
self.path = path + 'pwm' + number
self.features = features
self.duty = self.get_feature('')
self.enable = self.get_feature('_enable')
def get_feature(self, feature):
return self.features['pwm' + self.id + feature]
<|reserved_special_token_0|>
def __str__(self):
return 'pwm{}'.format(self.id)
<|reserved_special_token_1|>
class Pwm:
def __init__(self, number, path, features):
self.id = number
self.path = path + 'pwm' + number
self.features = features
self.duty = self.get_feature('')
self.enable = self.get_feature('_enable')
def get_feature(self, feature):
return self.features['pwm' + self.id + feature]
def set_feature(self, feature, value=0):
pass
def __str__(self):
return 'pwm{}'.format(self.id)
<|reserved_special_token_1|>
class Pwm():
def __init__(self, number, path, features):
self.id = number
self.path = path + 'pwm' + number
self.features = features
self.duty = self.get_feature('')
self.enable = self.get_feature('_enable')
def get_feature(self, feature):
return self.features['pwm' + self.id + feature]
def set_feature(self, feature, value=0):
pass
def __str__(self):
return 'pwm{}'.format(self.id)
|
flexible
|
{
"blob_id": "c38aff77a7beebc13e7486150d549b876c830db8",
"index": 6104,
"step-1": "class Pwm:\n\n def __init__(self, number, path, features):\n self.id = number\n self.path = path + 'pwm' + number\n self.features = features\n self.duty = self.get_feature('')\n self.enable = self.get_feature('_enable')\n <mask token>\n <mask token>\n <mask token>\n",
"step-2": "class Pwm:\n\n def __init__(self, number, path, features):\n self.id = number\n self.path = path + 'pwm' + number\n self.features = features\n self.duty = self.get_feature('')\n self.enable = self.get_feature('_enable')\n <mask token>\n <mask token>\n\n def __str__(self):\n return 'pwm{}'.format(self.id)\n",
"step-3": "class Pwm:\n\n def __init__(self, number, path, features):\n self.id = number\n self.path = path + 'pwm' + number\n self.features = features\n self.duty = self.get_feature('')\n self.enable = self.get_feature('_enable')\n\n def get_feature(self, feature):\n return self.features['pwm' + self.id + feature]\n <mask token>\n\n def __str__(self):\n return 'pwm{}'.format(self.id)\n",
"step-4": "class Pwm:\n\n def __init__(self, number, path, features):\n self.id = number\n self.path = path + 'pwm' + number\n self.features = features\n self.duty = self.get_feature('')\n self.enable = self.get_feature('_enable')\n\n def get_feature(self, feature):\n return self.features['pwm' + self.id + feature]\n\n def set_feature(self, feature, value=0):\n pass\n\n def __str__(self):\n return 'pwm{}'.format(self.id)\n",
"step-5": "\nclass Pwm():\n\n\tdef __init__(self, number, path, features):\n\t\tself.id = number\n\t\tself.path = path + 'pwm' + number\n\t\tself.features = features\n\t\tself.duty = self.get_feature('')\n\t\tself.enable = self.get_feature('_enable')\n\n\tdef get_feature(self, feature):\n\t\treturn self.features['pwm' + self.id + feature]\n\n\tdef set_feature(self, feature, value=0):\n\t\tpass\n\n\tdef __str__(self):\n\t\treturn 'pwm{}'.format(self.id)",
"step-ids": [
2,
3,
4,
5,
6
]
}
|
[
2,
3,
4,
5,
6
] |
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))
|
normal
|
{
"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|>
if list_1 == list_1_rev:
print('You entered a polindrom!')
else:
print('Your string is not a polindrom')
<|reserved_special_token_1|>
list_1 = input('Enter something: ')
list_1_rev = list_1[::-1]
if list_1 == list_1_rev:
print('You entered a polindrom!')
else:
print('Your string is not a polindrom')
<|reserved_special_token_1|>
#Проверяем, является ли введенная пользователем строка полиндромом
list_1 = input('Enter something: ')
list_1_rev = list_1[::-1]
if list_1 == list_1_rev:
print('You entered a polindrom!')
else: print('Your string is not a polindrom')
|
flexible
|
{
"blob_id": "45b56103db0a72ebbc7de340c4293e1f70552414",
"index": 5254,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif list_1 == list_1_rev:\n print('You entered a polindrom!')\nelse:\n print('Your string is not a polindrom')\n",
"step-3": "list_1 = input('Enter something: ')\nlist_1_rev = list_1[::-1]\nif list_1 == list_1_rev:\n print('You entered a polindrom!')\nelse:\n print('Your string is not a polindrom')\n",
"step-4": "#Проверяем, является ли введенная пользователем строка полиндромом\r\n\r\nlist_1 = input('Enter something: ')\r\nlist_1_rev = list_1[::-1]\r\n\r\nif list_1 == list_1_rev:\r\n print('You entered a polindrom!')\r\nelse: print('Your string is not a polindrom')\r\n\r\n\r\n\r\n\r\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
# -*- coding: utf-8 -*-
import serial
import time
import argparse
def write_command(serial, comm, verbose = False, dt = None):
""" Encodes a command and sends it over the serial port """
if verbose and comm != "":
if dt is None:
print("{} \t\t-> {}".format(comm, serial.port))
else:
print("{} \t\t-> {} at {:2.3f} ms".format(comm, serial.port, dt))
serial.write(comm.encode())
def read_buffer(serial):
""" Reads the serial port bufer and decodes it """
resp = serial.read_all()
return resp.decode()
def read_and_print(serial):
""" Obtains serial responser and prints it if it's not empty """
resp = read_buffer(serial)
if resp != "":
print(resp)
def runcommands(cs, ts, ps, serials, verbose = False, profiling = False):
""" Runs a series of commands at certain specified times """
if len(ts) == len(cs):
i = 0
t0 = time.time()
dt = time.time() - t0 # elapsed time
while i < len(cs):
ser = serials[ps[i]]
comm = cs[i]
t = ts[i]
while (dt - t) < 0.0005:
dt = time.time() - t0
if verbose: read_and_print(ser)
if profiling:
write_command(ser, comm, verbose, dt)
else:
write_command(ser, comm, verbose)
i += 1
else:
print('Error: Lists are not equally long. ')
def load_csv(f):
delimiter = ','
ts = []
cs = []
ps = []
for l in f.readlines():
values = l.strip("\n").split(delimiter)
ts.append(float(values[0]))
cs.append(values[1])
if len(values) <= 3: # if there isn't a third field
values.append("") # add an empty one
p = values[2].strip(" ") # take all spaces out
if p == "":
ps.append(ps[-1]) # use previous one if it's empty
else:
ps.append(p)
return ts, cs, ps
# Create argument parser
parser = argparse.ArgumentParser(description='sends a series of commands over the serial port')
parser.add_argument('filename',
type=str, help='CSV file with columns for time, commands and ports')
parser.add_argument('-r', '--reps', required = False, default=1,
type=int, help='Number of command sequence repetitions (default: %(default)s)')
parser.add_argument('-bd', '--baudrate', required = False, default=38400,
type=int, help='Baudrate (default: %(default)s)')
parser.add_argument('-v', '--verbose', required = False,
action='store_true',
help='Print Commands as they are sent (default: %(default)s)')
parser.add_argument('-p', '--profiling', required = False,
action='store_true',
help='Show profiling information if verbose (default: %(default)s).')
# Get parameters
args = parser.parse_args()
#print(args.filename)
#print(args.reps)
#print(args.baudrate)
#print(args.verbose)
#print(args.profiling)
# Parameters
fname = args.filename
reps = args.reps
baudrate = args.baudrate
verbose = args.verbose
profiling = args.profiling
# test.csv -r 2 -b 38400 -v -p
#fname = 'test.csv'
#reps = 2
#baudrate = 38400
#verbose = True
#profiling = True
try:
f = open(fname, 'r')
ts, cs, ps = load_csv(f)
# Repeat all lists the specified number of times
ts_rep = [] # offset each rep's times
for r in range(reps):
for t in ts:
ts_rep.append(t + ts[-1]*r)
cs_rep = cs*reps
ps_reps = ps*reps
# Try to open the serial port connections and run the commands
try:
# Get list of unique portnames
ports = list(set(ps))
serials = {} # serial connections
for port in ports:
ser = serial.Serial(port = port,
baudrate=baudrate,
write_timeout=0,
bytesize=serial.EIGHTBITS,
stopbits=serial.STOPBITS_ONE,
parity=serial.PARITY_NONE)
serials[port] = ser
runcommands(cs_rep, ts_rep, ps_reps, serials, verbose, profiling)
finally:
time.sleep(0.5)
for ser in serials.values():
ser.close()
finally:
f.close()
|
normal
|
{
"blob_id": "3ffcab4b36c6ca05f1e667c628ebb873ebdc0d25",
"index": 7866,
"step-1": "<mask token>\n\n\ndef write_command(serial, comm, verbose=False, dt=None):\n \"\"\" Encodes a command and sends it over the serial port \"\"\"\n if verbose and comm != '':\n if dt is None:\n print('{} \\t\\t-> {}'.format(comm, serial.port))\n else:\n print('{} \\t\\t-> {} at {:2.3f} ms'.format(comm, serial.port, dt))\n serial.write(comm.encode())\n\n\ndef read_buffer(serial):\n \"\"\" Reads the serial port bufer and decodes it \"\"\"\n resp = serial.read_all()\n return resp.decode()\n\n\ndef read_and_print(serial):\n \"\"\" Obtains serial responser and prints it if it's not empty \"\"\"\n resp = read_buffer(serial)\n if resp != '':\n print(resp)\n\n\ndef runcommands(cs, ts, ps, serials, verbose=False, profiling=False):\n \"\"\" Runs a series of commands at certain specified times \"\"\"\n if len(ts) == len(cs):\n i = 0\n t0 = time.time()\n dt = time.time() - t0\n while i < len(cs):\n ser = serials[ps[i]]\n comm = cs[i]\n t = ts[i]\n while dt - t < 0.0005:\n dt = time.time() - t0\n if verbose:\n read_and_print(ser)\n if profiling:\n write_command(ser, comm, verbose, dt)\n else:\n write_command(ser, comm, verbose)\n i += 1\n else:\n print('Error: Lists are not equally long. ')\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef write_command(serial, comm, verbose=False, dt=None):\n \"\"\" Encodes a command and sends it over the serial port \"\"\"\n if verbose and comm != '':\n if dt is None:\n print('{} \\t\\t-> {}'.format(comm, serial.port))\n else:\n print('{} \\t\\t-> {} at {:2.3f} ms'.format(comm, serial.port, dt))\n serial.write(comm.encode())\n\n\ndef read_buffer(serial):\n \"\"\" Reads the serial port bufer and decodes it \"\"\"\n resp = serial.read_all()\n return resp.decode()\n\n\ndef read_and_print(serial):\n \"\"\" Obtains serial responser and prints it if it's not empty \"\"\"\n resp = read_buffer(serial)\n if resp != '':\n print(resp)\n\n\ndef runcommands(cs, ts, ps, serials, verbose=False, profiling=False):\n \"\"\" Runs a series of commands at certain specified times \"\"\"\n if len(ts) == len(cs):\n i = 0\n t0 = time.time()\n dt = time.time() - t0\n while i < len(cs):\n ser = serials[ps[i]]\n comm = cs[i]\n t = ts[i]\n while dt - t < 0.0005:\n dt = time.time() - t0\n if verbose:\n read_and_print(ser)\n if profiling:\n write_command(ser, comm, verbose, dt)\n else:\n write_command(ser, comm, verbose)\n i += 1\n else:\n print('Error: Lists are not equally long. ')\n\n\ndef load_csv(f):\n delimiter = ','\n ts = []\n cs = []\n ps = []\n for l in f.readlines():\n values = l.strip('\\n').split(delimiter)\n ts.append(float(values[0]))\n cs.append(values[1])\n if len(values) <= 3:\n values.append('')\n p = values[2].strip(' ')\n if p == '':\n ps.append(ps[-1])\n else:\n ps.append(p)\n return ts, cs, ps\n\n\n<mask token>\nparser.add_argument('filename', type=str, help=\n 'CSV file with columns for time, commands and ports')\nparser.add_argument('-r', '--reps', required=False, default=1, type=int,\n help='Number of command sequence repetitions (default: %(default)s)')\nparser.add_argument('-bd', '--baudrate', required=False, default=38400,\n type=int, help='Baudrate (default: %(default)s)')\nparser.add_argument('-v', '--verbose', required=False, action='store_true',\n help='Print Commands as they are sent (default: %(default)s)')\nparser.add_argument('-p', '--profiling', required=False, action=\n 'store_true', help=\n 'Show profiling information if verbose (default: %(default)s).')\n<mask token>\ntry:\n f = open(fname, 'r')\n ts, cs, ps = load_csv(f)\n ts_rep = []\n for r in range(reps):\n for t in ts:\n ts_rep.append(t + ts[-1] * r)\n cs_rep = cs * reps\n ps_reps = ps * reps\n try:\n ports = list(set(ps))\n serials = {}\n for port in ports:\n ser = serial.Serial(port=port, baudrate=baudrate, write_timeout\n =0, bytesize=serial.EIGHTBITS, stopbits=serial.STOPBITS_ONE,\n parity=serial.PARITY_NONE)\n serials[port] = ser\n runcommands(cs_rep, ts_rep, ps_reps, serials, verbose, profiling)\n finally:\n time.sleep(0.5)\n for ser in serials.values():\n ser.close()\nfinally:\n f.close()\n",
"step-3": "<mask token>\n\n\ndef write_command(serial, comm, verbose=False, dt=None):\n \"\"\" Encodes a command and sends it over the serial port \"\"\"\n if verbose and comm != '':\n if dt is None:\n print('{} \\t\\t-> {}'.format(comm, serial.port))\n else:\n print('{} \\t\\t-> {} at {:2.3f} ms'.format(comm, serial.port, dt))\n serial.write(comm.encode())\n\n\ndef read_buffer(serial):\n \"\"\" Reads the serial port bufer and decodes it \"\"\"\n resp = serial.read_all()\n return resp.decode()\n\n\ndef read_and_print(serial):\n \"\"\" Obtains serial responser and prints it if it's not empty \"\"\"\n resp = read_buffer(serial)\n if resp != '':\n print(resp)\n\n\ndef runcommands(cs, ts, ps, serials, verbose=False, profiling=False):\n \"\"\" Runs a series of commands at certain specified times \"\"\"\n if len(ts) == len(cs):\n i = 0\n t0 = time.time()\n dt = time.time() - t0\n while i < len(cs):\n ser = serials[ps[i]]\n comm = cs[i]\n t = ts[i]\n while dt - t < 0.0005:\n dt = time.time() - t0\n if verbose:\n read_and_print(ser)\n if profiling:\n write_command(ser, comm, verbose, dt)\n else:\n write_command(ser, comm, verbose)\n i += 1\n else:\n print('Error: Lists are not equally long. ')\n\n\ndef load_csv(f):\n delimiter = ','\n ts = []\n cs = []\n ps = []\n for l in f.readlines():\n values = l.strip('\\n').split(delimiter)\n ts.append(float(values[0]))\n cs.append(values[1])\n if len(values) <= 3:\n values.append('')\n p = values[2].strip(' ')\n if p == '':\n ps.append(ps[-1])\n else:\n ps.append(p)\n return ts, cs, ps\n\n\nparser = argparse.ArgumentParser(description=\n 'sends a series of commands over the serial port')\nparser.add_argument('filename', type=str, help=\n 'CSV file with columns for time, commands and ports')\nparser.add_argument('-r', '--reps', required=False, default=1, type=int,\n help='Number of command sequence repetitions (default: %(default)s)')\nparser.add_argument('-bd', '--baudrate', required=False, default=38400,\n type=int, help='Baudrate (default: %(default)s)')\nparser.add_argument('-v', '--verbose', required=False, action='store_true',\n help='Print Commands as they are sent (default: %(default)s)')\nparser.add_argument('-p', '--profiling', required=False, action=\n 'store_true', help=\n 'Show profiling information if verbose (default: %(default)s).')\nargs = parser.parse_args()\nfname = args.filename\nreps = args.reps\nbaudrate = args.baudrate\nverbose = args.verbose\nprofiling = args.profiling\ntry:\n f = open(fname, 'r')\n ts, cs, ps = load_csv(f)\n ts_rep = []\n for r in range(reps):\n for t in ts:\n ts_rep.append(t + ts[-1] * r)\n cs_rep = cs * reps\n ps_reps = ps * reps\n try:\n ports = list(set(ps))\n serials = {}\n for port in ports:\n ser = serial.Serial(port=port, baudrate=baudrate, write_timeout\n =0, bytesize=serial.EIGHTBITS, stopbits=serial.STOPBITS_ONE,\n parity=serial.PARITY_NONE)\n serials[port] = ser\n runcommands(cs_rep, ts_rep, ps_reps, serials, verbose, profiling)\n finally:\n time.sleep(0.5)\n for ser in serials.values():\n ser.close()\nfinally:\n f.close()\n",
"step-4": "import serial\nimport time\nimport argparse\n\n\ndef write_command(serial, comm, verbose=False, dt=None):\n \"\"\" Encodes a command and sends it over the serial port \"\"\"\n if verbose and comm != '':\n if dt is None:\n print('{} \\t\\t-> {}'.format(comm, serial.port))\n else:\n print('{} \\t\\t-> {} at {:2.3f} ms'.format(comm, serial.port, dt))\n serial.write(comm.encode())\n\n\ndef read_buffer(serial):\n \"\"\" Reads the serial port bufer and decodes it \"\"\"\n resp = serial.read_all()\n return resp.decode()\n\n\ndef read_and_print(serial):\n \"\"\" Obtains serial responser and prints it if it's not empty \"\"\"\n resp = read_buffer(serial)\n if resp != '':\n print(resp)\n\n\ndef runcommands(cs, ts, ps, serials, verbose=False, profiling=False):\n \"\"\" Runs a series of commands at certain specified times \"\"\"\n if len(ts) == len(cs):\n i = 0\n t0 = time.time()\n dt = time.time() - t0\n while i < len(cs):\n ser = serials[ps[i]]\n comm = cs[i]\n t = ts[i]\n while dt - t < 0.0005:\n dt = time.time() - t0\n if verbose:\n read_and_print(ser)\n if profiling:\n write_command(ser, comm, verbose, dt)\n else:\n write_command(ser, comm, verbose)\n i += 1\n else:\n print('Error: Lists are not equally long. ')\n\n\ndef load_csv(f):\n delimiter = ','\n ts = []\n cs = []\n ps = []\n for l in f.readlines():\n values = l.strip('\\n').split(delimiter)\n ts.append(float(values[0]))\n cs.append(values[1])\n if len(values) <= 3:\n values.append('')\n p = values[2].strip(' ')\n if p == '':\n ps.append(ps[-1])\n else:\n ps.append(p)\n return ts, cs, ps\n\n\nparser = argparse.ArgumentParser(description=\n 'sends a series of commands over the serial port')\nparser.add_argument('filename', type=str, help=\n 'CSV file with columns for time, commands and ports')\nparser.add_argument('-r', '--reps', required=False, default=1, type=int,\n help='Number of command sequence repetitions (default: %(default)s)')\nparser.add_argument('-bd', '--baudrate', required=False, default=38400,\n type=int, help='Baudrate (default: %(default)s)')\nparser.add_argument('-v', '--verbose', required=False, action='store_true',\n help='Print Commands as they are sent (default: %(default)s)')\nparser.add_argument('-p', '--profiling', required=False, action=\n 'store_true', help=\n 'Show profiling information if verbose (default: %(default)s).')\nargs = parser.parse_args()\nfname = args.filename\nreps = args.reps\nbaudrate = args.baudrate\nverbose = args.verbose\nprofiling = args.profiling\ntry:\n f = open(fname, 'r')\n ts, cs, ps = load_csv(f)\n ts_rep = []\n for r in range(reps):\n for t in ts:\n ts_rep.append(t + ts[-1] * r)\n cs_rep = cs * reps\n ps_reps = ps * reps\n try:\n ports = list(set(ps))\n serials = {}\n for port in ports:\n ser = serial.Serial(port=port, baudrate=baudrate, write_timeout\n =0, bytesize=serial.EIGHTBITS, stopbits=serial.STOPBITS_ONE,\n parity=serial.PARITY_NONE)\n serials[port] = ser\n runcommands(cs_rep, ts_rep, ps_reps, serials, verbose, profiling)\n finally:\n time.sleep(0.5)\n for ser in serials.values():\n ser.close()\nfinally:\n f.close()\n",
"step-5": "# -*- coding: utf-8 -*-\r\n\r\nimport serial\r\nimport time\r\nimport argparse\r\n\r\n \r\ndef write_command(serial, comm, verbose = False, dt = None):\r\n \"\"\" Encodes a command and sends it over the serial port \"\"\"\r\n if verbose and comm != \"\":\r\n if dt is None:\r\n print(\"{} \\t\\t-> {}\".format(comm, serial.port))\r\n else:\r\n print(\"{} \\t\\t-> {} at {:2.3f} ms\".format(comm, serial.port, dt))\r\n serial.write(comm.encode())\r\n \r\ndef read_buffer(serial):\r\n \"\"\" Reads the serial port bufer and decodes it \"\"\"\r\n resp = serial.read_all()\r\n return resp.decode()\r\n\r\ndef read_and_print(serial):\r\n \"\"\" Obtains serial responser and prints it if it's not empty \"\"\"\r\n resp = read_buffer(serial)\r\n if resp != \"\":\r\n print(resp)\r\n \r\n\r\ndef runcommands(cs, ts, ps, serials, verbose = False, profiling = False):\r\n \"\"\" Runs a series of commands at certain specified times \"\"\"\r\n if len(ts) == len(cs):\r\n i = 0\r\n t0 = time.time()\r\n dt = time.time() - t0 # elapsed time\r\n while i < len(cs):\r\n ser = serials[ps[i]]\r\n comm = cs[i]\r\n t = ts[i]\r\n while (dt - t) < 0.0005:\r\n dt = time.time() - t0\r\n if verbose: read_and_print(ser)\r\n if profiling:\r\n write_command(ser, comm, verbose, dt)\r\n else:\r\n write_command(ser, comm, verbose)\r\n i += 1\r\n else:\r\n print('Error: Lists are not equally long. ')\r\n\r\n\r\ndef load_csv(f):\r\n delimiter = ','\r\n ts = []\r\n cs = []\r\n ps = []\r\n for l in f.readlines():\r\n values = l.strip(\"\\n\").split(delimiter)\r\n ts.append(float(values[0]))\r\n cs.append(values[1])\r\n if len(values) <= 3: # if there isn't a third field\r\n values.append(\"\") # add an empty one\r\n p = values[2].strip(\" \") # take all spaces out\r\n if p == \"\": \r\n ps.append(ps[-1]) # use previous one if it's empty\r\n else:\r\n ps.append(p)\r\n return ts, cs, ps\r\n\r\n# Create argument parser\r\n \r\nparser = argparse.ArgumentParser(description='sends a series of commands over the serial port')\r\nparser.add_argument('filename',\r\n type=str, help='CSV file with columns for time, commands and ports')\r\nparser.add_argument('-r', '--reps', required = False, default=1,\r\n type=int, help='Number of command sequence repetitions (default: %(default)s)')\r\nparser.add_argument('-bd', '--baudrate', required = False, default=38400,\r\n type=int, help='Baudrate (default: %(default)s)')\r\nparser.add_argument('-v', '--verbose', required = False,\r\n action='store_true',\r\n help='Print Commands as they are sent (default: %(default)s)')\r\nparser.add_argument('-p', '--profiling', required = False,\r\n action='store_true',\r\n help='Show profiling information if verbose (default: %(default)s).')\r\n \r\n# Get parameters\r\nargs = parser.parse_args()\r\n#print(args.filename)\r\n#print(args.reps)\r\n#print(args.baudrate)\r\n#print(args.verbose)\r\n#print(args.profiling)\r\n\r\n# Parameters\r\nfname = args.filename\r\nreps = args.reps\r\nbaudrate = args.baudrate\r\nverbose = args.verbose\r\nprofiling = args.profiling\r\n\r\n# test.csv -r 2 -b 38400 -v -p\r\n#fname = 'test.csv'\r\n#reps = 2\r\n#baudrate = 38400\r\n#verbose = True\r\n#profiling = True\r\ntry: \r\n f = open(fname, 'r')\r\n ts, cs, ps = load_csv(f)\r\n\r\n # Repeat all lists the specified number of times\r\n ts_rep = [] # offset each rep's times\r\n for r in range(reps):\r\n for t in ts:\r\n ts_rep.append(t + ts[-1]*r)\r\n cs_rep = cs*reps\r\n ps_reps = ps*reps\r\n \r\n # Try to open the serial port connections and run the commands\r\n\r\n try:\r\n # Get list of unique portnames\r\n ports = list(set(ps))\r\n serials = {} # serial connections\r\n for port in ports:\r\n ser = serial.Serial(port = port, \r\n baudrate=baudrate,\r\n write_timeout=0,\r\n bytesize=serial.EIGHTBITS,\r\n stopbits=serial.STOPBITS_ONE,\r\n parity=serial.PARITY_NONE)\r\n serials[port] = ser\r\n runcommands(cs_rep, ts_rep, ps_reps, serials, verbose, profiling)\r\n finally:\r\n time.sleep(0.5)\r\n for ser in serials.values():\r\n ser.close()\r\nfinally:\r\n f.close()",
"step-ids": [
4,
6,
7,
8,
9
]
}
|
[
4,
6,
7,
8,
9
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def change():
name = 'Brill'
print(name)
print(locals())
print(globals())
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def change():
name = 'Brill'
print(name)
print(locals())
print(globals())
change()
print(name)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
name = 'henggao'
def change():
name = 'Brill'
print(name)
print(locals())
print(globals())
change()
print(name)
<|reserved_special_token_1|>
'''
@Description:
@Version: 1.0
@Autor: Henggao
@Date: 2020-02-20 16:17:05
@LastEditors: Henggao
@LastEditTime: 2020-02-20 16:32:45
'''
name = "henggao"
def change():
name = "Brill"
print(name)
print(locals())
print(globals())
change()
print(name)
|
flexible
|
{
"blob_id": "6c7162a9bd81d618abda204c24031c5a5acc61b4",
"index": 7967,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef change():\n name = 'Brill'\n print(name)\n print(locals())\n print(globals())\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef change():\n name = 'Brill'\n print(name)\n print(locals())\n print(globals())\n\n\nchange()\nprint(name)\n",
"step-4": "<mask token>\nname = 'henggao'\n\n\ndef change():\n name = 'Brill'\n print(name)\n print(locals())\n print(globals())\n\n\nchange()\nprint(name)\n",
"step-5": "'''\n@Description: \n@Version: 1.0\n@Autor: Henggao\n@Date: 2020-02-20 16:17:05\n@LastEditors: Henggao\n@LastEditTime: 2020-02-20 16:32:45\n'''\nname = \"henggao\"\ndef change():\n name = \"Brill\"\n print(name)\n print(locals())\n print(globals())\n \nchange() \n\nprint(name)",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
# Generated by Django 3.0.4 on 2020-03-24 16:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('students', '0002_auto_20200324_1635'),
]
operations = [
migrations.AddField(
model_name='student',
name='parent_mobile',
field=models.CharField(max_length=100, null=True),
),
]
|
normal
|
{
"blob_id": "a372289d15b55f43887a37bb78a9fc308ddd0371",
"index": 5582,
"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 = [('students', '0002_auto_20200324_1635')]\n operations = [migrations.AddField(model_name='student', name=\n 'parent_mobile', field=models.CharField(max_length=100, null=True))]\n",
"step-4": "from django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('students', '0002_auto_20200324_1635')]\n operations = [migrations.AddField(model_name='student', name=\n 'parent_mobile', field=models.CharField(max_length=100, null=True))]\n",
"step-5": "# Generated by Django 3.0.4 on 2020-03-24 16:58\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('students', '0002_auto_20200324_1635'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='student',\n name='parent_mobile',\n field=models.CharField(max_length=100, null=True),\n ),\n ]\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
"""MPI-supported kernels for computing diffusion flux in 2D."""
from sopht.numeric.eulerian_grid_ops.stencil_ops_2d import (
gen_diffusion_flux_pyst_kernel_2d,
gen_set_fixed_val_pyst_kernel_2d,
)
from sopht_mpi.utils.mpi_utils import check_valid_ghost_size_and_kernel_support
from mpi4py import MPI
def gen_diffusion_flux_pyst_mpi_kernel_2d(
real_t, mpi_construct, ghost_exchange_communicator
):
# Note currently I'm generating these for arbit size arrays, we ca optimise this
# more by generating fixed size for the interior stencil and arbit size for
# boundary crunching
diffusion_flux_pyst_kernel = gen_diffusion_flux_pyst_kernel_2d(
real_t=real_t, reset_ghost_zone=False
)
kernel_support = 1
# define this here so that ghost size and kernel support is checked during
# generation phase itself
gen_diffusion_flux_pyst_mpi_kernel_2d.kernel_support = kernel_support
check_valid_ghost_size_and_kernel_support(
ghost_size=ghost_exchange_communicator.ghost_size,
kernel_support=gen_diffusion_flux_pyst_mpi_kernel_2d.kernel_support,
)
# for setting values at physical domain boundary
y_next, x_next = mpi_construct.next_grid_along
y_previous, x_previous = mpi_construct.previous_grid_along
set_fixed_val_kernel_2d = gen_set_fixed_val_pyst_kernel_2d(real_t=real_t)
def diffusion_flux_pyst_mpi_kernel_2d(
diffusion_flux,
field,
prefactor,
):
# define kernel support for kernel
diffusion_flux_pyst_mpi_kernel_2d.kernel_support = (
gen_diffusion_flux_pyst_mpi_kernel_2d.kernel_support
)
# define variable for use later
ghost_size = ghost_exchange_communicator.ghost_size
# begin ghost comm.
ghost_exchange_communicator.exchange_scalar_field_init(field)
# crunch interior stencil
diffusion_flux_pyst_kernel(
diffusion_flux=diffusion_flux[
ghost_size:-ghost_size, ghost_size:-ghost_size
],
field=field[ghost_size:-ghost_size, ghost_size:-ghost_size],
prefactor=prefactor,
)
# finalise ghost comm.
ghost_exchange_communicator.exchange_finalise()
# crunch boundary numbers
# NOTE: we pass in arrays of width 3 * kernel support size because the
# interior stencil computation leaves out a width of kernel_support.
# Since the support needed by the kernel is kernel_support on each side,
# we need to pass an array of width 3 * kernel_support, starting from
# index +/-(ghost_size - kernel_support) on the lower and upper end.
# Pystencils then automatically sets the kernel comp. bounds and
# crunches numbers in the kernel_support thickness zone at the boundary.
# Start of Y axis
diffusion_flux_pyst_kernel(
diffusion_flux=diffusion_flux[
ghost_size - kernel_support : ghost_size + 2 * kernel_support,
ghost_size:-ghost_size,
],
field=field[
ghost_size - kernel_support : ghost_size + 2 * kernel_support,
ghost_size:-ghost_size,
],
prefactor=prefactor,
)
# End of Y axis
diffusion_flux_pyst_kernel(
diffusion_flux=diffusion_flux[
-(ghost_size + 2 * kernel_support) : field.shape[0]
- (ghost_size - kernel_support),
ghost_size:-ghost_size,
],
field=field[
-(ghost_size + 2 * kernel_support) : field.shape[0]
- (ghost_size - kernel_support),
ghost_size:-ghost_size,
],
prefactor=prefactor,
)
# Start of X axis
diffusion_flux_pyst_kernel(
diffusion_flux=diffusion_flux[
:,
ghost_size - kernel_support : ghost_size + 2 * kernel_support,
],
field=field[
:,
ghost_size - kernel_support : ghost_size + 2 * kernel_support,
],
prefactor=prefactor,
)
# End of X axis
diffusion_flux_pyst_kernel(
diffusion_flux=diffusion_flux[
:,
-(ghost_size + 2 * kernel_support) : field.shape[1]
- (ghost_size - kernel_support),
],
field=field[
:,
-(ghost_size + 2 * kernel_support) : field.shape[1]
- (ghost_size - kernel_support),
],
prefactor=prefactor,
)
# Set physical domain boundary diffusion flus to zero based on neighboring block
boundary_width = 1
if x_previous == MPI.PROC_NULL:
set_fixed_val_kernel_2d(
field=diffusion_flux[:, : ghost_size + boundary_width],
fixed_val=0.0,
)
if x_next == MPI.PROC_NULL:
set_fixed_val_kernel_2d(
field=diffusion_flux[:, -ghost_size - boundary_width :],
fixed_val=0.0,
)
if y_previous == MPI.PROC_NULL:
set_fixed_val_kernel_2d(
field=diffusion_flux[: ghost_size + boundary_width, :],
fixed_val=0.0,
)
if y_next == MPI.PROC_NULL:
set_fixed_val_kernel_2d(
field=diffusion_flux[-ghost_size - boundary_width :, :],
fixed_val=0.0,
)
return diffusion_flux_pyst_mpi_kernel_2d
|
normal
|
{
"blob_id": "ba8cb18544e4ded8b229bfb9cc4b28599119414f",
"index": 854,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef gen_diffusion_flux_pyst_mpi_kernel_2d(real_t, mpi_construct,\n ghost_exchange_communicator):\n diffusion_flux_pyst_kernel = gen_diffusion_flux_pyst_kernel_2d(real_t=\n real_t, reset_ghost_zone=False)\n kernel_support = 1\n gen_diffusion_flux_pyst_mpi_kernel_2d.kernel_support = kernel_support\n check_valid_ghost_size_and_kernel_support(ghost_size=\n ghost_exchange_communicator.ghost_size, kernel_support=\n gen_diffusion_flux_pyst_mpi_kernel_2d.kernel_support)\n y_next, x_next = mpi_construct.next_grid_along\n y_previous, x_previous = mpi_construct.previous_grid_along\n set_fixed_val_kernel_2d = gen_set_fixed_val_pyst_kernel_2d(real_t=real_t)\n\n def diffusion_flux_pyst_mpi_kernel_2d(diffusion_flux, field, prefactor):\n diffusion_flux_pyst_mpi_kernel_2d.kernel_support = (\n gen_diffusion_flux_pyst_mpi_kernel_2d.kernel_support)\n ghost_size = ghost_exchange_communicator.ghost_size\n ghost_exchange_communicator.exchange_scalar_field_init(field)\n diffusion_flux_pyst_kernel(diffusion_flux=diffusion_flux[ghost_size\n :-ghost_size, ghost_size:-ghost_size], field=field[ghost_size:-\n ghost_size, ghost_size:-ghost_size], prefactor=prefactor)\n ghost_exchange_communicator.exchange_finalise()\n diffusion_flux_pyst_kernel(diffusion_flux=diffusion_flux[ghost_size -\n kernel_support:ghost_size + 2 * kernel_support, ghost_size:-\n ghost_size], field=field[ghost_size - kernel_support:ghost_size +\n 2 * kernel_support, ghost_size:-ghost_size], prefactor=prefactor)\n diffusion_flux_pyst_kernel(diffusion_flux=diffusion_flux[-(\n ghost_size + 2 * kernel_support):field.shape[0] - (ghost_size -\n kernel_support), ghost_size:-ghost_size], field=field[-(\n ghost_size + 2 * kernel_support):field.shape[0] - (ghost_size -\n kernel_support), ghost_size:-ghost_size], prefactor=prefactor)\n diffusion_flux_pyst_kernel(diffusion_flux=diffusion_flux[:, \n ghost_size - kernel_support:ghost_size + 2 * kernel_support],\n field=field[:, ghost_size - kernel_support:ghost_size + 2 *\n kernel_support], prefactor=prefactor)\n diffusion_flux_pyst_kernel(diffusion_flux=diffusion_flux[:, -(\n ghost_size + 2 * kernel_support):field.shape[1] - (ghost_size -\n kernel_support)], field=field[:, -(ghost_size + 2 *\n kernel_support):field.shape[1] - (ghost_size - kernel_support)],\n prefactor=prefactor)\n boundary_width = 1\n if x_previous == MPI.PROC_NULL:\n set_fixed_val_kernel_2d(field=diffusion_flux[:, :ghost_size +\n boundary_width], fixed_val=0.0)\n if x_next == MPI.PROC_NULL:\n set_fixed_val_kernel_2d(field=diffusion_flux[:, -ghost_size -\n boundary_width:], fixed_val=0.0)\n if y_previous == MPI.PROC_NULL:\n set_fixed_val_kernel_2d(field=diffusion_flux[:ghost_size +\n boundary_width, :], fixed_val=0.0)\n if y_next == MPI.PROC_NULL:\n set_fixed_val_kernel_2d(field=diffusion_flux[-ghost_size -\n boundary_width:, :], fixed_val=0.0)\n return diffusion_flux_pyst_mpi_kernel_2d\n",
"step-3": "<mask token>\nfrom sopht.numeric.eulerian_grid_ops.stencil_ops_2d import gen_diffusion_flux_pyst_kernel_2d, gen_set_fixed_val_pyst_kernel_2d\nfrom sopht_mpi.utils.mpi_utils import check_valid_ghost_size_and_kernel_support\nfrom mpi4py import MPI\n\n\ndef gen_diffusion_flux_pyst_mpi_kernel_2d(real_t, mpi_construct,\n ghost_exchange_communicator):\n diffusion_flux_pyst_kernel = gen_diffusion_flux_pyst_kernel_2d(real_t=\n real_t, reset_ghost_zone=False)\n kernel_support = 1\n gen_diffusion_flux_pyst_mpi_kernel_2d.kernel_support = kernel_support\n check_valid_ghost_size_and_kernel_support(ghost_size=\n ghost_exchange_communicator.ghost_size, kernel_support=\n gen_diffusion_flux_pyst_mpi_kernel_2d.kernel_support)\n y_next, x_next = mpi_construct.next_grid_along\n y_previous, x_previous = mpi_construct.previous_grid_along\n set_fixed_val_kernel_2d = gen_set_fixed_val_pyst_kernel_2d(real_t=real_t)\n\n def diffusion_flux_pyst_mpi_kernel_2d(diffusion_flux, field, prefactor):\n diffusion_flux_pyst_mpi_kernel_2d.kernel_support = (\n gen_diffusion_flux_pyst_mpi_kernel_2d.kernel_support)\n ghost_size = ghost_exchange_communicator.ghost_size\n ghost_exchange_communicator.exchange_scalar_field_init(field)\n diffusion_flux_pyst_kernel(diffusion_flux=diffusion_flux[ghost_size\n :-ghost_size, ghost_size:-ghost_size], field=field[ghost_size:-\n ghost_size, ghost_size:-ghost_size], prefactor=prefactor)\n ghost_exchange_communicator.exchange_finalise()\n diffusion_flux_pyst_kernel(diffusion_flux=diffusion_flux[ghost_size -\n kernel_support:ghost_size + 2 * kernel_support, ghost_size:-\n ghost_size], field=field[ghost_size - kernel_support:ghost_size +\n 2 * kernel_support, ghost_size:-ghost_size], prefactor=prefactor)\n diffusion_flux_pyst_kernel(diffusion_flux=diffusion_flux[-(\n ghost_size + 2 * kernel_support):field.shape[0] - (ghost_size -\n kernel_support), ghost_size:-ghost_size], field=field[-(\n ghost_size + 2 * kernel_support):field.shape[0] - (ghost_size -\n kernel_support), ghost_size:-ghost_size], prefactor=prefactor)\n diffusion_flux_pyst_kernel(diffusion_flux=diffusion_flux[:, \n ghost_size - kernel_support:ghost_size + 2 * kernel_support],\n field=field[:, ghost_size - kernel_support:ghost_size + 2 *\n kernel_support], prefactor=prefactor)\n diffusion_flux_pyst_kernel(diffusion_flux=diffusion_flux[:, -(\n ghost_size + 2 * kernel_support):field.shape[1] - (ghost_size -\n kernel_support)], field=field[:, -(ghost_size + 2 *\n kernel_support):field.shape[1] - (ghost_size - kernel_support)],\n prefactor=prefactor)\n boundary_width = 1\n if x_previous == MPI.PROC_NULL:\n set_fixed_val_kernel_2d(field=diffusion_flux[:, :ghost_size +\n boundary_width], fixed_val=0.0)\n if x_next == MPI.PROC_NULL:\n set_fixed_val_kernel_2d(field=diffusion_flux[:, -ghost_size -\n boundary_width:], fixed_val=0.0)\n if y_previous == MPI.PROC_NULL:\n set_fixed_val_kernel_2d(field=diffusion_flux[:ghost_size +\n boundary_width, :], fixed_val=0.0)\n if y_next == MPI.PROC_NULL:\n set_fixed_val_kernel_2d(field=diffusion_flux[-ghost_size -\n boundary_width:, :], fixed_val=0.0)\n return diffusion_flux_pyst_mpi_kernel_2d\n",
"step-4": "\"\"\"MPI-supported kernels for computing diffusion flux in 2D.\"\"\"\nfrom sopht.numeric.eulerian_grid_ops.stencil_ops_2d import (\n gen_diffusion_flux_pyst_kernel_2d,\n gen_set_fixed_val_pyst_kernel_2d,\n)\nfrom sopht_mpi.utils.mpi_utils import check_valid_ghost_size_and_kernel_support\nfrom mpi4py import MPI\n\n\ndef gen_diffusion_flux_pyst_mpi_kernel_2d(\n real_t, mpi_construct, ghost_exchange_communicator\n):\n # Note currently I'm generating these for arbit size arrays, we ca optimise this\n # more by generating fixed size for the interior stencil and arbit size for\n # boundary crunching\n diffusion_flux_pyst_kernel = gen_diffusion_flux_pyst_kernel_2d(\n real_t=real_t, reset_ghost_zone=False\n )\n kernel_support = 1\n # define this here so that ghost size and kernel support is checked during\n # generation phase itself\n gen_diffusion_flux_pyst_mpi_kernel_2d.kernel_support = kernel_support\n check_valid_ghost_size_and_kernel_support(\n ghost_size=ghost_exchange_communicator.ghost_size,\n kernel_support=gen_diffusion_flux_pyst_mpi_kernel_2d.kernel_support,\n )\n\n # for setting values at physical domain boundary\n y_next, x_next = mpi_construct.next_grid_along\n y_previous, x_previous = mpi_construct.previous_grid_along\n set_fixed_val_kernel_2d = gen_set_fixed_val_pyst_kernel_2d(real_t=real_t)\n\n def diffusion_flux_pyst_mpi_kernel_2d(\n diffusion_flux,\n field,\n prefactor,\n ):\n # define kernel support for kernel\n diffusion_flux_pyst_mpi_kernel_2d.kernel_support = (\n gen_diffusion_flux_pyst_mpi_kernel_2d.kernel_support\n )\n # define variable for use later\n ghost_size = ghost_exchange_communicator.ghost_size\n # begin ghost comm.\n ghost_exchange_communicator.exchange_scalar_field_init(field)\n\n # crunch interior stencil\n diffusion_flux_pyst_kernel(\n diffusion_flux=diffusion_flux[\n ghost_size:-ghost_size, ghost_size:-ghost_size\n ],\n field=field[ghost_size:-ghost_size, ghost_size:-ghost_size],\n prefactor=prefactor,\n )\n # finalise ghost comm.\n ghost_exchange_communicator.exchange_finalise()\n\n # crunch boundary numbers\n # NOTE: we pass in arrays of width 3 * kernel support size because the\n # interior stencil computation leaves out a width of kernel_support.\n # Since the support needed by the kernel is kernel_support on each side,\n # we need to pass an array of width 3 * kernel_support, starting from\n # index +/-(ghost_size - kernel_support) on the lower and upper end.\n # Pystencils then automatically sets the kernel comp. bounds and\n # crunches numbers in the kernel_support thickness zone at the boundary.\n # Start of Y axis\n diffusion_flux_pyst_kernel(\n diffusion_flux=diffusion_flux[\n ghost_size - kernel_support : ghost_size + 2 * kernel_support,\n ghost_size:-ghost_size,\n ],\n field=field[\n ghost_size - kernel_support : ghost_size + 2 * kernel_support,\n ghost_size:-ghost_size,\n ],\n prefactor=prefactor,\n )\n # End of Y axis\n diffusion_flux_pyst_kernel(\n diffusion_flux=diffusion_flux[\n -(ghost_size + 2 * kernel_support) : field.shape[0]\n - (ghost_size - kernel_support),\n ghost_size:-ghost_size,\n ],\n field=field[\n -(ghost_size + 2 * kernel_support) : field.shape[0]\n - (ghost_size - kernel_support),\n ghost_size:-ghost_size,\n ],\n prefactor=prefactor,\n )\n # Start of X axis\n diffusion_flux_pyst_kernel(\n diffusion_flux=diffusion_flux[\n :,\n ghost_size - kernel_support : ghost_size + 2 * kernel_support,\n ],\n field=field[\n :,\n ghost_size - kernel_support : ghost_size + 2 * kernel_support,\n ],\n prefactor=prefactor,\n )\n # End of X axis\n diffusion_flux_pyst_kernel(\n diffusion_flux=diffusion_flux[\n :,\n -(ghost_size + 2 * kernel_support) : field.shape[1]\n - (ghost_size - kernel_support),\n ],\n field=field[\n :,\n -(ghost_size + 2 * kernel_support) : field.shape[1]\n - (ghost_size - kernel_support),\n ],\n prefactor=prefactor,\n )\n\n # Set physical domain boundary diffusion flus to zero based on neighboring block\n boundary_width = 1\n if x_previous == MPI.PROC_NULL:\n set_fixed_val_kernel_2d(\n field=diffusion_flux[:, : ghost_size + boundary_width],\n fixed_val=0.0,\n )\n if x_next == MPI.PROC_NULL:\n set_fixed_val_kernel_2d(\n field=diffusion_flux[:, -ghost_size - boundary_width :],\n fixed_val=0.0,\n )\n if y_previous == MPI.PROC_NULL:\n set_fixed_val_kernel_2d(\n field=diffusion_flux[: ghost_size + boundary_width, :],\n fixed_val=0.0,\n )\n if y_next == MPI.PROC_NULL:\n set_fixed_val_kernel_2d(\n field=diffusion_flux[-ghost_size - boundary_width :, :],\n fixed_val=0.0,\n )\n\n return diffusion_flux_pyst_mpi_kernel_2d\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
def seed_everything(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
np.random.seed(seed)
random.seed(seed)
<|reserved_special_token_0|>
def increment_output_dir(output_path, exist_ok=False):
path = Path(output_path)
if path.exists() and exist_ok or not path.exists():
return str(path)
else:
dirs = glob.glob(f'{path}*')
matches = [re.search(f'%s(\\d+)' % path.stem, d) for d in dirs]
i = [int(m.groups()[0]) for m in matches if m]
n = max(i) + 1 if i else 2
return f'{path}{n}'
def train(args):
seed_everything(args.seed)
MODEL_NAME = 'monologg/koelectra-base-v3-discriminator'
tokenizer = ElectraTokenizer.from_pretrained(MODEL_NAME)
train_dataset = load_data('/opt/ml/input/data/train/train.tsv')
train_label = train_dataset['label'].values
tokenized_train = ko_tokenized_dataset(train_dataset, tokenizer)
RE_train_dataset = RE_Dataset(tokenized_train, train_label)
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
config_module = getattr(import_module('transformers'), 'ElectraConfig')
model_config = config_module.from_pretrained(MODEL_NAME)
model_config.num_labels = 42
model = ElectraForSequenceClassification.from_pretrained(MODEL_NAME,
config=model_config)
model.resize_token_embeddings(len(tokenizer))
model.parameters
model.to(device)
output_dir = increment_output_dir(args.output_dir)
training_args = TrainingArguments(output_dir=output_dir,
save_total_limit=args.save_total_limit, num_train_epochs=args.
epochs, learning_rate=args.lr, per_device_train_batch_size=args.
batch_size, warmup_steps=args.warmup_steps, weight_decay=args.
weight_decay, logging_dir='./logs', logging_steps=100, save_steps=
100, dataloader_num_workers=4, label_smoothing_factor=args.
label_smoothing_factor)
trainer = Trainer(model=model, args=training_args, train_dataset=
RE_train_dataset, compute_metrics=compute_metrics)
trainer.train()
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def seed_everything(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
np.random.seed(seed)
random.seed(seed)
def compute_metrics(pred):
labels = pred.label_ids
preds = pred.predictions.argmax(-1)
acc = accuracy_score(labels, preds)
return {'accuracy': acc}
def increment_output_dir(output_path, exist_ok=False):
path = Path(output_path)
if path.exists() and exist_ok or not path.exists():
return str(path)
else:
dirs = glob.glob(f'{path}*')
matches = [re.search(f'%s(\\d+)' % path.stem, d) for d in dirs]
i = [int(m.groups()[0]) for m in matches if m]
n = max(i) + 1 if i else 2
return f'{path}{n}'
def train(args):
seed_everything(args.seed)
MODEL_NAME = 'monologg/koelectra-base-v3-discriminator'
tokenizer = ElectraTokenizer.from_pretrained(MODEL_NAME)
train_dataset = load_data('/opt/ml/input/data/train/train.tsv')
train_label = train_dataset['label'].values
tokenized_train = ko_tokenized_dataset(train_dataset, tokenizer)
RE_train_dataset = RE_Dataset(tokenized_train, train_label)
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
config_module = getattr(import_module('transformers'), 'ElectraConfig')
model_config = config_module.from_pretrained(MODEL_NAME)
model_config.num_labels = 42
model = ElectraForSequenceClassification.from_pretrained(MODEL_NAME,
config=model_config)
model.resize_token_embeddings(len(tokenizer))
model.parameters
model.to(device)
output_dir = increment_output_dir(args.output_dir)
training_args = TrainingArguments(output_dir=output_dir,
save_total_limit=args.save_total_limit, num_train_epochs=args.
epochs, learning_rate=args.lr, per_device_train_batch_size=args.
batch_size, warmup_steps=args.warmup_steps, weight_decay=args.
weight_decay, logging_dir='./logs', logging_steps=100, save_steps=
100, dataloader_num_workers=4, label_smoothing_factor=args.
label_smoothing_factor)
trainer = Trainer(model=model, args=training_args, train_dataset=
RE_train_dataset, compute_metrics=compute_metrics)
trainer.train()
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def seed_everything(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
np.random.seed(seed)
random.seed(seed)
def compute_metrics(pred):
labels = pred.label_ids
preds = pred.predictions.argmax(-1)
acc = accuracy_score(labels, preds)
return {'accuracy': acc}
def increment_output_dir(output_path, exist_ok=False):
path = Path(output_path)
if path.exists() and exist_ok or not path.exists():
return str(path)
else:
dirs = glob.glob(f'{path}*')
matches = [re.search(f'%s(\\d+)' % path.stem, d) for d in dirs]
i = [int(m.groups()[0]) for m in matches if m]
n = max(i) + 1 if i else 2
return f'{path}{n}'
def train(args):
seed_everything(args.seed)
MODEL_NAME = 'monologg/koelectra-base-v3-discriminator'
tokenizer = ElectraTokenizer.from_pretrained(MODEL_NAME)
train_dataset = load_data('/opt/ml/input/data/train/train.tsv')
train_label = train_dataset['label'].values
tokenized_train = ko_tokenized_dataset(train_dataset, tokenizer)
RE_train_dataset = RE_Dataset(tokenized_train, train_label)
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
config_module = getattr(import_module('transformers'), 'ElectraConfig')
model_config = config_module.from_pretrained(MODEL_NAME)
model_config.num_labels = 42
model = ElectraForSequenceClassification.from_pretrained(MODEL_NAME,
config=model_config)
model.resize_token_embeddings(len(tokenizer))
model.parameters
model.to(device)
output_dir = increment_output_dir(args.output_dir)
training_args = TrainingArguments(output_dir=output_dir,
save_total_limit=args.save_total_limit, num_train_epochs=args.
epochs, learning_rate=args.lr, per_device_train_batch_size=args.
batch_size, warmup_steps=args.warmup_steps, weight_decay=args.
weight_decay, logging_dir='./logs', logging_steps=100, save_steps=
100, dataloader_num_workers=4, label_smoothing_factor=args.
label_smoothing_factor)
trainer = Trainer(model=model, args=training_args, train_dataset=
RE_train_dataset, compute_metrics=compute_metrics)
trainer.train()
def main(args):
train(args)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--seed', type=int, default=142)
parser.add_argument('--epochs', type=int, default=10)
parser.add_argument('--batch_size', type=int, default=32)
parser.add_argument('--lr', type=float, default=1e-05)
parser.add_argument('--weight_decay', type=float, default=0.01)
parser.add_argument('--warmup_steps', type=int, default=300)
parser.add_argument('--output_dir', type=str, default='./results/expr')
parser.add_argument('--save_steps', type=int, default=100)
parser.add_argument('--save_total_limit', type=int, default=1)
parser.add_argument('--logging_steps', type=int, default=100)
parser.add_argument('--logging_dir', type=str, default='./logs')
parser.add_argument('--label_smoothing_factor', type=float, default=0.5)
args = parser.parse_args()
main(args)
<|reserved_special_token_1|>
import pickle as pickle
import os
import pandas as pd
import torch
import numpy as np
import random
from sklearn.metrics import accuracy_score
from transformers import XLMRobertaTokenizer, XLMRobertaForSequenceClassification, Trainer, TrainingArguments, XLMRobertaConfig, ElectraForSequenceClassification, ElectraTokenizer
from load_data import *
import argparse
from importlib import import_module
from pathlib import Path
import glob
import re
def seed_everything(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
np.random.seed(seed)
random.seed(seed)
def compute_metrics(pred):
labels = pred.label_ids
preds = pred.predictions.argmax(-1)
acc = accuracy_score(labels, preds)
return {'accuracy': acc}
def increment_output_dir(output_path, exist_ok=False):
path = Path(output_path)
if path.exists() and exist_ok or not path.exists():
return str(path)
else:
dirs = glob.glob(f'{path}*')
matches = [re.search(f'%s(\\d+)' % path.stem, d) for d in dirs]
i = [int(m.groups()[0]) for m in matches if m]
n = max(i) + 1 if i else 2
return f'{path}{n}'
def train(args):
seed_everything(args.seed)
MODEL_NAME = 'monologg/koelectra-base-v3-discriminator'
tokenizer = ElectraTokenizer.from_pretrained(MODEL_NAME)
train_dataset = load_data('/opt/ml/input/data/train/train.tsv')
train_label = train_dataset['label'].values
tokenized_train = ko_tokenized_dataset(train_dataset, tokenizer)
RE_train_dataset = RE_Dataset(tokenized_train, train_label)
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
config_module = getattr(import_module('transformers'), 'ElectraConfig')
model_config = config_module.from_pretrained(MODEL_NAME)
model_config.num_labels = 42
model = ElectraForSequenceClassification.from_pretrained(MODEL_NAME,
config=model_config)
model.resize_token_embeddings(len(tokenizer))
model.parameters
model.to(device)
output_dir = increment_output_dir(args.output_dir)
training_args = TrainingArguments(output_dir=output_dir,
save_total_limit=args.save_total_limit, num_train_epochs=args.
epochs, learning_rate=args.lr, per_device_train_batch_size=args.
batch_size, warmup_steps=args.warmup_steps, weight_decay=args.
weight_decay, logging_dir='./logs', logging_steps=100, save_steps=
100, dataloader_num_workers=4, label_smoothing_factor=args.
label_smoothing_factor)
trainer = Trainer(model=model, args=training_args, train_dataset=
RE_train_dataset, compute_metrics=compute_metrics)
trainer.train()
def main(args):
train(args)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--seed', type=int, default=142)
parser.add_argument('--epochs', type=int, default=10)
parser.add_argument('--batch_size', type=int, default=32)
parser.add_argument('--lr', type=float, default=1e-05)
parser.add_argument('--weight_decay', type=float, default=0.01)
parser.add_argument('--warmup_steps', type=int, default=300)
parser.add_argument('--output_dir', type=str, default='./results/expr')
parser.add_argument('--save_steps', type=int, default=100)
parser.add_argument('--save_total_limit', type=int, default=1)
parser.add_argument('--logging_steps', type=int, default=100)
parser.add_argument('--logging_dir', type=str, default='./logs')
parser.add_argument('--label_smoothing_factor', type=float, default=0.5)
args = parser.parse_args()
main(args)
<|reserved_special_token_1|>
import pickle as pickle
import os
import pandas as pd
import torch
import numpy as np
import random
from sklearn.metrics import accuracy_score
from transformers import XLMRobertaTokenizer, XLMRobertaForSequenceClassification, Trainer, TrainingArguments, XLMRobertaConfig, ElectraForSequenceClassification, ElectraTokenizer
from load_data import *
import argparse
from importlib import import_module
from pathlib import Path
import glob
import re
# seed 고정
def seed_everything(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed) # if use multi-GPU
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
np.random.seed(seed)
random.seed(seed)
# 평가를 위한 metrics function.
def compute_metrics(pred):
labels = pred.label_ids
preds = pred.predictions.argmax(-1)
# calculate accuracy using sklearn's function
acc = accuracy_score(labels, preds)
return {
'accuracy': acc,
}
def increment_output_dir(output_path, exist_ok=False):
path = Path(output_path)
if (path.exists() and exist_ok) or (not path.exists()):
return str(path)
else:
dirs = glob.glob(f"{path}*")
matches = [re.search(rf"%s(\d+)" %path.stem, d) for d in dirs]
i = [int(m.groups()[0]) for m in matches if m]
n = max(i) + 1 if i else 2
return f"{path}{n}"
def train(args):
seed_everything(args.seed)
# load model and tokenizer
# MODEL_NAME = "xlm-roberta-large"
# tokenizer = XLMRobertaTokenizer.from_pretrained(MODEL_NAME)
MODEL_NAME = "monologg/koelectra-base-v3-discriminator"
tokenizer = ElectraTokenizer.from_pretrained(MODEL_NAME)
# load dataset
train_dataset = load_data("/opt/ml/input/data/train/train.tsv")
#dev_dataset = load_data("./dataset/train/train_dev.tsv")
train_label = train_dataset['label'].values
#dev_label = dev_dataset['label'].values
# tokenizing dataset
tokenized_train = ko_tokenized_dataset(train_dataset, tokenizer)
#tokenized_dev = tokenized_dataset(dev_dataset, tokenizer)
# make dataset for pytorch.
RE_train_dataset = RE_Dataset(tokenized_train, train_label)
#RE_dev_dataset = RE_Dataset(tokenized_dev, dev_label)
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
# setting model hyperparameter
# bert_config = XLMRobertaConfig.from_pretrained(MODEL_NAME)
# bert_config.num_labels = 42
# model = XLMRobertaForSequenceClassification.from_pretrained(MODEL_NAME, config=bert_config)
# model.resize_token_embeddings(len(tokenizer))
config_module = getattr(import_module("transformers"), "ElectraConfig")
model_config = config_module.from_pretrained(MODEL_NAME)
model_config.num_labels = 42
model = ElectraForSequenceClassification.from_pretrained(MODEL_NAME, config=model_config)
model.resize_token_embeddings(len(tokenizer))
model.parameters
model.to(device)
output_dir = increment_output_dir(args.output_dir)
# 사용한 option 외에도 다양한 option들이 있습니다.
# https://huggingface.co/transformers/main_classes/trainer.html#trainingarguments 참고해주세요.
training_args = TrainingArguments(
output_dir=output_dir, # output directory
save_total_limit=args.save_total_limit, # number of total save model.
num_train_epochs=args.epochs, # total number of training epochs
learning_rate=args.lr, # learning_rate
per_device_train_batch_size=args.batch_size, # batch size per device during training
warmup_steps=args.warmup_steps, # number of warmup steps for learning rate scheduler
weight_decay=args.weight_decay, # strength of weight decay
logging_dir='./logs', # directory for storing logs
logging_steps=100, # log saving step.
save_steps=100,
dataloader_num_workers=4,
label_smoothing_factor=args.label_smoothing_factor,
)
trainer = Trainer(
model=model, # the instantiated 🤗 Transformers model to be trained
args=training_args, # training arguments, defined above
train_dataset=RE_train_dataset, # training dataset
compute_metrics = compute_metrics,
)
# train model
trainer.train()
def main(args):
train(args)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--seed', type=int, default=142)
parser.add_argument('--epochs', type=int, default=10)
parser.add_argument('--batch_size', type=int, default=32)
parser.add_argument('--lr', type=float, default=1e-5)
parser.add_argument('--weight_decay', type=float, default=0.01)
parser.add_argument('--warmup_steps', type=int, default=300) # number of warmup steps for learning rate scheduler
parser.add_argument('--output_dir', type=str, default='./results/expr')
parser.add_argument('--save_steps', type=int, default=100)
parser.add_argument('--save_total_limit', type=int, default=1)
parser.add_argument('--logging_steps', type=int, default=100)
parser.add_argument('--logging_dir', type=str, default='./logs') # directory for storing logs
parser.add_argument('--label_smoothing_factor', type=float, default=0.5) # directory for storing logs
args = parser.parse_args()
main(args)
|
flexible
|
{
"blob_id": "d3b6a105b14d9c3485a71058391a03c2f4aa5c10",
"index": 8628,
"step-1": "<mask token>\n\n\ndef seed_everything(seed):\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n np.random.seed(seed)\n random.seed(seed)\n\n\n<mask token>\n\n\ndef increment_output_dir(output_path, exist_ok=False):\n path = Path(output_path)\n if path.exists() and exist_ok or not path.exists():\n return str(path)\n else:\n dirs = glob.glob(f'{path}*')\n matches = [re.search(f'%s(\\\\d+)' % path.stem, d) for d in dirs]\n i = [int(m.groups()[0]) for m in matches if m]\n n = max(i) + 1 if i else 2\n return f'{path}{n}'\n\n\ndef train(args):\n seed_everything(args.seed)\n MODEL_NAME = 'monologg/koelectra-base-v3-discriminator'\n tokenizer = ElectraTokenizer.from_pretrained(MODEL_NAME)\n train_dataset = load_data('/opt/ml/input/data/train/train.tsv')\n train_label = train_dataset['label'].values\n tokenized_train = ko_tokenized_dataset(train_dataset, tokenizer)\n RE_train_dataset = RE_Dataset(tokenized_train, train_label)\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n config_module = getattr(import_module('transformers'), 'ElectraConfig')\n model_config = config_module.from_pretrained(MODEL_NAME)\n model_config.num_labels = 42\n model = ElectraForSequenceClassification.from_pretrained(MODEL_NAME,\n config=model_config)\n model.resize_token_embeddings(len(tokenizer))\n model.parameters\n model.to(device)\n output_dir = increment_output_dir(args.output_dir)\n training_args = TrainingArguments(output_dir=output_dir,\n save_total_limit=args.save_total_limit, num_train_epochs=args.\n epochs, learning_rate=args.lr, per_device_train_batch_size=args.\n batch_size, warmup_steps=args.warmup_steps, weight_decay=args.\n weight_decay, logging_dir='./logs', logging_steps=100, save_steps=\n 100, dataloader_num_workers=4, label_smoothing_factor=args.\n label_smoothing_factor)\n trainer = Trainer(model=model, args=training_args, train_dataset=\n RE_train_dataset, compute_metrics=compute_metrics)\n trainer.train()\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef seed_everything(seed):\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n np.random.seed(seed)\n random.seed(seed)\n\n\ndef compute_metrics(pred):\n labels = pred.label_ids\n preds = pred.predictions.argmax(-1)\n acc = accuracy_score(labels, preds)\n return {'accuracy': acc}\n\n\ndef increment_output_dir(output_path, exist_ok=False):\n path = Path(output_path)\n if path.exists() and exist_ok or not path.exists():\n return str(path)\n else:\n dirs = glob.glob(f'{path}*')\n matches = [re.search(f'%s(\\\\d+)' % path.stem, d) for d in dirs]\n i = [int(m.groups()[0]) for m in matches if m]\n n = max(i) + 1 if i else 2\n return f'{path}{n}'\n\n\ndef train(args):\n seed_everything(args.seed)\n MODEL_NAME = 'monologg/koelectra-base-v3-discriminator'\n tokenizer = ElectraTokenizer.from_pretrained(MODEL_NAME)\n train_dataset = load_data('/opt/ml/input/data/train/train.tsv')\n train_label = train_dataset['label'].values\n tokenized_train = ko_tokenized_dataset(train_dataset, tokenizer)\n RE_train_dataset = RE_Dataset(tokenized_train, train_label)\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n config_module = getattr(import_module('transformers'), 'ElectraConfig')\n model_config = config_module.from_pretrained(MODEL_NAME)\n model_config.num_labels = 42\n model = ElectraForSequenceClassification.from_pretrained(MODEL_NAME,\n config=model_config)\n model.resize_token_embeddings(len(tokenizer))\n model.parameters\n model.to(device)\n output_dir = increment_output_dir(args.output_dir)\n training_args = TrainingArguments(output_dir=output_dir,\n save_total_limit=args.save_total_limit, num_train_epochs=args.\n epochs, learning_rate=args.lr, per_device_train_batch_size=args.\n batch_size, warmup_steps=args.warmup_steps, weight_decay=args.\n weight_decay, logging_dir='./logs', logging_steps=100, save_steps=\n 100, dataloader_num_workers=4, label_smoothing_factor=args.\n label_smoothing_factor)\n trainer = Trainer(model=model, args=training_args, train_dataset=\n RE_train_dataset, compute_metrics=compute_metrics)\n trainer.train()\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef seed_everything(seed):\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n np.random.seed(seed)\n random.seed(seed)\n\n\ndef compute_metrics(pred):\n labels = pred.label_ids\n preds = pred.predictions.argmax(-1)\n acc = accuracy_score(labels, preds)\n return {'accuracy': acc}\n\n\ndef increment_output_dir(output_path, exist_ok=False):\n path = Path(output_path)\n if path.exists() and exist_ok or not path.exists():\n return str(path)\n else:\n dirs = glob.glob(f'{path}*')\n matches = [re.search(f'%s(\\\\d+)' % path.stem, d) for d in dirs]\n i = [int(m.groups()[0]) for m in matches if m]\n n = max(i) + 1 if i else 2\n return f'{path}{n}'\n\n\ndef train(args):\n seed_everything(args.seed)\n MODEL_NAME = 'monologg/koelectra-base-v3-discriminator'\n tokenizer = ElectraTokenizer.from_pretrained(MODEL_NAME)\n train_dataset = load_data('/opt/ml/input/data/train/train.tsv')\n train_label = train_dataset['label'].values\n tokenized_train = ko_tokenized_dataset(train_dataset, tokenizer)\n RE_train_dataset = RE_Dataset(tokenized_train, train_label)\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n config_module = getattr(import_module('transformers'), 'ElectraConfig')\n model_config = config_module.from_pretrained(MODEL_NAME)\n model_config.num_labels = 42\n model = ElectraForSequenceClassification.from_pretrained(MODEL_NAME,\n config=model_config)\n model.resize_token_embeddings(len(tokenizer))\n model.parameters\n model.to(device)\n output_dir = increment_output_dir(args.output_dir)\n training_args = TrainingArguments(output_dir=output_dir,\n save_total_limit=args.save_total_limit, num_train_epochs=args.\n epochs, learning_rate=args.lr, per_device_train_batch_size=args.\n batch_size, warmup_steps=args.warmup_steps, weight_decay=args.\n weight_decay, logging_dir='./logs', logging_steps=100, save_steps=\n 100, dataloader_num_workers=4, label_smoothing_factor=args.\n label_smoothing_factor)\n trainer = Trainer(model=model, args=training_args, train_dataset=\n RE_train_dataset, compute_metrics=compute_metrics)\n trainer.train()\n\n\ndef main(args):\n train(args)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--seed', type=int, default=142)\n parser.add_argument('--epochs', type=int, default=10)\n parser.add_argument('--batch_size', type=int, default=32)\n parser.add_argument('--lr', type=float, default=1e-05)\n parser.add_argument('--weight_decay', type=float, default=0.01)\n parser.add_argument('--warmup_steps', type=int, default=300)\n parser.add_argument('--output_dir', type=str, default='./results/expr')\n parser.add_argument('--save_steps', type=int, default=100)\n parser.add_argument('--save_total_limit', type=int, default=1)\n parser.add_argument('--logging_steps', type=int, default=100)\n parser.add_argument('--logging_dir', type=str, default='./logs')\n parser.add_argument('--label_smoothing_factor', type=float, default=0.5)\n args = parser.parse_args()\n main(args)\n",
"step-4": "import pickle as pickle\nimport os\nimport pandas as pd\nimport torch\nimport numpy as np\nimport random\nfrom sklearn.metrics import accuracy_score\nfrom transformers import XLMRobertaTokenizer, XLMRobertaForSequenceClassification, Trainer, TrainingArguments, XLMRobertaConfig, ElectraForSequenceClassification, ElectraTokenizer\nfrom load_data import *\nimport argparse\nfrom importlib import import_module\nfrom pathlib import Path\nimport glob\nimport re\n\n\ndef seed_everything(seed):\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n np.random.seed(seed)\n random.seed(seed)\n\n\ndef compute_metrics(pred):\n labels = pred.label_ids\n preds = pred.predictions.argmax(-1)\n acc = accuracy_score(labels, preds)\n return {'accuracy': acc}\n\n\ndef increment_output_dir(output_path, exist_ok=False):\n path = Path(output_path)\n if path.exists() and exist_ok or not path.exists():\n return str(path)\n else:\n dirs = glob.glob(f'{path}*')\n matches = [re.search(f'%s(\\\\d+)' % path.stem, d) for d in dirs]\n i = [int(m.groups()[0]) for m in matches if m]\n n = max(i) + 1 if i else 2\n return f'{path}{n}'\n\n\ndef train(args):\n seed_everything(args.seed)\n MODEL_NAME = 'monologg/koelectra-base-v3-discriminator'\n tokenizer = ElectraTokenizer.from_pretrained(MODEL_NAME)\n train_dataset = load_data('/opt/ml/input/data/train/train.tsv')\n train_label = train_dataset['label'].values\n tokenized_train = ko_tokenized_dataset(train_dataset, tokenizer)\n RE_train_dataset = RE_Dataset(tokenized_train, train_label)\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n config_module = getattr(import_module('transformers'), 'ElectraConfig')\n model_config = config_module.from_pretrained(MODEL_NAME)\n model_config.num_labels = 42\n model = ElectraForSequenceClassification.from_pretrained(MODEL_NAME,\n config=model_config)\n model.resize_token_embeddings(len(tokenizer))\n model.parameters\n model.to(device)\n output_dir = increment_output_dir(args.output_dir)\n training_args = TrainingArguments(output_dir=output_dir,\n save_total_limit=args.save_total_limit, num_train_epochs=args.\n epochs, learning_rate=args.lr, per_device_train_batch_size=args.\n batch_size, warmup_steps=args.warmup_steps, weight_decay=args.\n weight_decay, logging_dir='./logs', logging_steps=100, save_steps=\n 100, dataloader_num_workers=4, label_smoothing_factor=args.\n label_smoothing_factor)\n trainer = Trainer(model=model, args=training_args, train_dataset=\n RE_train_dataset, compute_metrics=compute_metrics)\n trainer.train()\n\n\ndef main(args):\n train(args)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--seed', type=int, default=142)\n parser.add_argument('--epochs', type=int, default=10)\n parser.add_argument('--batch_size', type=int, default=32)\n parser.add_argument('--lr', type=float, default=1e-05)\n parser.add_argument('--weight_decay', type=float, default=0.01)\n parser.add_argument('--warmup_steps', type=int, default=300)\n parser.add_argument('--output_dir', type=str, default='./results/expr')\n parser.add_argument('--save_steps', type=int, default=100)\n parser.add_argument('--save_total_limit', type=int, default=1)\n parser.add_argument('--logging_steps', type=int, default=100)\n parser.add_argument('--logging_dir', type=str, default='./logs')\n parser.add_argument('--label_smoothing_factor', type=float, default=0.5)\n args = parser.parse_args()\n main(args)\n",
"step-5": "import pickle as pickle\r\nimport os\r\nimport pandas as pd\r\nimport torch\r\nimport numpy as np\r\nimport random\r\nfrom sklearn.metrics import accuracy_score\r\nfrom transformers import XLMRobertaTokenizer, XLMRobertaForSequenceClassification, Trainer, TrainingArguments, XLMRobertaConfig, ElectraForSequenceClassification, ElectraTokenizer\r\nfrom load_data import *\r\n\r\nimport argparse\r\nfrom importlib import import_module\r\nfrom pathlib import Path\r\nimport glob\r\nimport re\r\n\r\n# seed 고정 \r\ndef seed_everything(seed):\r\n torch.manual_seed(seed)\r\n torch.cuda.manual_seed(seed)\r\n torch.cuda.manual_seed_all(seed) # if use multi-GPU\r\n torch.backends.cudnn.deterministic = True\r\n torch.backends.cudnn.benchmark = False\r\n np.random.seed(seed)\r\n random.seed(seed)\r\n\r\n# 평가를 위한 metrics function.\r\ndef compute_metrics(pred):\r\n labels = pred.label_ids\r\n preds = pred.predictions.argmax(-1)\r\n # calculate accuracy using sklearn's function\r\n acc = accuracy_score(labels, preds)\r\n return {\r\n 'accuracy': acc,\r\n }\r\n\r\ndef increment_output_dir(output_path, exist_ok=False):\r\n path = Path(output_path)\r\n if (path.exists() and exist_ok) or (not path.exists()):\r\n return str(path)\r\n else:\r\n dirs = glob.glob(f\"{path}*\")\r\n matches = [re.search(rf\"%s(\\d+)\" %path.stem, d) for d in dirs]\r\n i = [int(m.groups()[0]) for m in matches if m]\r\n n = max(i) + 1 if i else 2\r\n return f\"{path}{n}\"\r\n\r\ndef train(args):\r\n seed_everything(args.seed)\r\n # load model and tokenizer\r\n# MODEL_NAME = \"xlm-roberta-large\"\r\n# tokenizer = XLMRobertaTokenizer.from_pretrained(MODEL_NAME)\r\n MODEL_NAME = \"monologg/koelectra-base-v3-discriminator\"\r\n tokenizer = ElectraTokenizer.from_pretrained(MODEL_NAME)\r\n\r\n # load dataset\r\n train_dataset = load_data(\"/opt/ml/input/data/train/train.tsv\")\r\n #dev_dataset = load_data(\"./dataset/train/train_dev.tsv\")\r\n train_label = train_dataset['label'].values\r\n #dev_label = dev_dataset['label'].values\r\n\r\n # tokenizing dataset\r\n tokenized_train = ko_tokenized_dataset(train_dataset, tokenizer)\r\n #tokenized_dev = tokenized_dataset(dev_dataset, tokenizer)\r\n\r\n # make dataset for pytorch.\r\n RE_train_dataset = RE_Dataset(tokenized_train, train_label)\r\n #RE_dev_dataset = RE_Dataset(tokenized_dev, dev_label)\r\n\r\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\r\n\r\n # setting model hyperparameter\r\n# bert_config = XLMRobertaConfig.from_pretrained(MODEL_NAME)\r\n# bert_config.num_labels = 42\r\n# model = XLMRobertaForSequenceClassification.from_pretrained(MODEL_NAME, config=bert_config)\r\n# model.resize_token_embeddings(len(tokenizer))\r\n config_module = getattr(import_module(\"transformers\"), \"ElectraConfig\")\r\n model_config = config_module.from_pretrained(MODEL_NAME)\r\n model_config.num_labels = 42\r\n model = ElectraForSequenceClassification.from_pretrained(MODEL_NAME, config=model_config)\r\n model.resize_token_embeddings(len(tokenizer))\r\n model.parameters\r\n model.to(device)\r\n\r\n output_dir = increment_output_dir(args.output_dir)\r\n \r\n # 사용한 option 외에도 다양한 option들이 있습니다.\r\n # https://huggingface.co/transformers/main_classes/trainer.html#trainingarguments 참고해주세요.\r\n training_args = TrainingArguments(\r\n output_dir=output_dir, # output directory\r\n save_total_limit=args.save_total_limit, # number of total save model.\r\n num_train_epochs=args.epochs, # total number of training epochs\r\n learning_rate=args.lr, # learning_rate\r\n per_device_train_batch_size=args.batch_size, # batch size per device during training\r\n warmup_steps=args.warmup_steps, # number of warmup steps for learning rate scheduler\r\n weight_decay=args.weight_decay, # strength of weight decay\r\n logging_dir='./logs', # directory for storing logs\r\n logging_steps=100, # log saving step.\r\n save_steps=100,\r\n dataloader_num_workers=4,\r\n label_smoothing_factor=args.label_smoothing_factor,\r\n )\r\n trainer = Trainer(\r\n model=model, # the instantiated 🤗 Transformers model to be trained\r\n args=training_args, # training arguments, defined above\r\n train_dataset=RE_train_dataset, # training dataset\r\n compute_metrics = compute_metrics,\r\n )\r\n\r\n # train model\r\n trainer.train()\r\n\r\ndef main(args):\r\n train(args)\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--seed', type=int, default=142)\r\n parser.add_argument('--epochs', type=int, default=10)\r\n parser.add_argument('--batch_size', type=int, default=32)\r\n parser.add_argument('--lr', type=float, default=1e-5)\r\n parser.add_argument('--weight_decay', type=float, default=0.01)\r\n parser.add_argument('--warmup_steps', type=int, default=300) # number of warmup steps for learning rate scheduler\r\n parser.add_argument('--output_dir', type=str, default='./results/expr')\r\n parser.add_argument('--save_steps', type=int, default=100)\r\n parser.add_argument('--save_total_limit', type=int, default=1)\r\n parser.add_argument('--logging_steps', type=int, default=100)\r\n parser.add_argument('--logging_dir', type=str, default='./logs') # directory for storing logs\r\n parser.add_argument('--label_smoothing_factor', type=float, default=0.5) # directory for storing logs\r\n\r\n\r\n args = parser.parse_args()\r\n \r\n main(args)",
"step-ids": [
3,
4,
6,
7,
8
]
}
|
[
3,
4,
6,
7,
8
] |
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: legolas
#
# Created: 05.03.2015
# Copyright: (c) legolas 2015
# Licence: <your licence>
#-------------------------------------------------------------------------------
print "This is checking the feature of the function 'input'."
familyName = input("What's your name?")
family = 'Hey'
print familyName
|
normal
|
{
"blob_id": "08abb94424598cb54a6b16db68759b216682d866",
"index": 6254,
"step-1": "#-------------------------------------------------------------------------------\n# Name: module1\n# Purpose:\n#\n# Author: legolas\n#\n# Created: 05.03.2015\n# Copyright: (c) legolas 2015\n# Licence: <your licence>\n#-------------------------------------------------------------------------------\n\nprint \"This is checking the feature of the function 'input'.\"\n\nfamilyName = input(\"What's your name?\")\n\nfamily = 'Hey'\n\nprint familyName\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
#!/usr/bin/env python3
import sys
import re
from collections import namedtuple
def isnum(name):
return name.startswith('-') or name.isdigit()
class WireValues:
def __init__(self):
self.wires = {}
def __getitem__(self, name):
return int(name) if isnum(name) else self.wires[name]
def __setitem__(self, name, value):
self.wires[name] = value
def __contains__(self, name):
return isnum(name) or name in self.wires
Command = namedtuple('Command', 'pattern function')
WireLink = namedtuple('WireLink', 'command inputs output')
COMMANDS = []
def make_command(expr):
pattern = re.compile('^'+expr.replace('#', '([0-9a-z]+)')+'$')
def command_maker(function):
command = Command(pattern, function)
COMMANDS.append(command)
return command
return command_maker
@make_command('# -> #')
def assignment(wires, v1, name):
wires[name] = wires[v1]
@make_command('# AND # -> #')
def anding(wires, v1, v2, name):
wires[name] = wires[v1] & wires[v2]
@make_command('# OR # -> #')
def oring(wires, v1, v2, name):
wires[name] = wires[v1] | wires[v2]
@make_command('# LSHIFT # -> #')
def lshift(wires, v1, v2, name):
wires[name] = wires[v1] << wires[v2]
@make_command('# RSHIFT # -> #')
def rshift(wires, v1, v2, name):
wires[name] = wires[v1] >> wires[v2]
@make_command('NOT # -> #')
def notting(wires, v1, name):
wires[name] = ((1<<16)-1)&~wires[v1]
def create_link(line):
for cmd in COMMANDS:
m = re.match(cmd.pattern, line)
if m:
gps = m.groups()
return WireLink(cmd, gps[:-1], gps[-1])
raise ValueError(repr(line))
def process_links(links):
wires = WireValues()
while links:
remaining = []
for link in links:
if all(i in wires for i in link.inputs):
link.command.function(wires, *link.inputs, link.output)
else:
remaining.append(link)
links = remaining
return wires
def main():
lines = sys.stdin.read().strip().split('\n')
links = [create_link(line) for line in lines]
wires = process_links(links)
answer = wires['a']
print("Part 1 wire a:", answer)
index = next(i for (i,link) in enumerate(links) if link.output=='b')
links[index] = WireLink(assignment, [str(answer)], 'b')
wires = process_links(links)
answer = wires['a']
print("Part 2 wire a:", answer)
if __name__ == '__main__':
main()
|
normal
|
{
"blob_id": "a5eb1f559972519dbe0f3702e03af77e61fbfb4e",
"index": 7985,
"step-1": "<mask token>\n\n\nclass WireValues:\n\n def __init__(self):\n self.wires = {}\n\n def __getitem__(self, name):\n return int(name) if isnum(name) else self.wires[name]\n\n def __setitem__(self, name, value):\n self.wires[name] = value\n\n def __contains__(self, name):\n return isnum(name) or name in self.wires\n\n\n<mask token>\n\n\n@make_command('# RSHIFT # -> #')\ndef rshift(wires, v1, v2, name):\n wires[name] = wires[v1] >> wires[v2]\n\n\n<mask token>\n\n\ndef process_links(links):\n wires = WireValues()\n while links:\n remaining = []\n for link in links:\n if all(i in wires for i in link.inputs):\n link.command.function(wires, *link.inputs, link.output)\n else:\n remaining.append(link)\n links = remaining\n return wires\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef isnum(name):\n return name.startswith('-') or name.isdigit()\n\n\nclass WireValues:\n\n def __init__(self):\n self.wires = {}\n\n def __getitem__(self, name):\n return int(name) if isnum(name) else self.wires[name]\n\n def __setitem__(self, name, value):\n self.wires[name] = value\n\n def __contains__(self, name):\n return isnum(name) or name in self.wires\n\n\n<mask token>\n\n\ndef make_command(expr):\n pattern = re.compile('^' + expr.replace('#', '([0-9a-z]+)') + '$')\n\n def command_maker(function):\n command = Command(pattern, function)\n COMMANDS.append(command)\n return command\n return command_maker\n\n\n@make_command('# -> #')\ndef assignment(wires, v1, name):\n wires[name] = wires[v1]\n\n\n@make_command('# AND # -> #')\ndef anding(wires, v1, v2, name):\n wires[name] = wires[v1] & wires[v2]\n\n\n<mask token>\n\n\n@make_command('# RSHIFT # -> #')\ndef rshift(wires, v1, v2, name):\n wires[name] = wires[v1] >> wires[v2]\n\n\n@make_command('NOT # -> #')\ndef notting(wires, v1, name):\n wires[name] = (1 << 16) - 1 & ~wires[v1]\n\n\ndef create_link(line):\n for cmd in COMMANDS:\n m = re.match(cmd.pattern, line)\n if m:\n gps = m.groups()\n return WireLink(cmd, gps[:-1], gps[-1])\n raise ValueError(repr(line))\n\n\ndef process_links(links):\n wires = WireValues()\n while links:\n remaining = []\n for link in links:\n if all(i in wires for i in link.inputs):\n link.command.function(wires, *link.inputs, link.output)\n else:\n remaining.append(link)\n links = remaining\n return wires\n\n\ndef main():\n lines = sys.stdin.read().strip().split('\\n')\n links = [create_link(line) for line in lines]\n wires = process_links(links)\n answer = wires['a']\n print('Part 1 wire a:', answer)\n index = next(i for i, link in enumerate(links) if link.output == 'b')\n links[index] = WireLink(assignment, [str(answer)], 'b')\n wires = process_links(links)\n answer = wires['a']\n print('Part 2 wire a:', answer)\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef isnum(name):\n return name.startswith('-') or name.isdigit()\n\n\nclass WireValues:\n\n def __init__(self):\n self.wires = {}\n\n def __getitem__(self, name):\n return int(name) if isnum(name) else self.wires[name]\n\n def __setitem__(self, name, value):\n self.wires[name] = value\n\n def __contains__(self, name):\n return isnum(name) or name in self.wires\n\n\n<mask token>\n\n\ndef make_command(expr):\n pattern = re.compile('^' + expr.replace('#', '([0-9a-z]+)') + '$')\n\n def command_maker(function):\n command = Command(pattern, function)\n COMMANDS.append(command)\n return command\n return command_maker\n\n\n@make_command('# -> #')\ndef assignment(wires, v1, name):\n wires[name] = wires[v1]\n\n\n@make_command('# AND # -> #')\ndef anding(wires, v1, v2, name):\n wires[name] = wires[v1] & wires[v2]\n\n\n@make_command('# OR # -> #')\ndef oring(wires, v1, v2, name):\n wires[name] = wires[v1] | wires[v2]\n\n\n@make_command('# LSHIFT # -> #')\ndef lshift(wires, v1, v2, name):\n wires[name] = wires[v1] << wires[v2]\n\n\n@make_command('# RSHIFT # -> #')\ndef rshift(wires, v1, v2, name):\n wires[name] = wires[v1] >> wires[v2]\n\n\n@make_command('NOT # -> #')\ndef notting(wires, v1, name):\n wires[name] = (1 << 16) - 1 & ~wires[v1]\n\n\ndef create_link(line):\n for cmd in COMMANDS:\n m = re.match(cmd.pattern, line)\n if m:\n gps = m.groups()\n return WireLink(cmd, gps[:-1], gps[-1])\n raise ValueError(repr(line))\n\n\ndef process_links(links):\n wires = WireValues()\n while links:\n remaining = []\n for link in links:\n if all(i in wires for i in link.inputs):\n link.command.function(wires, *link.inputs, link.output)\n else:\n remaining.append(link)\n links = remaining\n return wires\n\n\ndef main():\n lines = sys.stdin.read().strip().split('\\n')\n links = [create_link(line) for line in lines]\n wires = process_links(links)\n answer = wires['a']\n print('Part 1 wire a:', answer)\n index = next(i for i, link in enumerate(links) if link.output == 'b')\n links[index] = WireLink(assignment, [str(answer)], 'b')\n wires = process_links(links)\n answer = wires['a']\n print('Part 2 wire a:', answer)\n\n\n<mask token>\n",
"step-4": "<mask token>\n\n\ndef isnum(name):\n return name.startswith('-') or name.isdigit()\n\n\nclass WireValues:\n\n def __init__(self):\n self.wires = {}\n\n def __getitem__(self, name):\n return int(name) if isnum(name) else self.wires[name]\n\n def __setitem__(self, name, value):\n self.wires[name] = value\n\n def __contains__(self, name):\n return isnum(name) or name in self.wires\n\n\nCommand = namedtuple('Command', 'pattern function')\nWireLink = namedtuple('WireLink', 'command inputs output')\nCOMMANDS = []\n\n\ndef make_command(expr):\n pattern = re.compile('^' + expr.replace('#', '([0-9a-z]+)') + '$')\n\n def command_maker(function):\n command = Command(pattern, function)\n COMMANDS.append(command)\n return command\n return command_maker\n\n\n@make_command('# -> #')\ndef assignment(wires, v1, name):\n wires[name] = wires[v1]\n\n\n@make_command('# AND # -> #')\ndef anding(wires, v1, v2, name):\n wires[name] = wires[v1] & wires[v2]\n\n\n@make_command('# OR # -> #')\ndef oring(wires, v1, v2, name):\n wires[name] = wires[v1] | wires[v2]\n\n\n@make_command('# LSHIFT # -> #')\ndef lshift(wires, v1, v2, name):\n wires[name] = wires[v1] << wires[v2]\n\n\n@make_command('# RSHIFT # -> #')\ndef rshift(wires, v1, v2, name):\n wires[name] = wires[v1] >> wires[v2]\n\n\n@make_command('NOT # -> #')\ndef notting(wires, v1, name):\n wires[name] = (1 << 16) - 1 & ~wires[v1]\n\n\ndef create_link(line):\n for cmd in COMMANDS:\n m = re.match(cmd.pattern, line)\n if m:\n gps = m.groups()\n return WireLink(cmd, gps[:-1], gps[-1])\n raise ValueError(repr(line))\n\n\ndef process_links(links):\n wires = WireValues()\n while links:\n remaining = []\n for link in links:\n if all(i in wires for i in link.inputs):\n link.command.function(wires, *link.inputs, link.output)\n else:\n remaining.append(link)\n links = remaining\n return wires\n\n\ndef main():\n lines = sys.stdin.read().strip().split('\\n')\n links = [create_link(line) for line in lines]\n wires = process_links(links)\n answer = wires['a']\n print('Part 1 wire a:', answer)\n index = next(i for i, link in enumerate(links) if link.output == 'b')\n links[index] = WireLink(assignment, [str(answer)], 'b')\n wires = process_links(links)\n answer = wires['a']\n print('Part 2 wire a:', answer)\n\n\nif __name__ == '__main__':\n main()\n",
"step-5": "#!/usr/bin/env python3\n\nimport sys\nimport re\n\nfrom collections import namedtuple\n\ndef isnum(name):\n return name.startswith('-') or name.isdigit()\n\nclass WireValues:\n def __init__(self):\n self.wires = {}\n def __getitem__(self, name):\n return int(name) if isnum(name) else self.wires[name]\n def __setitem__(self, name, value):\n self.wires[name] = value\n def __contains__(self, name):\n return isnum(name) or name in self.wires\n\nCommand = namedtuple('Command', 'pattern function')\nWireLink = namedtuple('WireLink', 'command inputs output')\n\nCOMMANDS = []\n\ndef make_command(expr):\n pattern = re.compile('^'+expr.replace('#', '([0-9a-z]+)')+'$')\n def command_maker(function):\n command = Command(pattern, function)\n COMMANDS.append(command)\n return command\n return command_maker\n\n@make_command('# -> #')\ndef assignment(wires, v1, name):\n wires[name] = wires[v1]\n\n@make_command('# AND # -> #')\ndef anding(wires, v1, v2, name):\n wires[name] = wires[v1] & wires[v2]\n\n@make_command('# OR # -> #')\ndef oring(wires, v1, v2, name):\n wires[name] = wires[v1] | wires[v2]\n\n@make_command('# LSHIFT # -> #')\ndef lshift(wires, v1, v2, name):\n wires[name] = wires[v1] << wires[v2]\n\n@make_command('# RSHIFT # -> #')\ndef rshift(wires, v1, v2, name):\n wires[name] = wires[v1] >> wires[v2]\n\n@make_command('NOT # -> #')\ndef notting(wires, v1, name):\n wires[name] = ((1<<16)-1)&~wires[v1]\n\ndef create_link(line):\n for cmd in COMMANDS:\n m = re.match(cmd.pattern, line)\n if m:\n gps = m.groups()\n return WireLink(cmd, gps[:-1], gps[-1])\n raise ValueError(repr(line))\n\ndef process_links(links):\n wires = WireValues()\n while links:\n remaining = []\n for link in links:\n if all(i in wires for i in link.inputs):\n link.command.function(wires, *link.inputs, link.output)\n else:\n remaining.append(link)\n links = remaining\n return wires\n\ndef main():\n lines = sys.stdin.read().strip().split('\\n')\n links = [create_link(line) for line in lines]\n wires = process_links(links)\n answer = wires['a']\n print(\"Part 1 wire a:\", answer)\n index = next(i for (i,link) in enumerate(links) if link.output=='b')\n links[index] = WireLink(assignment, [str(answer)], 'b')\n wires = process_links(links)\n answer = wires['a']\n print(\"Part 2 wire a:\", answer)\n\nif __name__ == '__main__':\n main()\n",
"step-ids": [
7,
14,
16,
18,
20
]
}
|
[
7,
14,
16,
18,
20
] |
<|reserved_special_token_0|>
def evaluate(sess, data, embds, model, logdir):
checkpoint_dir = '{}checkpoints'.format(logdir)
saver = tf.train.Saver()
sess.run(tf.global_variables_initializer())
sess.run(model.embedding_init, feed_dict={model.embedding_placeholder:
embds})
saver.restore(sess, checkpoint_dir)
predictions = model.predict()
x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_test()
feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths:
sent_lengths_val, model.seq_lengths: seq_lengths_val, model.
dropout_keep_prob: 1, model.max_seq_length: data.
test_max_seq_length, model.max_sent_length: data.test_max_sent_length}
pred = sess.run(predictions, feed_dict=feed_dict)
acc = metrics.accuracy_score(pred['labels'], pred['predictions'])
macro_f1 = metrics.f1_score(pred['labels'], pred['predictions'],
average='macro')
f1_0 = metrics.f1_score(pred['labels'], pred['predictions'], pos_label=0)
f1_1 = metrics.f1_score(pred['labels'], pred['predictions'], pos_label=1)
macro_precision = metrics.precision_score(pred['labels'], pred[
'predictions'], average='macro')
precision_0 = metrics.precision_score(pred['labels'], pred[
'predictions'], pos_label=0)
precision_1 = metrics.precision_score(pred['labels'], pred[
'predictions'], pos_label=1)
macro_recall = metrics.recall_score(pred['labels'], pred['predictions'],
average='macro')
recall_0 = metrics.recall_score(pred['labels'], pred['predictions'],
pos_label=0)
recall_1 = metrics.recall_score(pred['labels'], pred['predictions'],
pos_label=1)
return (acc, macro_f1, f1_0, f1_1, macro_precision, precision_0,
precision_1, macro_recall, recall_0, recall_1)
<|reserved_special_token_0|>
def get_attention_weights(data, embds):
tf.reset_default_graph()
it = 0
now = 'han_100d_163b_50cx_0.0001_0.5d'
with tf.Session() as sess:
model = HierarchicalAttention(num_classes=2, vocab_size=embds.shape
[0], embedding_size=embds.shape[1])
root_logdir = 'logs'
logdir = '{}/run-{}-{}/'.format(root_logdir, now, it)
checkpoint_dir = '{}checkpoints'.format(logdir)
saver = tf.train.Saver()
sess.run(tf.global_variables_initializer())
sess.run(model.embedding_init, feed_dict={model.embedding_placeholder:
embds})
saver.restore(sess, checkpoint_dir)
predictions = model.predict()
x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_val()
feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths:
sent_lengths_val, model.seq_lengths: seq_lengths_val, model.
dropout_keep_prob: 1, model.max_seq_length: data.val_max_seq_length,
model.max_sent_length: data.val_max_sent_length}
pred, a_word, a_sent = sess.run([predictions, model.alphas_word, model.
alphas_sent], feed_dict=feed_dict)
a_word = np.reshape(a_word, [-1, data.val_max_seq_length, data.
val_max_sent_length, 1])
zipped = list(zip(x_val, pred['labels'], pred['predictions'], pred[
'probabilities'], a_word, a_sent))
selection = [list(x) for x in zipped][133]
zipped_correct = [list(x) for x in zipped if x[1] == x[2] and x[1] == 1]
def get_predicted_prob(x):
return x[3][x[2]]
sorted_correct = sorted(zipped_correct, key=get_predicted_prob, reverse
=True)
print(sorted_correct[0:2])
selection_zipped_tuple = list(zip(selection[0], selection[4], selection[5])
)
selection_zipped = [list(x) for x in selection_zipped_tuple]
for s in selection_zipped:
s[0] = dp.translate_to_voc(s[0])
return selection_zipped
def visualize_attention(data):
data.reverse()
attention_weights_word = np.array([np.squeeze(x[1]) for x in data])
attention_weights_sent = np.array([np.squeeze(x[2]) for x in data])
sentence = np.array([x[0] for x in data])
max_idx = 0
empty_rows = 0
for i, s in enumerate(sentence):
idx = list(s).index('PAD')
attention_weights_word[i, idx:] = 0
if idx > max_idx:
max_idx = idx
if idx == 0:
empty_rows += 1
sentence = sentence[empty_rows:, 0:max_idx]
attention_weights_word = attention_weights_word[empty_rows:, 0:max_idx]
attention_weights_sent = attention_weights_sent[empty_rows:]
max_weight1 = attention_weights_word.max()
attention_weights_word = attention_weights_word / max_weight1
max_weight2 = attention_weights_sent.max()
attention_weights_sent = attention_weights_sent / max_weight2
print(np.shape(sentence))
MAX_FONTSIZE = 15
MIN_FONTSIZE = 10
def _font_size(word_len):
return max(int(round(MAX_FONTSIZE - 0.5 * word_len)), MIN_FONTSIZE)
def plot_attention(fname, attention_weights, attention_weights_sent,
sentence):
length = np.vectorize(lambda s: len(s))
max_word_len = length(sentence).max()
font_size_max_len = _font_size(max_word_len)
plt.figure(figsize=(attention_weights.shape[-1] * (max_word_len *
font_size_max_len / 100 + 0.5), attention_weights.shape[0]))
plt.title('Attention')
plt.xlabel('words')
plt.ylabel('batch')
pc_sent = plt.pcolor(attention_weights_sent, edgecolors='k',
linewidths=4, cmap='Reds', vmin=0.0, vmax=1.0)
pc_sent.update_scalarmappable()
pc = plt.pcolor(attention_weights, edgecolors='k', linewidths=4,
cmap='Blues', vmin=0.0, vmax=1.0)
pc.update_scalarmappable()
ax = pc.axes
for p, color, value in zip(pc.get_paths(), pc.get_facecolors(), pc.
get_array()):
x, y = p.vertices[:-2, :].mean(0)
if np.all(color[:3] > 0.5):
color = 0.0, 0.0, 0.0
else:
color = 1.0, 1.0, 1.0
j, i = int(floor(x)), int(floor(y))
if sentence[i, j] != 'PAD':
word = sentence[i, j]
else:
word = ''
fontsize = _font_size(len(word))
ax.text(x, y, word, ha='center', va='center', color=color, size
=fontsize)
idx = [(i + 0.5) for i in range(attention_weights_sent.shape[0])]
plt.yticks(idx, attention_weights_sent)
for l, i in zip(ax.yaxis.get_ticklabels(), pc_sent.get_facecolors()):
l.set_color(i)
l.set_backgroundcolor(i)
l.set_fontsize(15)
plt.colorbar(pc)
plt.savefig(fname)
plot_attention('attention_real_han.png', attention_weights_word, np.
array([[x] for x in attention_weights_sent]), sentence)
<|reserved_special_token_0|>
def get_confusion(data, embds):
tf.reset_default_graph()
now = 'banl2norm_100d_163b_[10,10,10,10]cx_0.0001_0.5d_accstop'
tf.reset_default_graph()
with tf.Session() as sess:
model = BucketizedAttention(num_classes=2, vocab_size=embds.shape[0
], embedding_size=embds.shape[1])
root_logdir = 'logs'
logdir = '{}/run-{}-{}/'.format(root_logdir, now, 0)
checkpoint_dir = '{}checkpoints'.format(logdir)
saver = tf.train.Saver()
sess.run(tf.global_variables_initializer())
sess.run(model.embedding_init, feed_dict={model.embedding_placeholder:
embds})
saver.restore(sess, checkpoint_dir)
predictions = model.predict()
x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_test()
feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths:
sent_lengths_val, model.seq_lengths: seq_lengths_val, model.
dropout_keep_prob: 1, model.max_seq_length: data.
test_max_seq_length, model.max_sent_length: data.test_max_sent_length}
pred = sess.run(predictions, feed_dict=feed_dict)
def fn(x):
if x == 0:
return 3
elif x == 1:
return 4
elif x == 2:
return 2
elif x == 3:
return 1
elif x == 4:
return 5
elif x == 5:
return 0
else:
return -1
labels = list(map(fn, pred['labels']))
predicts = list(map(fn, pred['predictions']))
cnf_matrix = metrics.confusion_matrix(labels, predicts)
plt.figure()
classes = ['True', 'False']
plot_confusion_matrix(cnf_matrix, classes=classes, title=
'Confusion matrix, without normalization')
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=classes, normalize=True,
title='Normalized confusion matrix')
plt.show()
def t_test(data, embds):
tf.reset_default_graph()
acc_ban = []
f1_ban = []
now = 'banl2norm_100d_163b_[10,10,10,10]cx_0.0001_0.5d_accstop'
for it in range(30):
tf.reset_default_graph()
with tf.Session() as sess:
lstm = BucketizedAttention(num_classes=2, vocab_size=embds.
shape[0], embedding_size=embds.shape[1])
root_logdir = 'logs'
logdir = '{}/run-{}-{}/'.format(root_logdir, now, it)
(acc, macro_f1, f1_0, f1_1, macro_precision, precision_0,
precision_1, macro_recall, recall_0, recall_1) = evaluate(sess,
data, embds, lstm, logdir)
print(acc)
acc_ban.append(acc)
f1_ban.append(macro_f1)
tf.reset_default_graph()
acc_cnn = [0.6313328137178488, 0.6157443491816056, 0.6110678098207326,
0.6141855027279813, 0.6165237724084178, 0.627435697583788,
0.6297739672642245, 0.6102883865939205, 0.6219797349961029,
0.6157443491816056, 0.6188620420888542, 0.6087295401402962,
0.6071706936866719, 0.6118472330475448, 0.6336710833982853,
0.6243180046765393, 0.6056118472330475, 0.6180826188620421,
0.6243180046765393, 0.6180826188620421, 0.6250974279033515,
0.6180826188620421, 0.6219797349961029, 0.6056118472330475,
0.6188620420888542, 0.6235385814497272, 0.6063912704598597,
0.5962587685113017, 0.6313328137178488, 0.6149649259547935]
f1_cnn = [0.625208977558574, 0.6067531970160148, 0.6109316669026621,
0.6020553751990241, 0.6090837028412892, 0.6094950282209589,
0.6172590617767771, 0.607132008544496, 0.6080345191414308,
0.5998115849326153, 0.6085742361143607, 0.6078430656223209,
0.5935340795944845, 0.5862705332027911, 0.6173464207571212,
0.6042373835890662, 0.6010630976083375, 0.5991259035560702,
0.5946686067851712, 0.5925791031776069, 0.6052042516849045,
0.6115004325794092, 0.6152243182460431, 0.6045333820662768,
0.6009255107006212, 0.6008323601423038, 0.5949095710792511,
0.59088816113464, 0.6062203096074071, 0.6064241216914394]
print(stats.ttest_ind(acc_ban, acc_cnn, equal_var=False))
print(stats.ttest_ind(f1_ban, f1_cnn, equal_var=False))
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def evaluate(sess, data, embds, model, logdir):
checkpoint_dir = '{}checkpoints'.format(logdir)
saver = tf.train.Saver()
sess.run(tf.global_variables_initializer())
sess.run(model.embedding_init, feed_dict={model.embedding_placeholder:
embds})
saver.restore(sess, checkpoint_dir)
predictions = model.predict()
x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_test()
feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths:
sent_lengths_val, model.seq_lengths: seq_lengths_val, model.
dropout_keep_prob: 1, model.max_seq_length: data.
test_max_seq_length, model.max_sent_length: data.test_max_sent_length}
pred = sess.run(predictions, feed_dict=feed_dict)
acc = metrics.accuracy_score(pred['labels'], pred['predictions'])
macro_f1 = metrics.f1_score(pred['labels'], pred['predictions'],
average='macro')
f1_0 = metrics.f1_score(pred['labels'], pred['predictions'], pos_label=0)
f1_1 = metrics.f1_score(pred['labels'], pred['predictions'], pos_label=1)
macro_precision = metrics.precision_score(pred['labels'], pred[
'predictions'], average='macro')
precision_0 = metrics.precision_score(pred['labels'], pred[
'predictions'], pos_label=0)
precision_1 = metrics.precision_score(pred['labels'], pred[
'predictions'], pos_label=1)
macro_recall = metrics.recall_score(pred['labels'], pred['predictions'],
average='macro')
recall_0 = metrics.recall_score(pred['labels'], pred['predictions'],
pos_label=0)
recall_1 = metrics.recall_score(pred['labels'], pred['predictions'],
pos_label=1)
return (acc, macro_f1, f1_0, f1_1, macro_precision, precision_0,
precision_1, macro_recall, recall_0, recall_1)
def run_std(data, embds):
selection = get_attention_weights(data, embds)
visualize_attention(selection)
tf.reset_default_graph()
results = []
now = 'han_100d_163b_50cx_0.0001_0.5d'
result = []
for it in range(5):
tf.reset_default_graph()
with tf.Session() as sess:
lstm = HierarchicalAttention(num_classes=2, vocab_size=embds.
shape[0], embedding_size=embds.shape[1])
root_logdir = 'logs'
logdir = '{}/run-{}-{}/'.format(root_logdir, now, it)
(acc, macro_f1, f1_0, f1_1, macro_precision, precision_0,
precision_1, macro_recall, recall_0, recall_1) = evaluate(sess,
data, embds, lstm, logdir)
print(logdir)
print(acc, ' ', macro_f1, ' ', f1_0, ' ', f1_1, ' ',
macro_precision, ' ', precision_0, ' ', precision_1, ' ',
macro_recall, ' ', recall_0, ' ', recall_1)
result.append([acc, macro_f1, f1_0, f1_1, macro_precision,
precision_0, precision_1, macro_recall, recall_0, recall_1])
result_averages = np.mean(result, axis=0)
print(result_averages)
result_stds = np.std(result, axis=0)
print(result_stds)
result = list(zip(result_averages, result_stds))
result.insert(0, now)
results.append(result)
print(result)
print('averages-------')
print(results)
print('------------')
def get_attention_weights(data, embds):
tf.reset_default_graph()
it = 0
now = 'han_100d_163b_50cx_0.0001_0.5d'
with tf.Session() as sess:
model = HierarchicalAttention(num_classes=2, vocab_size=embds.shape
[0], embedding_size=embds.shape[1])
root_logdir = 'logs'
logdir = '{}/run-{}-{}/'.format(root_logdir, now, it)
checkpoint_dir = '{}checkpoints'.format(logdir)
saver = tf.train.Saver()
sess.run(tf.global_variables_initializer())
sess.run(model.embedding_init, feed_dict={model.embedding_placeholder:
embds})
saver.restore(sess, checkpoint_dir)
predictions = model.predict()
x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_val()
feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths:
sent_lengths_val, model.seq_lengths: seq_lengths_val, model.
dropout_keep_prob: 1, model.max_seq_length: data.val_max_seq_length,
model.max_sent_length: data.val_max_sent_length}
pred, a_word, a_sent = sess.run([predictions, model.alphas_word, model.
alphas_sent], feed_dict=feed_dict)
a_word = np.reshape(a_word, [-1, data.val_max_seq_length, data.
val_max_sent_length, 1])
zipped = list(zip(x_val, pred['labels'], pred['predictions'], pred[
'probabilities'], a_word, a_sent))
selection = [list(x) for x in zipped][133]
zipped_correct = [list(x) for x in zipped if x[1] == x[2] and x[1] == 1]
def get_predicted_prob(x):
return x[3][x[2]]
sorted_correct = sorted(zipped_correct, key=get_predicted_prob, reverse
=True)
print(sorted_correct[0:2])
selection_zipped_tuple = list(zip(selection[0], selection[4], selection[5])
)
selection_zipped = [list(x) for x in selection_zipped_tuple]
for s in selection_zipped:
s[0] = dp.translate_to_voc(s[0])
return selection_zipped
def visualize_attention(data):
data.reverse()
attention_weights_word = np.array([np.squeeze(x[1]) for x in data])
attention_weights_sent = np.array([np.squeeze(x[2]) for x in data])
sentence = np.array([x[0] for x in data])
max_idx = 0
empty_rows = 0
for i, s in enumerate(sentence):
idx = list(s).index('PAD')
attention_weights_word[i, idx:] = 0
if idx > max_idx:
max_idx = idx
if idx == 0:
empty_rows += 1
sentence = sentence[empty_rows:, 0:max_idx]
attention_weights_word = attention_weights_word[empty_rows:, 0:max_idx]
attention_weights_sent = attention_weights_sent[empty_rows:]
max_weight1 = attention_weights_word.max()
attention_weights_word = attention_weights_word / max_weight1
max_weight2 = attention_weights_sent.max()
attention_weights_sent = attention_weights_sent / max_weight2
print(np.shape(sentence))
MAX_FONTSIZE = 15
MIN_FONTSIZE = 10
def _font_size(word_len):
return max(int(round(MAX_FONTSIZE - 0.5 * word_len)), MIN_FONTSIZE)
def plot_attention(fname, attention_weights, attention_weights_sent,
sentence):
length = np.vectorize(lambda s: len(s))
max_word_len = length(sentence).max()
font_size_max_len = _font_size(max_word_len)
plt.figure(figsize=(attention_weights.shape[-1] * (max_word_len *
font_size_max_len / 100 + 0.5), attention_weights.shape[0]))
plt.title('Attention')
plt.xlabel('words')
plt.ylabel('batch')
pc_sent = plt.pcolor(attention_weights_sent, edgecolors='k',
linewidths=4, cmap='Reds', vmin=0.0, vmax=1.0)
pc_sent.update_scalarmappable()
pc = plt.pcolor(attention_weights, edgecolors='k', linewidths=4,
cmap='Blues', vmin=0.0, vmax=1.0)
pc.update_scalarmappable()
ax = pc.axes
for p, color, value in zip(pc.get_paths(), pc.get_facecolors(), pc.
get_array()):
x, y = p.vertices[:-2, :].mean(0)
if np.all(color[:3] > 0.5):
color = 0.0, 0.0, 0.0
else:
color = 1.0, 1.0, 1.0
j, i = int(floor(x)), int(floor(y))
if sentence[i, j] != 'PAD':
word = sentence[i, j]
else:
word = ''
fontsize = _font_size(len(word))
ax.text(x, y, word, ha='center', va='center', color=color, size
=fontsize)
idx = [(i + 0.5) for i in range(attention_weights_sent.shape[0])]
plt.yticks(idx, attention_weights_sent)
for l, i in zip(ax.yaxis.get_ticklabels(), pc_sent.get_facecolors()):
l.set_color(i)
l.set_backgroundcolor(i)
l.set_fontsize(15)
plt.colorbar(pc)
plt.savefig(fname)
plot_attention('attention_real_han.png', attention_weights_word, np.
array([[x] for x in attention_weights_sent]), sentence)
<|reserved_special_token_0|>
def get_confusion(data, embds):
tf.reset_default_graph()
now = 'banl2norm_100d_163b_[10,10,10,10]cx_0.0001_0.5d_accstop'
tf.reset_default_graph()
with tf.Session() as sess:
model = BucketizedAttention(num_classes=2, vocab_size=embds.shape[0
], embedding_size=embds.shape[1])
root_logdir = 'logs'
logdir = '{}/run-{}-{}/'.format(root_logdir, now, 0)
checkpoint_dir = '{}checkpoints'.format(logdir)
saver = tf.train.Saver()
sess.run(tf.global_variables_initializer())
sess.run(model.embedding_init, feed_dict={model.embedding_placeholder:
embds})
saver.restore(sess, checkpoint_dir)
predictions = model.predict()
x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_test()
feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths:
sent_lengths_val, model.seq_lengths: seq_lengths_val, model.
dropout_keep_prob: 1, model.max_seq_length: data.
test_max_seq_length, model.max_sent_length: data.test_max_sent_length}
pred = sess.run(predictions, feed_dict=feed_dict)
def fn(x):
if x == 0:
return 3
elif x == 1:
return 4
elif x == 2:
return 2
elif x == 3:
return 1
elif x == 4:
return 5
elif x == 5:
return 0
else:
return -1
labels = list(map(fn, pred['labels']))
predicts = list(map(fn, pred['predictions']))
cnf_matrix = metrics.confusion_matrix(labels, predicts)
plt.figure()
classes = ['True', 'False']
plot_confusion_matrix(cnf_matrix, classes=classes, title=
'Confusion matrix, without normalization')
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=classes, normalize=True,
title='Normalized confusion matrix')
plt.show()
def t_test(data, embds):
tf.reset_default_graph()
acc_ban = []
f1_ban = []
now = 'banl2norm_100d_163b_[10,10,10,10]cx_0.0001_0.5d_accstop'
for it in range(30):
tf.reset_default_graph()
with tf.Session() as sess:
lstm = BucketizedAttention(num_classes=2, vocab_size=embds.
shape[0], embedding_size=embds.shape[1])
root_logdir = 'logs'
logdir = '{}/run-{}-{}/'.format(root_logdir, now, it)
(acc, macro_f1, f1_0, f1_1, macro_precision, precision_0,
precision_1, macro_recall, recall_0, recall_1) = evaluate(sess,
data, embds, lstm, logdir)
print(acc)
acc_ban.append(acc)
f1_ban.append(macro_f1)
tf.reset_default_graph()
acc_cnn = [0.6313328137178488, 0.6157443491816056, 0.6110678098207326,
0.6141855027279813, 0.6165237724084178, 0.627435697583788,
0.6297739672642245, 0.6102883865939205, 0.6219797349961029,
0.6157443491816056, 0.6188620420888542, 0.6087295401402962,
0.6071706936866719, 0.6118472330475448, 0.6336710833982853,
0.6243180046765393, 0.6056118472330475, 0.6180826188620421,
0.6243180046765393, 0.6180826188620421, 0.6250974279033515,
0.6180826188620421, 0.6219797349961029, 0.6056118472330475,
0.6188620420888542, 0.6235385814497272, 0.6063912704598597,
0.5962587685113017, 0.6313328137178488, 0.6149649259547935]
f1_cnn = [0.625208977558574, 0.6067531970160148, 0.6109316669026621,
0.6020553751990241, 0.6090837028412892, 0.6094950282209589,
0.6172590617767771, 0.607132008544496, 0.6080345191414308,
0.5998115849326153, 0.6085742361143607, 0.6078430656223209,
0.5935340795944845, 0.5862705332027911, 0.6173464207571212,
0.6042373835890662, 0.6010630976083375, 0.5991259035560702,
0.5946686067851712, 0.5925791031776069, 0.6052042516849045,
0.6115004325794092, 0.6152243182460431, 0.6045333820662768,
0.6009255107006212, 0.6008323601423038, 0.5949095710792511,
0.59088816113464, 0.6062203096074071, 0.6064241216914394]
print(stats.ttest_ind(acc_ban, acc_cnn, equal_var=False))
print(stats.ttest_ind(f1_ban, f1_cnn, equal_var=False))
<|reserved_special_token_1|>
<|reserved_special_token_0|>
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
def evaluate(sess, data, embds, model, logdir):
checkpoint_dir = '{}checkpoints'.format(logdir)
saver = tf.train.Saver()
sess.run(tf.global_variables_initializer())
sess.run(model.embedding_init, feed_dict={model.embedding_placeholder:
embds})
saver.restore(sess, checkpoint_dir)
predictions = model.predict()
x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_test()
feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths:
sent_lengths_val, model.seq_lengths: seq_lengths_val, model.
dropout_keep_prob: 1, model.max_seq_length: data.
test_max_seq_length, model.max_sent_length: data.test_max_sent_length}
pred = sess.run(predictions, feed_dict=feed_dict)
acc = metrics.accuracy_score(pred['labels'], pred['predictions'])
macro_f1 = metrics.f1_score(pred['labels'], pred['predictions'],
average='macro')
f1_0 = metrics.f1_score(pred['labels'], pred['predictions'], pos_label=0)
f1_1 = metrics.f1_score(pred['labels'], pred['predictions'], pos_label=1)
macro_precision = metrics.precision_score(pred['labels'], pred[
'predictions'], average='macro')
precision_0 = metrics.precision_score(pred['labels'], pred[
'predictions'], pos_label=0)
precision_1 = metrics.precision_score(pred['labels'], pred[
'predictions'], pos_label=1)
macro_recall = metrics.recall_score(pred['labels'], pred['predictions'],
average='macro')
recall_0 = metrics.recall_score(pred['labels'], pred['predictions'],
pos_label=0)
recall_1 = metrics.recall_score(pred['labels'], pred['predictions'],
pos_label=1)
return (acc, macro_f1, f1_0, f1_1, macro_precision, precision_0,
precision_1, macro_recall, recall_0, recall_1)
def run_std(data, embds):
selection = get_attention_weights(data, embds)
visualize_attention(selection)
tf.reset_default_graph()
results = []
now = 'han_100d_163b_50cx_0.0001_0.5d'
result = []
for it in range(5):
tf.reset_default_graph()
with tf.Session() as sess:
lstm = HierarchicalAttention(num_classes=2, vocab_size=embds.
shape[0], embedding_size=embds.shape[1])
root_logdir = 'logs'
logdir = '{}/run-{}-{}/'.format(root_logdir, now, it)
(acc, macro_f1, f1_0, f1_1, macro_precision, precision_0,
precision_1, macro_recall, recall_0, recall_1) = evaluate(sess,
data, embds, lstm, logdir)
print(logdir)
print(acc, ' ', macro_f1, ' ', f1_0, ' ', f1_1, ' ',
macro_precision, ' ', precision_0, ' ', precision_1, ' ',
macro_recall, ' ', recall_0, ' ', recall_1)
result.append([acc, macro_f1, f1_0, f1_1, macro_precision,
precision_0, precision_1, macro_recall, recall_0, recall_1])
result_averages = np.mean(result, axis=0)
print(result_averages)
result_stds = np.std(result, axis=0)
print(result_stds)
result = list(zip(result_averages, result_stds))
result.insert(0, now)
results.append(result)
print(result)
print('averages-------')
print(results)
print('------------')
def get_attention_weights(data, embds):
tf.reset_default_graph()
it = 0
now = 'han_100d_163b_50cx_0.0001_0.5d'
with tf.Session() as sess:
model = HierarchicalAttention(num_classes=2, vocab_size=embds.shape
[0], embedding_size=embds.shape[1])
root_logdir = 'logs'
logdir = '{}/run-{}-{}/'.format(root_logdir, now, it)
checkpoint_dir = '{}checkpoints'.format(logdir)
saver = tf.train.Saver()
sess.run(tf.global_variables_initializer())
sess.run(model.embedding_init, feed_dict={model.embedding_placeholder:
embds})
saver.restore(sess, checkpoint_dir)
predictions = model.predict()
x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_val()
feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths:
sent_lengths_val, model.seq_lengths: seq_lengths_val, model.
dropout_keep_prob: 1, model.max_seq_length: data.val_max_seq_length,
model.max_sent_length: data.val_max_sent_length}
pred, a_word, a_sent = sess.run([predictions, model.alphas_word, model.
alphas_sent], feed_dict=feed_dict)
a_word = np.reshape(a_word, [-1, data.val_max_seq_length, data.
val_max_sent_length, 1])
zipped = list(zip(x_val, pred['labels'], pred['predictions'], pred[
'probabilities'], a_word, a_sent))
selection = [list(x) for x in zipped][133]
zipped_correct = [list(x) for x in zipped if x[1] == x[2] and x[1] == 1]
def get_predicted_prob(x):
return x[3][x[2]]
sorted_correct = sorted(zipped_correct, key=get_predicted_prob, reverse
=True)
print(sorted_correct[0:2])
selection_zipped_tuple = list(zip(selection[0], selection[4], selection[5])
)
selection_zipped = [list(x) for x in selection_zipped_tuple]
for s in selection_zipped:
s[0] = dp.translate_to_voc(s[0])
return selection_zipped
def visualize_attention(data):
data.reverse()
attention_weights_word = np.array([np.squeeze(x[1]) for x in data])
attention_weights_sent = np.array([np.squeeze(x[2]) for x in data])
sentence = np.array([x[0] for x in data])
max_idx = 0
empty_rows = 0
for i, s in enumerate(sentence):
idx = list(s).index('PAD')
attention_weights_word[i, idx:] = 0
if idx > max_idx:
max_idx = idx
if idx == 0:
empty_rows += 1
sentence = sentence[empty_rows:, 0:max_idx]
attention_weights_word = attention_weights_word[empty_rows:, 0:max_idx]
attention_weights_sent = attention_weights_sent[empty_rows:]
max_weight1 = attention_weights_word.max()
attention_weights_word = attention_weights_word / max_weight1
max_weight2 = attention_weights_sent.max()
attention_weights_sent = attention_weights_sent / max_weight2
print(np.shape(sentence))
MAX_FONTSIZE = 15
MIN_FONTSIZE = 10
def _font_size(word_len):
return max(int(round(MAX_FONTSIZE - 0.5 * word_len)), MIN_FONTSIZE)
def plot_attention(fname, attention_weights, attention_weights_sent,
sentence):
length = np.vectorize(lambda s: len(s))
max_word_len = length(sentence).max()
font_size_max_len = _font_size(max_word_len)
plt.figure(figsize=(attention_weights.shape[-1] * (max_word_len *
font_size_max_len / 100 + 0.5), attention_weights.shape[0]))
plt.title('Attention')
plt.xlabel('words')
plt.ylabel('batch')
pc_sent = plt.pcolor(attention_weights_sent, edgecolors='k',
linewidths=4, cmap='Reds', vmin=0.0, vmax=1.0)
pc_sent.update_scalarmappable()
pc = plt.pcolor(attention_weights, edgecolors='k', linewidths=4,
cmap='Blues', vmin=0.0, vmax=1.0)
pc.update_scalarmappable()
ax = pc.axes
for p, color, value in zip(pc.get_paths(), pc.get_facecolors(), pc.
get_array()):
x, y = p.vertices[:-2, :].mean(0)
if np.all(color[:3] > 0.5):
color = 0.0, 0.0, 0.0
else:
color = 1.0, 1.0, 1.0
j, i = int(floor(x)), int(floor(y))
if sentence[i, j] != 'PAD':
word = sentence[i, j]
else:
word = ''
fontsize = _font_size(len(word))
ax.text(x, y, word, ha='center', va='center', color=color, size
=fontsize)
idx = [(i + 0.5) for i in range(attention_weights_sent.shape[0])]
plt.yticks(idx, attention_weights_sent)
for l, i in zip(ax.yaxis.get_ticklabels(), pc_sent.get_facecolors()):
l.set_color(i)
l.set_backgroundcolor(i)
l.set_fontsize(15)
plt.colorbar(pc)
plt.savefig(fname)
plot_attention('attention_real_han.png', attention_weights_word, np.
array([[x] for x in attention_weights_sent]), sentence)
def plot_confusion_matrix(cm, classes, normalize=False, title=
'Confusion matrix', cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print('Normalized confusion matrix')
else:
print('Confusion matrix, without normalization')
print(cm)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.0
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt), horizontalalignment='center',
color='white' if cm[i, j] > thresh else 'black')
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
def get_confusion(data, embds):
tf.reset_default_graph()
now = 'banl2norm_100d_163b_[10,10,10,10]cx_0.0001_0.5d_accstop'
tf.reset_default_graph()
with tf.Session() as sess:
model = BucketizedAttention(num_classes=2, vocab_size=embds.shape[0
], embedding_size=embds.shape[1])
root_logdir = 'logs'
logdir = '{}/run-{}-{}/'.format(root_logdir, now, 0)
checkpoint_dir = '{}checkpoints'.format(logdir)
saver = tf.train.Saver()
sess.run(tf.global_variables_initializer())
sess.run(model.embedding_init, feed_dict={model.embedding_placeholder:
embds})
saver.restore(sess, checkpoint_dir)
predictions = model.predict()
x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_test()
feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths:
sent_lengths_val, model.seq_lengths: seq_lengths_val, model.
dropout_keep_prob: 1, model.max_seq_length: data.
test_max_seq_length, model.max_sent_length: data.test_max_sent_length}
pred = sess.run(predictions, feed_dict=feed_dict)
def fn(x):
if x == 0:
return 3
elif x == 1:
return 4
elif x == 2:
return 2
elif x == 3:
return 1
elif x == 4:
return 5
elif x == 5:
return 0
else:
return -1
labels = list(map(fn, pred['labels']))
predicts = list(map(fn, pred['predictions']))
cnf_matrix = metrics.confusion_matrix(labels, predicts)
plt.figure()
classes = ['True', 'False']
plot_confusion_matrix(cnf_matrix, classes=classes, title=
'Confusion matrix, without normalization')
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=classes, normalize=True,
title='Normalized confusion matrix')
plt.show()
def t_test(data, embds):
tf.reset_default_graph()
acc_ban = []
f1_ban = []
now = 'banl2norm_100d_163b_[10,10,10,10]cx_0.0001_0.5d_accstop'
for it in range(30):
tf.reset_default_graph()
with tf.Session() as sess:
lstm = BucketizedAttention(num_classes=2, vocab_size=embds.
shape[0], embedding_size=embds.shape[1])
root_logdir = 'logs'
logdir = '{}/run-{}-{}/'.format(root_logdir, now, it)
(acc, macro_f1, f1_0, f1_1, macro_precision, precision_0,
precision_1, macro_recall, recall_0, recall_1) = evaluate(sess,
data, embds, lstm, logdir)
print(acc)
acc_ban.append(acc)
f1_ban.append(macro_f1)
tf.reset_default_graph()
acc_cnn = [0.6313328137178488, 0.6157443491816056, 0.6110678098207326,
0.6141855027279813, 0.6165237724084178, 0.627435697583788,
0.6297739672642245, 0.6102883865939205, 0.6219797349961029,
0.6157443491816056, 0.6188620420888542, 0.6087295401402962,
0.6071706936866719, 0.6118472330475448, 0.6336710833982853,
0.6243180046765393, 0.6056118472330475, 0.6180826188620421,
0.6243180046765393, 0.6180826188620421, 0.6250974279033515,
0.6180826188620421, 0.6219797349961029, 0.6056118472330475,
0.6188620420888542, 0.6235385814497272, 0.6063912704598597,
0.5962587685113017, 0.6313328137178488, 0.6149649259547935]
f1_cnn = [0.625208977558574, 0.6067531970160148, 0.6109316669026621,
0.6020553751990241, 0.6090837028412892, 0.6094950282209589,
0.6172590617767771, 0.607132008544496, 0.6080345191414308,
0.5998115849326153, 0.6085742361143607, 0.6078430656223209,
0.5935340795944845, 0.5862705332027911, 0.6173464207571212,
0.6042373835890662, 0.6010630976083375, 0.5991259035560702,
0.5946686067851712, 0.5925791031776069, 0.6052042516849045,
0.6115004325794092, 0.6152243182460431, 0.6045333820662768,
0.6009255107006212, 0.6008323601423038, 0.5949095710792511,
0.59088816113464, 0.6062203096074071, 0.6064241216914394]
print(stats.ttest_ind(acc_ban, acc_cnn, equal_var=False))
print(stats.ttest_ind(f1_ban, f1_cnn, equal_var=False))
<|reserved_special_token_1|>
import tensorflow as tf
import numpy as np
from datetime import datetime
import os
from CNN import CNN
from LSTM import LSTM
from BiLSTM import BiLSTM
from SLAN import Attention
from HAN2 import HierarchicalAttention
import sklearn.metrics as metrics
import DataProcessor as dp
import matplotlib.pyplot as plt
import numpy as np
import itertools
from scipy import stats
from math import floor
from BAN import BucketizedAttention
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
def evaluate(sess, data, embds, model, logdir):
checkpoint_dir = '{}checkpoints'.format(logdir)
saver = tf.train.Saver()
sess.run(tf.global_variables_initializer())
sess.run(model.embedding_init, feed_dict={model.embedding_placeholder:
embds})
saver.restore(sess, checkpoint_dir)
predictions = model.predict()
x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_test()
feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths:
sent_lengths_val, model.seq_lengths: seq_lengths_val, model.
dropout_keep_prob: 1, model.max_seq_length: data.
test_max_seq_length, model.max_sent_length: data.test_max_sent_length}
pred = sess.run(predictions, feed_dict=feed_dict)
acc = metrics.accuracy_score(pred['labels'], pred['predictions'])
macro_f1 = metrics.f1_score(pred['labels'], pred['predictions'],
average='macro')
f1_0 = metrics.f1_score(pred['labels'], pred['predictions'], pos_label=0)
f1_1 = metrics.f1_score(pred['labels'], pred['predictions'], pos_label=1)
macro_precision = metrics.precision_score(pred['labels'], pred[
'predictions'], average='macro')
precision_0 = metrics.precision_score(pred['labels'], pred[
'predictions'], pos_label=0)
precision_1 = metrics.precision_score(pred['labels'], pred[
'predictions'], pos_label=1)
macro_recall = metrics.recall_score(pred['labels'], pred['predictions'],
average='macro')
recall_0 = metrics.recall_score(pred['labels'], pred['predictions'],
pos_label=0)
recall_1 = metrics.recall_score(pred['labels'], pred['predictions'],
pos_label=1)
return (acc, macro_f1, f1_0, f1_1, macro_precision, precision_0,
precision_1, macro_recall, recall_0, recall_1)
def run_std(data, embds):
selection = get_attention_weights(data, embds)
visualize_attention(selection)
tf.reset_default_graph()
results = []
now = 'han_100d_163b_50cx_0.0001_0.5d'
result = []
for it in range(5):
tf.reset_default_graph()
with tf.Session() as sess:
lstm = HierarchicalAttention(num_classes=2, vocab_size=embds.
shape[0], embedding_size=embds.shape[1])
root_logdir = 'logs'
logdir = '{}/run-{}-{}/'.format(root_logdir, now, it)
(acc, macro_f1, f1_0, f1_1, macro_precision, precision_0,
precision_1, macro_recall, recall_0, recall_1) = evaluate(sess,
data, embds, lstm, logdir)
print(logdir)
print(acc, ' ', macro_f1, ' ', f1_0, ' ', f1_1, ' ',
macro_precision, ' ', precision_0, ' ', precision_1, ' ',
macro_recall, ' ', recall_0, ' ', recall_1)
result.append([acc, macro_f1, f1_0, f1_1, macro_precision,
precision_0, precision_1, macro_recall, recall_0, recall_1])
result_averages = np.mean(result, axis=0)
print(result_averages)
result_stds = np.std(result, axis=0)
print(result_stds)
result = list(zip(result_averages, result_stds))
result.insert(0, now)
results.append(result)
print(result)
print('averages-------')
print(results)
print('------------')
def get_attention_weights(data, embds):
tf.reset_default_graph()
it = 0
now = 'han_100d_163b_50cx_0.0001_0.5d'
with tf.Session() as sess:
model = HierarchicalAttention(num_classes=2, vocab_size=embds.shape
[0], embedding_size=embds.shape[1])
root_logdir = 'logs'
logdir = '{}/run-{}-{}/'.format(root_logdir, now, it)
checkpoint_dir = '{}checkpoints'.format(logdir)
saver = tf.train.Saver()
sess.run(tf.global_variables_initializer())
sess.run(model.embedding_init, feed_dict={model.embedding_placeholder:
embds})
saver.restore(sess, checkpoint_dir)
predictions = model.predict()
x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_val()
feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths:
sent_lengths_val, model.seq_lengths: seq_lengths_val, model.
dropout_keep_prob: 1, model.max_seq_length: data.val_max_seq_length,
model.max_sent_length: data.val_max_sent_length}
pred, a_word, a_sent = sess.run([predictions, model.alphas_word, model.
alphas_sent], feed_dict=feed_dict)
a_word = np.reshape(a_word, [-1, data.val_max_seq_length, data.
val_max_sent_length, 1])
zipped = list(zip(x_val, pred['labels'], pred['predictions'], pred[
'probabilities'], a_word, a_sent))
selection = [list(x) for x in zipped][133]
zipped_correct = [list(x) for x in zipped if x[1] == x[2] and x[1] == 1]
def get_predicted_prob(x):
return x[3][x[2]]
sorted_correct = sorted(zipped_correct, key=get_predicted_prob, reverse
=True)
print(sorted_correct[0:2])
selection_zipped_tuple = list(zip(selection[0], selection[4], selection[5])
)
selection_zipped = [list(x) for x in selection_zipped_tuple]
for s in selection_zipped:
s[0] = dp.translate_to_voc(s[0])
return selection_zipped
def visualize_attention(data):
data.reverse()
attention_weights_word = np.array([np.squeeze(x[1]) for x in data])
attention_weights_sent = np.array([np.squeeze(x[2]) for x in data])
sentence = np.array([x[0] for x in data])
max_idx = 0
empty_rows = 0
for i, s in enumerate(sentence):
idx = list(s).index('PAD')
attention_weights_word[i, idx:] = 0
if idx > max_idx:
max_idx = idx
if idx == 0:
empty_rows += 1
sentence = sentence[empty_rows:, 0:max_idx]
attention_weights_word = attention_weights_word[empty_rows:, 0:max_idx]
attention_weights_sent = attention_weights_sent[empty_rows:]
max_weight1 = attention_weights_word.max()
attention_weights_word = attention_weights_word / max_weight1
max_weight2 = attention_weights_sent.max()
attention_weights_sent = attention_weights_sent / max_weight2
print(np.shape(sentence))
MAX_FONTSIZE = 15
MIN_FONTSIZE = 10
def _font_size(word_len):
return max(int(round(MAX_FONTSIZE - 0.5 * word_len)), MIN_FONTSIZE)
def plot_attention(fname, attention_weights, attention_weights_sent,
sentence):
length = np.vectorize(lambda s: len(s))
max_word_len = length(sentence).max()
font_size_max_len = _font_size(max_word_len)
plt.figure(figsize=(attention_weights.shape[-1] * (max_word_len *
font_size_max_len / 100 + 0.5), attention_weights.shape[0]))
plt.title('Attention')
plt.xlabel('words')
plt.ylabel('batch')
pc_sent = plt.pcolor(attention_weights_sent, edgecolors='k',
linewidths=4, cmap='Reds', vmin=0.0, vmax=1.0)
pc_sent.update_scalarmappable()
pc = plt.pcolor(attention_weights, edgecolors='k', linewidths=4,
cmap='Blues', vmin=0.0, vmax=1.0)
pc.update_scalarmappable()
ax = pc.axes
for p, color, value in zip(pc.get_paths(), pc.get_facecolors(), pc.
get_array()):
x, y = p.vertices[:-2, :].mean(0)
if np.all(color[:3] > 0.5):
color = 0.0, 0.0, 0.0
else:
color = 1.0, 1.0, 1.0
j, i = int(floor(x)), int(floor(y))
if sentence[i, j] != 'PAD':
word = sentence[i, j]
else:
word = ''
fontsize = _font_size(len(word))
ax.text(x, y, word, ha='center', va='center', color=color, size
=fontsize)
idx = [(i + 0.5) for i in range(attention_weights_sent.shape[0])]
plt.yticks(idx, attention_weights_sent)
for l, i in zip(ax.yaxis.get_ticklabels(), pc_sent.get_facecolors()):
l.set_color(i)
l.set_backgroundcolor(i)
l.set_fontsize(15)
plt.colorbar(pc)
plt.savefig(fname)
plot_attention('attention_real_han.png', attention_weights_word, np.
array([[x] for x in attention_weights_sent]), sentence)
def plot_confusion_matrix(cm, classes, normalize=False, title=
'Confusion matrix', cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print('Normalized confusion matrix')
else:
print('Confusion matrix, without normalization')
print(cm)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.0
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt), horizontalalignment='center',
color='white' if cm[i, j] > thresh else 'black')
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
def get_confusion(data, embds):
tf.reset_default_graph()
now = 'banl2norm_100d_163b_[10,10,10,10]cx_0.0001_0.5d_accstop'
tf.reset_default_graph()
with tf.Session() as sess:
model = BucketizedAttention(num_classes=2, vocab_size=embds.shape[0
], embedding_size=embds.shape[1])
root_logdir = 'logs'
logdir = '{}/run-{}-{}/'.format(root_logdir, now, 0)
checkpoint_dir = '{}checkpoints'.format(logdir)
saver = tf.train.Saver()
sess.run(tf.global_variables_initializer())
sess.run(model.embedding_init, feed_dict={model.embedding_placeholder:
embds})
saver.restore(sess, checkpoint_dir)
predictions = model.predict()
x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_test()
feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths:
sent_lengths_val, model.seq_lengths: seq_lengths_val, model.
dropout_keep_prob: 1, model.max_seq_length: data.
test_max_seq_length, model.max_sent_length: data.test_max_sent_length}
pred = sess.run(predictions, feed_dict=feed_dict)
def fn(x):
if x == 0:
return 3
elif x == 1:
return 4
elif x == 2:
return 2
elif x == 3:
return 1
elif x == 4:
return 5
elif x == 5:
return 0
else:
return -1
labels = list(map(fn, pred['labels']))
predicts = list(map(fn, pred['predictions']))
cnf_matrix = metrics.confusion_matrix(labels, predicts)
plt.figure()
classes = ['True', 'False']
plot_confusion_matrix(cnf_matrix, classes=classes, title=
'Confusion matrix, without normalization')
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=classes, normalize=True,
title='Normalized confusion matrix')
plt.show()
def t_test(data, embds):
tf.reset_default_graph()
acc_ban = []
f1_ban = []
now = 'banl2norm_100d_163b_[10,10,10,10]cx_0.0001_0.5d_accstop'
for it in range(30):
tf.reset_default_graph()
with tf.Session() as sess:
lstm = BucketizedAttention(num_classes=2, vocab_size=embds.
shape[0], embedding_size=embds.shape[1])
root_logdir = 'logs'
logdir = '{}/run-{}-{}/'.format(root_logdir, now, it)
(acc, macro_f1, f1_0, f1_1, macro_precision, precision_0,
precision_1, macro_recall, recall_0, recall_1) = evaluate(sess,
data, embds, lstm, logdir)
print(acc)
acc_ban.append(acc)
f1_ban.append(macro_f1)
tf.reset_default_graph()
acc_cnn = [0.6313328137178488, 0.6157443491816056, 0.6110678098207326,
0.6141855027279813, 0.6165237724084178, 0.627435697583788,
0.6297739672642245, 0.6102883865939205, 0.6219797349961029,
0.6157443491816056, 0.6188620420888542, 0.6087295401402962,
0.6071706936866719, 0.6118472330475448, 0.6336710833982853,
0.6243180046765393, 0.6056118472330475, 0.6180826188620421,
0.6243180046765393, 0.6180826188620421, 0.6250974279033515,
0.6180826188620421, 0.6219797349961029, 0.6056118472330475,
0.6188620420888542, 0.6235385814497272, 0.6063912704598597,
0.5962587685113017, 0.6313328137178488, 0.6149649259547935]
f1_cnn = [0.625208977558574, 0.6067531970160148, 0.6109316669026621,
0.6020553751990241, 0.6090837028412892, 0.6094950282209589,
0.6172590617767771, 0.607132008544496, 0.6080345191414308,
0.5998115849326153, 0.6085742361143607, 0.6078430656223209,
0.5935340795944845, 0.5862705332027911, 0.6173464207571212,
0.6042373835890662, 0.6010630976083375, 0.5991259035560702,
0.5946686067851712, 0.5925791031776069, 0.6052042516849045,
0.6115004325794092, 0.6152243182460431, 0.6045333820662768,
0.6009255107006212, 0.6008323601423038, 0.5949095710792511,
0.59088816113464, 0.6062203096074071, 0.6064241216914394]
print(stats.ttest_ind(acc_ban, acc_cnn, equal_var=False))
print(stats.ttest_ind(f1_ban, f1_cnn, equal_var=False))
<|reserved_special_token_1|>
import tensorflow as tf
import numpy as np
from datetime import datetime
import os
from CNN import CNN
from LSTM import LSTM
from BiLSTM import BiLSTM
from SLAN import Attention
from HAN2 import HierarchicalAttention
import sklearn.metrics as metrics
import DataProcessor as dp
import matplotlib.pyplot as plt
import numpy as np
import itertools
from scipy import stats
from math import floor
from BAN import BucketizedAttention
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
def evaluate(sess, data, embds, model, logdir):
checkpoint_dir = "{}checkpoints".format(logdir)
saver = tf.train.Saver()
#saver = tf.train.import_meta_graph("{}.meta".format(checkpoint_dir))
# Training model
#training_op, global_step = model.optimize()
sess.run(tf.global_variables_initializer())
sess.run(model.embedding_init, feed_dict={model.embedding_placeholder: embds})
saver.restore(sess, checkpoint_dir)
predictions = model.predict()
#print("Evaluation:")
x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_test()
feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths: sent_lengths_val,
model.seq_lengths: seq_lengths_val, model.dropout_keep_prob: 1,
model.max_seq_length: data.test_max_seq_length,
model.max_sent_length: data.test_max_sent_length
}
pred = sess.run(predictions, feed_dict=feed_dict)
acc = metrics.accuracy_score(pred['labels'], pred['predictions'])
macro_f1 = metrics.f1_score(pred['labels'], pred['predictions'], average="macro")
f1_0 = metrics.f1_score(pred['labels'], pred['predictions'], pos_label=0)
f1_1 = metrics.f1_score(pred['labels'], pred['predictions'], pos_label=1)
macro_precision = metrics.precision_score(pred['labels'], pred['predictions'], average="macro")
precision_0 = metrics.precision_score(pred['labels'], pred['predictions'], pos_label=0)
precision_1 = metrics.precision_score(pred['labels'], pred['predictions'], pos_label=1)
macro_recall = metrics.recall_score(pred['labels'], pred['predictions'], average="macro")
recall_0 = metrics.recall_score(pred['labels'], pred['predictions'], pos_label=0)
recall_1 = metrics.recall_score(pred['labels'], pred['predictions'], pos_label=1)
return (acc, macro_f1, f1_0, f1_1, macro_precision, precision_0, precision_1, macro_recall, recall_0, recall_1)
#return (acc, macro_f1, 1, 1, macro_precision, 1, 1, macro_recall, 1, 1)
def run_std(data, embds):
selection = get_attention_weights(data, embds)
visualize_attention(selection)
tf.reset_default_graph()
results = []
now = "han_100d_163b_50cx_0.0001_0.5d"
result = []
for it in range(5):
tf.reset_default_graph()
with tf.Session() as sess:
lstm = HierarchicalAttention(
num_classes=2,
vocab_size=embds.shape[0],
embedding_size=embds.shape[1]
)
root_logdir = "logs"
logdir = "{}/run-{}-{}/".format(root_logdir, now, it)
acc, macro_f1, f1_0, f1_1, macro_precision, precision_0, precision_1, macro_recall, recall_0, recall_1 = evaluate(
sess, data, embds, lstm, logdir)
print(logdir)
print(acc, " ", macro_f1, " ", f1_0, " ", f1_1, " ", macro_precision, " ", precision_0, " ",
precision_1, " ", macro_recall, " ", recall_0, " ", recall_1)
result.append(
[acc, macro_f1, f1_0, f1_1, macro_precision, precision_0, precision_1, macro_recall,
recall_0, recall_1])
result_averages = np.mean(result, axis=0)
print(result_averages)
result_stds = np.std(result, axis=0)
print(result_stds)
result = list(zip(result_averages, result_stds))
result.insert(0, now)
results.append(result)
print(result)
print("averages-------")
print(results)
print("------------")
def get_attention_weights(data, embds):
tf.reset_default_graph()
it = 0
now = "han_100d_163b_50cx_0.0001_0.5d"
with tf.Session() as sess:
model = HierarchicalAttention(
num_classes=2,
vocab_size=embds.shape[0],
embedding_size=embds.shape[1]
)
root_logdir = "logs"
logdir = "{}/run-{}-{}/".format(root_logdir, now, it)
checkpoint_dir = "{}checkpoints".format(logdir)
saver = tf.train.Saver()
# saver = tf.train.import_meta_graph("{}.meta".format(checkpoint_dir))
# Training model
# training_op, global_step = model.optimize()
sess.run(tf.global_variables_initializer())
sess.run(model.embedding_init, feed_dict={model.embedding_placeholder: embds})
saver.restore(sess, checkpoint_dir)
predictions = model.predict()
# print("Evaluation:")
x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_val()
feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths: sent_lengths_val,
model.seq_lengths: seq_lengths_val, model.dropout_keep_prob: 1,
model.max_seq_length: data.val_max_seq_length,
model.max_sent_length: data.val_max_sent_length
}
pred, a_word, a_sent = sess.run([predictions, model.alphas_word, model.alphas_sent], feed_dict=feed_dict)
#pred, a1, A = sess.run([predictions, model.alphas1, model.alphas2, model.alphas3, model.alphas4],
#feed_dict=feed_dict)
a_word = np.reshape(a_word, [-1, data.val_max_seq_length, data.val_max_sent_length, 1])
# filter on correct predictions
zipped = list(zip(x_val, pred['labels'], pred['predictions'], pred['probabilities'], a_word, a_sent))
# print(zipped[0:2])
selection = [list(x) for x in zipped][133]
zipped_correct = [list(x) for x in zipped if x[1]==x[2] and x[1] == 1]
# print(zipped_correct[0:2])
def get_predicted_prob(x):
return (x[3])[(x[2])]
sorted_correct = sorted(zipped_correct, key=get_predicted_prob, reverse=True)
print(sorted_correct[0:2])
#selection = sorted_correct[1]
selection_zipped_tuple = list(zip(selection[0], selection[4], selection[5]))
#selection_zipped_tuple = list(zip(selection[0], selection[4]))
selection_zipped = [list(x) for x in selection_zipped_tuple]
for s in selection_zipped:
s[0] = dp.translate_to_voc(s[0])
return selection_zipped
def visualize_attention(data):
#data = np.array(data)
data.reverse()
attention_weights_word = np.array([np.squeeze(x[1]) for x in data])
attention_weights_sent = np.array([np.squeeze(x[2]) for x in data])
#max_weight = attention_weights.max()
#attention_weights = attention_weights/max_weight # increase weights to make visualization clearer
#max_weight1 = np.array(attention_weights1.max(axis=-1))
#attention_weights1 = attention_weights1 / max_weight1[:, None] # increase weights to make visualization clearer
sentence = np.array([x[0] for x in data])
#labels = np.array(["label-{}, pred-{}, prob-{}".format(x[1], x[2], max(x[3])) for x in data])
max_idx = 0
empty_rows = 0
for i, s in enumerate(sentence):
idx = list(s).index("PAD")
attention_weights_word[i, idx:] = 0
# attention_weights3[i, idx:] = 0
# attention_weights4[i, idx:] = 0
if idx > max_idx:
max_idx = idx
if idx == 0:
empty_rows += 1
sentence = sentence[empty_rows:, 0:max_idx]
attention_weights_word = attention_weights_word[empty_rows:, 0:max_idx]
attention_weights_sent = attention_weights_sent[empty_rows:]
# attention_weights3 = attention_weights3[empty_rows:, 0:max_idx]
# attention_weights4 = attention_weights4[empty_rows:, 0:max_idx]
max_weight1 = attention_weights_word.max()
attention_weights_word = attention_weights_word / max_weight1 # increase weights to make visualization clearer
max_weight2 = attention_weights_sent.max()
attention_weights_sent = attention_weights_sent / max_weight2 # increase weights to make visualization clearer
# max_weight3 = attention_weights3.max()
# attention_weights3 = attention_weights3 / max_weight3 # increase weights to make visualization clearer
# max_weight4 = attention_weights4.max()
# attention_weights4 = attention_weights4 / max_weight4 # increase weights to make visualization clearer
#print(np.shape(attention_weights1))
print(np.shape(sentence))
#print(np.shape(labels))
MAX_FONTSIZE = 15
MIN_FONTSIZE = 10
def _font_size(word_len):
return max(int(round(MAX_FONTSIZE - 0.5 * word_len)), MIN_FONTSIZE)
def plot_attention(fname, attention_weights, attention_weights_sent, sentence):
length = np.vectorize(lambda s: len(s))
max_word_len = length(sentence).max()
font_size_max_len = _font_size(max_word_len)
plt.figure(figsize=(
attention_weights.shape[-1] * (max_word_len * font_size_max_len / 100 + 0.5), attention_weights.shape[0]))
plt.title("Attention")
plt.xlabel("words")
plt.ylabel("batch")
pc_sent = plt.pcolor(attention_weights_sent, edgecolors='k', linewidths=4, cmap='Reds', vmin=0.0, vmax=1.0)
pc_sent.update_scalarmappable()
pc = plt.pcolor(attention_weights, edgecolors='k', linewidths=4, cmap='Blues', vmin=0.0, vmax=1.0)
pc.update_scalarmappable()
ax = pc.axes
for p, color, value in zip(pc.get_paths(), pc.get_facecolors(), pc.get_array()):
x, y = p.vertices[:-2, :].mean(0)
if np.all(color[:3] > 0.5):
color = (0.0, 0.0, 0.0)
else:
color = (1.0, 1.0, 1.0)
j, i = int(floor(x)), int(floor(y))
if sentence[i, j] != "PAD":
word = sentence[i, j]
else:
word = ""
fontsize = _font_size(len(word))
ax.text(x, y, word, ha="center", va="center", color=color, size=fontsize)
idx = [i + 0.5 for i in range(attention_weights_sent.shape[0])]
plt.yticks(idx, attention_weights_sent)
for l, i in zip(ax.yaxis.get_ticklabels(), pc_sent.get_facecolors()):
l.set_color(i)
l.set_backgroundcolor(i)
l.set_fontsize(15)
plt.colorbar(pc)
plt.savefig(fname)
plot_attention("attention_real_han.png", attention_weights_word, np.array([[x] for x in attention_weights_sent]), sentence)
# plot_attention("attention_real3.png", attention_weights3, sentence)
# plot_attention("attention_real4.png", attention_weights4, sentence)
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
def get_confusion(data, embds):
tf.reset_default_graph()
now = "banl2norm_100d_163b_[10,10,10,10]cx_0.0001_0.5d_accstop"
tf.reset_default_graph()
with tf.Session() as sess:
model = BucketizedAttention(
num_classes=2,
vocab_size=embds.shape[0],
embedding_size=embds.shape[1]
)
root_logdir = "logs"
logdir = "{}/run-{}-{}/".format(root_logdir, now, 0)
checkpoint_dir = "{}checkpoints".format(logdir)
saver = tf.train.Saver()
sess.run(tf.global_variables_initializer())
sess.run(model.embedding_init, feed_dict={model.embedding_placeholder: embds})
saver.restore(sess, checkpoint_dir)
predictions = model.predict()
x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_test()
feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths: sent_lengths_val,
model.seq_lengths: seq_lengths_val, model.dropout_keep_prob: 1,
model.max_seq_length: data.test_max_seq_length,
model.max_sent_length: data.test_max_sent_length
}
pred = sess.run(predictions, feed_dict=feed_dict)
def fn(x):
if x == 0:
return 3
elif x == 1:
return 4
elif x == 2:
return 2
elif x == 3:
return 1
elif x == 4:
return 5
elif x == 5:
return 0
else:
return -1
labels = list(map(fn, pred['labels']))
predicts = list(map(fn, pred['predictions']))
cnf_matrix = metrics.confusion_matrix(labels, predicts)
# Plot non-normalized confusion matrix
plt.figure()
#classes = ["True", "Mostly-true", "Half-true", "Barely-true", "False", "Pants-on-fire"]
classes = ["True", "False"]
plot_confusion_matrix(cnf_matrix, classes=classes,
title='Confusion matrix, without normalization')
# Plot normalized confusion matrix
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=classes, normalize=True,
title='Normalized confusion matrix')
plt.show()
def t_test(data, embds):
tf.reset_default_graph()
acc_ban = []
f1_ban = []
now = "banl2norm_100d_163b_[10,10,10,10]cx_0.0001_0.5d_accstop"
for it in range(30):
tf.reset_default_graph()
with tf.Session() as sess:
lstm = BucketizedAttention(
num_classes=2,
vocab_size=embds.shape[0],
embedding_size=embds.shape[1]
)
root_logdir = "logs"
logdir = "{}/run-{}-{}/".format(root_logdir, now, it)
acc, macro_f1, f1_0, f1_1, macro_precision, precision_0, precision_1, macro_recall, recall_0, recall_1 = evaluate(
sess, data, embds, lstm, logdir)
print(acc)
acc_ban.append(acc)
f1_ban.append(macro_f1)
tf.reset_default_graph()
acc_cnn = [0.6313328137178488, 0.6157443491816056, 0.6110678098207326, 0.6141855027279813, 0.6165237724084178, 0.627435697583788, 0.6297739672642245, 0.6102883865939205, 0.6219797349961029, 0.6157443491816056, 0.6188620420888542, 0.6087295401402962, 0.6071706936866719, 0.6118472330475448, 0.6336710833982853, 0.6243180046765393, 0.6056118472330475, 0.6180826188620421, 0.6243180046765393, 0.6180826188620421, 0.6250974279033515, 0.6180826188620421, 0.6219797349961029, 0.6056118472330475, 0.6188620420888542, 0.6235385814497272, 0.6063912704598597, 0.5962587685113017, 0.6313328137178488, 0.6149649259547935]
f1_cnn = [0.625208977558574, 0.6067531970160148, 0.6109316669026621, 0.6020553751990241, 0.6090837028412892, 0.6094950282209589, 0.6172590617767771, 0.607132008544496, 0.6080345191414308, 0.5998115849326153, 0.6085742361143607, 0.6078430656223209, 0.5935340795944845, 0.5862705332027911, 0.6173464207571212, 0.6042373835890662, 0.6010630976083375, 0.5991259035560702, 0.5946686067851712, 0.5925791031776069, 0.6052042516849045, 0.6115004325794092, 0.6152243182460431, 0.6045333820662768, 0.6009255107006212, 0.6008323601423038, 0.5949095710792511, 0.59088816113464, 0.6062203096074071, 0.6064241216914394]
# now = "han_100d_163b_50cx_0.0001_0.5d"
# for it in range(30):
# tf.reset_default_graph()
# with tf.Session() as sess:
# lstm = HierarchicalAttention(
# num_classes=2,
# vocab_size=embds.shape[0],
# embedding_size=embds.shape[1]
# )
# root_logdir = "logs"
# logdir = "{}/run-{}-{}/".format(root_logdir, now, it)
# acc, macro_f1, f1_0, f1_1, macro_precision, precision_0, precision_1, macro_recall, recall_0, recall_1 = evaluate(
# sess, data, embds, lstm, logdir)
# print(acc)
# acc_han.append(acc)
# f1_han.append(macro_f1)
print(stats.ttest_ind(acc_ban, acc_cnn, equal_var=False))
print(stats.ttest_ind(f1_ban, f1_cnn, equal_var=False))
|
flexible
|
{
"blob_id": "3aff6bdfd7c2ffd57af7bb5d0079a8a428e02331",
"index": 1284,
"step-1": "<mask token>\n\n\ndef evaluate(sess, data, embds, model, logdir):\n checkpoint_dir = '{}checkpoints'.format(logdir)\n saver = tf.train.Saver()\n sess.run(tf.global_variables_initializer())\n sess.run(model.embedding_init, feed_dict={model.embedding_placeholder:\n embds})\n saver.restore(sess, checkpoint_dir)\n predictions = model.predict()\n x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_test()\n feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths:\n sent_lengths_val, model.seq_lengths: seq_lengths_val, model.\n dropout_keep_prob: 1, model.max_seq_length: data.\n test_max_seq_length, model.max_sent_length: data.test_max_sent_length}\n pred = sess.run(predictions, feed_dict=feed_dict)\n acc = metrics.accuracy_score(pred['labels'], pred['predictions'])\n macro_f1 = metrics.f1_score(pred['labels'], pred['predictions'],\n average='macro')\n f1_0 = metrics.f1_score(pred['labels'], pred['predictions'], pos_label=0)\n f1_1 = metrics.f1_score(pred['labels'], pred['predictions'], pos_label=1)\n macro_precision = metrics.precision_score(pred['labels'], pred[\n 'predictions'], average='macro')\n precision_0 = metrics.precision_score(pred['labels'], pred[\n 'predictions'], pos_label=0)\n precision_1 = metrics.precision_score(pred['labels'], pred[\n 'predictions'], pos_label=1)\n macro_recall = metrics.recall_score(pred['labels'], pred['predictions'],\n average='macro')\n recall_0 = metrics.recall_score(pred['labels'], pred['predictions'],\n pos_label=0)\n recall_1 = metrics.recall_score(pred['labels'], pred['predictions'],\n pos_label=1)\n return (acc, macro_f1, f1_0, f1_1, macro_precision, precision_0,\n precision_1, macro_recall, recall_0, recall_1)\n\n\n<mask token>\n\n\ndef get_attention_weights(data, embds):\n tf.reset_default_graph()\n it = 0\n now = 'han_100d_163b_50cx_0.0001_0.5d'\n with tf.Session() as sess:\n model = HierarchicalAttention(num_classes=2, vocab_size=embds.shape\n [0], embedding_size=embds.shape[1])\n root_logdir = 'logs'\n logdir = '{}/run-{}-{}/'.format(root_logdir, now, it)\n checkpoint_dir = '{}checkpoints'.format(logdir)\n saver = tf.train.Saver()\n sess.run(tf.global_variables_initializer())\n sess.run(model.embedding_init, feed_dict={model.embedding_placeholder:\n embds})\n saver.restore(sess, checkpoint_dir)\n predictions = model.predict()\n x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_val()\n feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths:\n sent_lengths_val, model.seq_lengths: seq_lengths_val, model.\n dropout_keep_prob: 1, model.max_seq_length: data.val_max_seq_length,\n model.max_sent_length: data.val_max_sent_length}\n pred, a_word, a_sent = sess.run([predictions, model.alphas_word, model.\n alphas_sent], feed_dict=feed_dict)\n a_word = np.reshape(a_word, [-1, data.val_max_seq_length, data.\n val_max_sent_length, 1])\n zipped = list(zip(x_val, pred['labels'], pred['predictions'], pred[\n 'probabilities'], a_word, a_sent))\n selection = [list(x) for x in zipped][133]\n zipped_correct = [list(x) for x in zipped if x[1] == x[2] and x[1] == 1]\n\n def get_predicted_prob(x):\n return x[3][x[2]]\n sorted_correct = sorted(zipped_correct, key=get_predicted_prob, reverse\n =True)\n print(sorted_correct[0:2])\n selection_zipped_tuple = list(zip(selection[0], selection[4], selection[5])\n )\n selection_zipped = [list(x) for x in selection_zipped_tuple]\n for s in selection_zipped:\n s[0] = dp.translate_to_voc(s[0])\n return selection_zipped\n\n\ndef visualize_attention(data):\n data.reverse()\n attention_weights_word = np.array([np.squeeze(x[1]) for x in data])\n attention_weights_sent = np.array([np.squeeze(x[2]) for x in data])\n sentence = np.array([x[0] for x in data])\n max_idx = 0\n empty_rows = 0\n for i, s in enumerate(sentence):\n idx = list(s).index('PAD')\n attention_weights_word[i, idx:] = 0\n if idx > max_idx:\n max_idx = idx\n if idx == 0:\n empty_rows += 1\n sentence = sentence[empty_rows:, 0:max_idx]\n attention_weights_word = attention_weights_word[empty_rows:, 0:max_idx]\n attention_weights_sent = attention_weights_sent[empty_rows:]\n max_weight1 = attention_weights_word.max()\n attention_weights_word = attention_weights_word / max_weight1\n max_weight2 = attention_weights_sent.max()\n attention_weights_sent = attention_weights_sent / max_weight2\n print(np.shape(sentence))\n MAX_FONTSIZE = 15\n MIN_FONTSIZE = 10\n\n def _font_size(word_len):\n return max(int(round(MAX_FONTSIZE - 0.5 * word_len)), MIN_FONTSIZE)\n\n def plot_attention(fname, attention_weights, attention_weights_sent,\n sentence):\n length = np.vectorize(lambda s: len(s))\n max_word_len = length(sentence).max()\n font_size_max_len = _font_size(max_word_len)\n plt.figure(figsize=(attention_weights.shape[-1] * (max_word_len *\n font_size_max_len / 100 + 0.5), attention_weights.shape[0]))\n plt.title('Attention')\n plt.xlabel('words')\n plt.ylabel('batch')\n pc_sent = plt.pcolor(attention_weights_sent, edgecolors='k',\n linewidths=4, cmap='Reds', vmin=0.0, vmax=1.0)\n pc_sent.update_scalarmappable()\n pc = plt.pcolor(attention_weights, edgecolors='k', linewidths=4,\n cmap='Blues', vmin=0.0, vmax=1.0)\n pc.update_scalarmappable()\n ax = pc.axes\n for p, color, value in zip(pc.get_paths(), pc.get_facecolors(), pc.\n get_array()):\n x, y = p.vertices[:-2, :].mean(0)\n if np.all(color[:3] > 0.5):\n color = 0.0, 0.0, 0.0\n else:\n color = 1.0, 1.0, 1.0\n j, i = int(floor(x)), int(floor(y))\n if sentence[i, j] != 'PAD':\n word = sentence[i, j]\n else:\n word = ''\n fontsize = _font_size(len(word))\n ax.text(x, y, word, ha='center', va='center', color=color, size\n =fontsize)\n idx = [(i + 0.5) for i in range(attention_weights_sent.shape[0])]\n plt.yticks(idx, attention_weights_sent)\n for l, i in zip(ax.yaxis.get_ticklabels(), pc_sent.get_facecolors()):\n l.set_color(i)\n l.set_backgroundcolor(i)\n l.set_fontsize(15)\n plt.colorbar(pc)\n plt.savefig(fname)\n plot_attention('attention_real_han.png', attention_weights_word, np.\n array([[x] for x in attention_weights_sent]), sentence)\n\n\n<mask token>\n\n\ndef get_confusion(data, embds):\n tf.reset_default_graph()\n now = 'banl2norm_100d_163b_[10,10,10,10]cx_0.0001_0.5d_accstop'\n tf.reset_default_graph()\n with tf.Session() as sess:\n model = BucketizedAttention(num_classes=2, vocab_size=embds.shape[0\n ], embedding_size=embds.shape[1])\n root_logdir = 'logs'\n logdir = '{}/run-{}-{}/'.format(root_logdir, now, 0)\n checkpoint_dir = '{}checkpoints'.format(logdir)\n saver = tf.train.Saver()\n sess.run(tf.global_variables_initializer())\n sess.run(model.embedding_init, feed_dict={model.embedding_placeholder:\n embds})\n saver.restore(sess, checkpoint_dir)\n predictions = model.predict()\n x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_test()\n feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths:\n sent_lengths_val, model.seq_lengths: seq_lengths_val, model.\n dropout_keep_prob: 1, model.max_seq_length: data.\n test_max_seq_length, model.max_sent_length: data.test_max_sent_length}\n pred = sess.run(predictions, feed_dict=feed_dict)\n\n def fn(x):\n if x == 0:\n return 3\n elif x == 1:\n return 4\n elif x == 2:\n return 2\n elif x == 3:\n return 1\n elif x == 4:\n return 5\n elif x == 5:\n return 0\n else:\n return -1\n labels = list(map(fn, pred['labels']))\n predicts = list(map(fn, pred['predictions']))\n cnf_matrix = metrics.confusion_matrix(labels, predicts)\n plt.figure()\n classes = ['True', 'False']\n plot_confusion_matrix(cnf_matrix, classes=classes, title=\n 'Confusion matrix, without normalization')\n plt.figure()\n plot_confusion_matrix(cnf_matrix, classes=classes, normalize=True,\n title='Normalized confusion matrix')\n plt.show()\n\n\ndef t_test(data, embds):\n tf.reset_default_graph()\n acc_ban = []\n f1_ban = []\n now = 'banl2norm_100d_163b_[10,10,10,10]cx_0.0001_0.5d_accstop'\n for it in range(30):\n tf.reset_default_graph()\n with tf.Session() as sess:\n lstm = BucketizedAttention(num_classes=2, vocab_size=embds.\n shape[0], embedding_size=embds.shape[1])\n root_logdir = 'logs'\n logdir = '{}/run-{}-{}/'.format(root_logdir, now, it)\n (acc, macro_f1, f1_0, f1_1, macro_precision, precision_0,\n precision_1, macro_recall, recall_0, recall_1) = evaluate(sess,\n data, embds, lstm, logdir)\n print(acc)\n acc_ban.append(acc)\n f1_ban.append(macro_f1)\n tf.reset_default_graph()\n acc_cnn = [0.6313328137178488, 0.6157443491816056, 0.6110678098207326, \n 0.6141855027279813, 0.6165237724084178, 0.627435697583788, \n 0.6297739672642245, 0.6102883865939205, 0.6219797349961029, \n 0.6157443491816056, 0.6188620420888542, 0.6087295401402962, \n 0.6071706936866719, 0.6118472330475448, 0.6336710833982853, \n 0.6243180046765393, 0.6056118472330475, 0.6180826188620421, \n 0.6243180046765393, 0.6180826188620421, 0.6250974279033515, \n 0.6180826188620421, 0.6219797349961029, 0.6056118472330475, \n 0.6188620420888542, 0.6235385814497272, 0.6063912704598597, \n 0.5962587685113017, 0.6313328137178488, 0.6149649259547935]\n f1_cnn = [0.625208977558574, 0.6067531970160148, 0.6109316669026621, \n 0.6020553751990241, 0.6090837028412892, 0.6094950282209589, \n 0.6172590617767771, 0.607132008544496, 0.6080345191414308, \n 0.5998115849326153, 0.6085742361143607, 0.6078430656223209, \n 0.5935340795944845, 0.5862705332027911, 0.6173464207571212, \n 0.6042373835890662, 0.6010630976083375, 0.5991259035560702, \n 0.5946686067851712, 0.5925791031776069, 0.6052042516849045, \n 0.6115004325794092, 0.6152243182460431, 0.6045333820662768, \n 0.6009255107006212, 0.6008323601423038, 0.5949095710792511, \n 0.59088816113464, 0.6062203096074071, 0.6064241216914394]\n print(stats.ttest_ind(acc_ban, acc_cnn, equal_var=False))\n print(stats.ttest_ind(f1_ban, f1_cnn, equal_var=False))\n",
"step-2": "<mask token>\n\n\ndef evaluate(sess, data, embds, model, logdir):\n checkpoint_dir = '{}checkpoints'.format(logdir)\n saver = tf.train.Saver()\n sess.run(tf.global_variables_initializer())\n sess.run(model.embedding_init, feed_dict={model.embedding_placeholder:\n embds})\n saver.restore(sess, checkpoint_dir)\n predictions = model.predict()\n x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_test()\n feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths:\n sent_lengths_val, model.seq_lengths: seq_lengths_val, model.\n dropout_keep_prob: 1, model.max_seq_length: data.\n test_max_seq_length, model.max_sent_length: data.test_max_sent_length}\n pred = sess.run(predictions, feed_dict=feed_dict)\n acc = metrics.accuracy_score(pred['labels'], pred['predictions'])\n macro_f1 = metrics.f1_score(pred['labels'], pred['predictions'],\n average='macro')\n f1_0 = metrics.f1_score(pred['labels'], pred['predictions'], pos_label=0)\n f1_1 = metrics.f1_score(pred['labels'], pred['predictions'], pos_label=1)\n macro_precision = metrics.precision_score(pred['labels'], pred[\n 'predictions'], average='macro')\n precision_0 = metrics.precision_score(pred['labels'], pred[\n 'predictions'], pos_label=0)\n precision_1 = metrics.precision_score(pred['labels'], pred[\n 'predictions'], pos_label=1)\n macro_recall = metrics.recall_score(pred['labels'], pred['predictions'],\n average='macro')\n recall_0 = metrics.recall_score(pred['labels'], pred['predictions'],\n pos_label=0)\n recall_1 = metrics.recall_score(pred['labels'], pred['predictions'],\n pos_label=1)\n return (acc, macro_f1, f1_0, f1_1, macro_precision, precision_0,\n precision_1, macro_recall, recall_0, recall_1)\n\n\ndef run_std(data, embds):\n selection = get_attention_weights(data, embds)\n visualize_attention(selection)\n tf.reset_default_graph()\n results = []\n now = 'han_100d_163b_50cx_0.0001_0.5d'\n result = []\n for it in range(5):\n tf.reset_default_graph()\n with tf.Session() as sess:\n lstm = HierarchicalAttention(num_classes=2, vocab_size=embds.\n shape[0], embedding_size=embds.shape[1])\n root_logdir = 'logs'\n logdir = '{}/run-{}-{}/'.format(root_logdir, now, it)\n (acc, macro_f1, f1_0, f1_1, macro_precision, precision_0,\n precision_1, macro_recall, recall_0, recall_1) = evaluate(sess,\n data, embds, lstm, logdir)\n print(logdir)\n print(acc, ' ', macro_f1, ' ', f1_0, ' ', f1_1, ' ',\n macro_precision, ' ', precision_0, ' ', precision_1, ' ',\n macro_recall, ' ', recall_0, ' ', recall_1)\n result.append([acc, macro_f1, f1_0, f1_1, macro_precision,\n precision_0, precision_1, macro_recall, recall_0, recall_1])\n result_averages = np.mean(result, axis=0)\n print(result_averages)\n result_stds = np.std(result, axis=0)\n print(result_stds)\n result = list(zip(result_averages, result_stds))\n result.insert(0, now)\n results.append(result)\n print(result)\n print('averages-------')\n print(results)\n print('------------')\n\n\ndef get_attention_weights(data, embds):\n tf.reset_default_graph()\n it = 0\n now = 'han_100d_163b_50cx_0.0001_0.5d'\n with tf.Session() as sess:\n model = HierarchicalAttention(num_classes=2, vocab_size=embds.shape\n [0], embedding_size=embds.shape[1])\n root_logdir = 'logs'\n logdir = '{}/run-{}-{}/'.format(root_logdir, now, it)\n checkpoint_dir = '{}checkpoints'.format(logdir)\n saver = tf.train.Saver()\n sess.run(tf.global_variables_initializer())\n sess.run(model.embedding_init, feed_dict={model.embedding_placeholder:\n embds})\n saver.restore(sess, checkpoint_dir)\n predictions = model.predict()\n x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_val()\n feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths:\n sent_lengths_val, model.seq_lengths: seq_lengths_val, model.\n dropout_keep_prob: 1, model.max_seq_length: data.val_max_seq_length,\n model.max_sent_length: data.val_max_sent_length}\n pred, a_word, a_sent = sess.run([predictions, model.alphas_word, model.\n alphas_sent], feed_dict=feed_dict)\n a_word = np.reshape(a_word, [-1, data.val_max_seq_length, data.\n val_max_sent_length, 1])\n zipped = list(zip(x_val, pred['labels'], pred['predictions'], pred[\n 'probabilities'], a_word, a_sent))\n selection = [list(x) for x in zipped][133]\n zipped_correct = [list(x) for x in zipped if x[1] == x[2] and x[1] == 1]\n\n def get_predicted_prob(x):\n return x[3][x[2]]\n sorted_correct = sorted(zipped_correct, key=get_predicted_prob, reverse\n =True)\n print(sorted_correct[0:2])\n selection_zipped_tuple = list(zip(selection[0], selection[4], selection[5])\n )\n selection_zipped = [list(x) for x in selection_zipped_tuple]\n for s in selection_zipped:\n s[0] = dp.translate_to_voc(s[0])\n return selection_zipped\n\n\ndef visualize_attention(data):\n data.reverse()\n attention_weights_word = np.array([np.squeeze(x[1]) for x in data])\n attention_weights_sent = np.array([np.squeeze(x[2]) for x in data])\n sentence = np.array([x[0] for x in data])\n max_idx = 0\n empty_rows = 0\n for i, s in enumerate(sentence):\n idx = list(s).index('PAD')\n attention_weights_word[i, idx:] = 0\n if idx > max_idx:\n max_idx = idx\n if idx == 0:\n empty_rows += 1\n sentence = sentence[empty_rows:, 0:max_idx]\n attention_weights_word = attention_weights_word[empty_rows:, 0:max_idx]\n attention_weights_sent = attention_weights_sent[empty_rows:]\n max_weight1 = attention_weights_word.max()\n attention_weights_word = attention_weights_word / max_weight1\n max_weight2 = attention_weights_sent.max()\n attention_weights_sent = attention_weights_sent / max_weight2\n print(np.shape(sentence))\n MAX_FONTSIZE = 15\n MIN_FONTSIZE = 10\n\n def _font_size(word_len):\n return max(int(round(MAX_FONTSIZE - 0.5 * word_len)), MIN_FONTSIZE)\n\n def plot_attention(fname, attention_weights, attention_weights_sent,\n sentence):\n length = np.vectorize(lambda s: len(s))\n max_word_len = length(sentence).max()\n font_size_max_len = _font_size(max_word_len)\n plt.figure(figsize=(attention_weights.shape[-1] * (max_word_len *\n font_size_max_len / 100 + 0.5), attention_weights.shape[0]))\n plt.title('Attention')\n plt.xlabel('words')\n plt.ylabel('batch')\n pc_sent = plt.pcolor(attention_weights_sent, edgecolors='k',\n linewidths=4, cmap='Reds', vmin=0.0, vmax=1.0)\n pc_sent.update_scalarmappable()\n pc = plt.pcolor(attention_weights, edgecolors='k', linewidths=4,\n cmap='Blues', vmin=0.0, vmax=1.0)\n pc.update_scalarmappable()\n ax = pc.axes\n for p, color, value in zip(pc.get_paths(), pc.get_facecolors(), pc.\n get_array()):\n x, y = p.vertices[:-2, :].mean(0)\n if np.all(color[:3] > 0.5):\n color = 0.0, 0.0, 0.0\n else:\n color = 1.0, 1.0, 1.0\n j, i = int(floor(x)), int(floor(y))\n if sentence[i, j] != 'PAD':\n word = sentence[i, j]\n else:\n word = ''\n fontsize = _font_size(len(word))\n ax.text(x, y, word, ha='center', va='center', color=color, size\n =fontsize)\n idx = [(i + 0.5) for i in range(attention_weights_sent.shape[0])]\n plt.yticks(idx, attention_weights_sent)\n for l, i in zip(ax.yaxis.get_ticklabels(), pc_sent.get_facecolors()):\n l.set_color(i)\n l.set_backgroundcolor(i)\n l.set_fontsize(15)\n plt.colorbar(pc)\n plt.savefig(fname)\n plot_attention('attention_real_han.png', attention_weights_word, np.\n array([[x] for x in attention_weights_sent]), sentence)\n\n\n<mask token>\n\n\ndef get_confusion(data, embds):\n tf.reset_default_graph()\n now = 'banl2norm_100d_163b_[10,10,10,10]cx_0.0001_0.5d_accstop'\n tf.reset_default_graph()\n with tf.Session() as sess:\n model = BucketizedAttention(num_classes=2, vocab_size=embds.shape[0\n ], embedding_size=embds.shape[1])\n root_logdir = 'logs'\n logdir = '{}/run-{}-{}/'.format(root_logdir, now, 0)\n checkpoint_dir = '{}checkpoints'.format(logdir)\n saver = tf.train.Saver()\n sess.run(tf.global_variables_initializer())\n sess.run(model.embedding_init, feed_dict={model.embedding_placeholder:\n embds})\n saver.restore(sess, checkpoint_dir)\n predictions = model.predict()\n x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_test()\n feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths:\n sent_lengths_val, model.seq_lengths: seq_lengths_val, model.\n dropout_keep_prob: 1, model.max_seq_length: data.\n test_max_seq_length, model.max_sent_length: data.test_max_sent_length}\n pred = sess.run(predictions, feed_dict=feed_dict)\n\n def fn(x):\n if x == 0:\n return 3\n elif x == 1:\n return 4\n elif x == 2:\n return 2\n elif x == 3:\n return 1\n elif x == 4:\n return 5\n elif x == 5:\n return 0\n else:\n return -1\n labels = list(map(fn, pred['labels']))\n predicts = list(map(fn, pred['predictions']))\n cnf_matrix = metrics.confusion_matrix(labels, predicts)\n plt.figure()\n classes = ['True', 'False']\n plot_confusion_matrix(cnf_matrix, classes=classes, title=\n 'Confusion matrix, without normalization')\n plt.figure()\n plot_confusion_matrix(cnf_matrix, classes=classes, normalize=True,\n title='Normalized confusion matrix')\n plt.show()\n\n\ndef t_test(data, embds):\n tf.reset_default_graph()\n acc_ban = []\n f1_ban = []\n now = 'banl2norm_100d_163b_[10,10,10,10]cx_0.0001_0.5d_accstop'\n for it in range(30):\n tf.reset_default_graph()\n with tf.Session() as sess:\n lstm = BucketizedAttention(num_classes=2, vocab_size=embds.\n shape[0], embedding_size=embds.shape[1])\n root_logdir = 'logs'\n logdir = '{}/run-{}-{}/'.format(root_logdir, now, it)\n (acc, macro_f1, f1_0, f1_1, macro_precision, precision_0,\n precision_1, macro_recall, recall_0, recall_1) = evaluate(sess,\n data, embds, lstm, logdir)\n print(acc)\n acc_ban.append(acc)\n f1_ban.append(macro_f1)\n tf.reset_default_graph()\n acc_cnn = [0.6313328137178488, 0.6157443491816056, 0.6110678098207326, \n 0.6141855027279813, 0.6165237724084178, 0.627435697583788, \n 0.6297739672642245, 0.6102883865939205, 0.6219797349961029, \n 0.6157443491816056, 0.6188620420888542, 0.6087295401402962, \n 0.6071706936866719, 0.6118472330475448, 0.6336710833982853, \n 0.6243180046765393, 0.6056118472330475, 0.6180826188620421, \n 0.6243180046765393, 0.6180826188620421, 0.6250974279033515, \n 0.6180826188620421, 0.6219797349961029, 0.6056118472330475, \n 0.6188620420888542, 0.6235385814497272, 0.6063912704598597, \n 0.5962587685113017, 0.6313328137178488, 0.6149649259547935]\n f1_cnn = [0.625208977558574, 0.6067531970160148, 0.6109316669026621, \n 0.6020553751990241, 0.6090837028412892, 0.6094950282209589, \n 0.6172590617767771, 0.607132008544496, 0.6080345191414308, \n 0.5998115849326153, 0.6085742361143607, 0.6078430656223209, \n 0.5935340795944845, 0.5862705332027911, 0.6173464207571212, \n 0.6042373835890662, 0.6010630976083375, 0.5991259035560702, \n 0.5946686067851712, 0.5925791031776069, 0.6052042516849045, \n 0.6115004325794092, 0.6152243182460431, 0.6045333820662768, \n 0.6009255107006212, 0.6008323601423038, 0.5949095710792511, \n 0.59088816113464, 0.6062203096074071, 0.6064241216914394]\n print(stats.ttest_ind(acc_ban, acc_cnn, equal_var=False))\n print(stats.ttest_ind(f1_ban, f1_cnn, equal_var=False))\n",
"step-3": "<mask token>\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\n\n\ndef evaluate(sess, data, embds, model, logdir):\n checkpoint_dir = '{}checkpoints'.format(logdir)\n saver = tf.train.Saver()\n sess.run(tf.global_variables_initializer())\n sess.run(model.embedding_init, feed_dict={model.embedding_placeholder:\n embds})\n saver.restore(sess, checkpoint_dir)\n predictions = model.predict()\n x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_test()\n feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths:\n sent_lengths_val, model.seq_lengths: seq_lengths_val, model.\n dropout_keep_prob: 1, model.max_seq_length: data.\n test_max_seq_length, model.max_sent_length: data.test_max_sent_length}\n pred = sess.run(predictions, feed_dict=feed_dict)\n acc = metrics.accuracy_score(pred['labels'], pred['predictions'])\n macro_f1 = metrics.f1_score(pred['labels'], pred['predictions'],\n average='macro')\n f1_0 = metrics.f1_score(pred['labels'], pred['predictions'], pos_label=0)\n f1_1 = metrics.f1_score(pred['labels'], pred['predictions'], pos_label=1)\n macro_precision = metrics.precision_score(pred['labels'], pred[\n 'predictions'], average='macro')\n precision_0 = metrics.precision_score(pred['labels'], pred[\n 'predictions'], pos_label=0)\n precision_1 = metrics.precision_score(pred['labels'], pred[\n 'predictions'], pos_label=1)\n macro_recall = metrics.recall_score(pred['labels'], pred['predictions'],\n average='macro')\n recall_0 = metrics.recall_score(pred['labels'], pred['predictions'],\n pos_label=0)\n recall_1 = metrics.recall_score(pred['labels'], pred['predictions'],\n pos_label=1)\n return (acc, macro_f1, f1_0, f1_1, macro_precision, precision_0,\n precision_1, macro_recall, recall_0, recall_1)\n\n\ndef run_std(data, embds):\n selection = get_attention_weights(data, embds)\n visualize_attention(selection)\n tf.reset_default_graph()\n results = []\n now = 'han_100d_163b_50cx_0.0001_0.5d'\n result = []\n for it in range(5):\n tf.reset_default_graph()\n with tf.Session() as sess:\n lstm = HierarchicalAttention(num_classes=2, vocab_size=embds.\n shape[0], embedding_size=embds.shape[1])\n root_logdir = 'logs'\n logdir = '{}/run-{}-{}/'.format(root_logdir, now, it)\n (acc, macro_f1, f1_0, f1_1, macro_precision, precision_0,\n precision_1, macro_recall, recall_0, recall_1) = evaluate(sess,\n data, embds, lstm, logdir)\n print(logdir)\n print(acc, ' ', macro_f1, ' ', f1_0, ' ', f1_1, ' ',\n macro_precision, ' ', precision_0, ' ', precision_1, ' ',\n macro_recall, ' ', recall_0, ' ', recall_1)\n result.append([acc, macro_f1, f1_0, f1_1, macro_precision,\n precision_0, precision_1, macro_recall, recall_0, recall_1])\n result_averages = np.mean(result, axis=0)\n print(result_averages)\n result_stds = np.std(result, axis=0)\n print(result_stds)\n result = list(zip(result_averages, result_stds))\n result.insert(0, now)\n results.append(result)\n print(result)\n print('averages-------')\n print(results)\n print('------------')\n\n\ndef get_attention_weights(data, embds):\n tf.reset_default_graph()\n it = 0\n now = 'han_100d_163b_50cx_0.0001_0.5d'\n with tf.Session() as sess:\n model = HierarchicalAttention(num_classes=2, vocab_size=embds.shape\n [0], embedding_size=embds.shape[1])\n root_logdir = 'logs'\n logdir = '{}/run-{}-{}/'.format(root_logdir, now, it)\n checkpoint_dir = '{}checkpoints'.format(logdir)\n saver = tf.train.Saver()\n sess.run(tf.global_variables_initializer())\n sess.run(model.embedding_init, feed_dict={model.embedding_placeholder:\n embds})\n saver.restore(sess, checkpoint_dir)\n predictions = model.predict()\n x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_val()\n feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths:\n sent_lengths_val, model.seq_lengths: seq_lengths_val, model.\n dropout_keep_prob: 1, model.max_seq_length: data.val_max_seq_length,\n model.max_sent_length: data.val_max_sent_length}\n pred, a_word, a_sent = sess.run([predictions, model.alphas_word, model.\n alphas_sent], feed_dict=feed_dict)\n a_word = np.reshape(a_word, [-1, data.val_max_seq_length, data.\n val_max_sent_length, 1])\n zipped = list(zip(x_val, pred['labels'], pred['predictions'], pred[\n 'probabilities'], a_word, a_sent))\n selection = [list(x) for x in zipped][133]\n zipped_correct = [list(x) for x in zipped if x[1] == x[2] and x[1] == 1]\n\n def get_predicted_prob(x):\n return x[3][x[2]]\n sorted_correct = sorted(zipped_correct, key=get_predicted_prob, reverse\n =True)\n print(sorted_correct[0:2])\n selection_zipped_tuple = list(zip(selection[0], selection[4], selection[5])\n )\n selection_zipped = [list(x) for x in selection_zipped_tuple]\n for s in selection_zipped:\n s[0] = dp.translate_to_voc(s[0])\n return selection_zipped\n\n\ndef visualize_attention(data):\n data.reverse()\n attention_weights_word = np.array([np.squeeze(x[1]) for x in data])\n attention_weights_sent = np.array([np.squeeze(x[2]) for x in data])\n sentence = np.array([x[0] for x in data])\n max_idx = 0\n empty_rows = 0\n for i, s in enumerate(sentence):\n idx = list(s).index('PAD')\n attention_weights_word[i, idx:] = 0\n if idx > max_idx:\n max_idx = idx\n if idx == 0:\n empty_rows += 1\n sentence = sentence[empty_rows:, 0:max_idx]\n attention_weights_word = attention_weights_word[empty_rows:, 0:max_idx]\n attention_weights_sent = attention_weights_sent[empty_rows:]\n max_weight1 = attention_weights_word.max()\n attention_weights_word = attention_weights_word / max_weight1\n max_weight2 = attention_weights_sent.max()\n attention_weights_sent = attention_weights_sent / max_weight2\n print(np.shape(sentence))\n MAX_FONTSIZE = 15\n MIN_FONTSIZE = 10\n\n def _font_size(word_len):\n return max(int(round(MAX_FONTSIZE - 0.5 * word_len)), MIN_FONTSIZE)\n\n def plot_attention(fname, attention_weights, attention_weights_sent,\n sentence):\n length = np.vectorize(lambda s: len(s))\n max_word_len = length(sentence).max()\n font_size_max_len = _font_size(max_word_len)\n plt.figure(figsize=(attention_weights.shape[-1] * (max_word_len *\n font_size_max_len / 100 + 0.5), attention_weights.shape[0]))\n plt.title('Attention')\n plt.xlabel('words')\n plt.ylabel('batch')\n pc_sent = plt.pcolor(attention_weights_sent, edgecolors='k',\n linewidths=4, cmap='Reds', vmin=0.0, vmax=1.0)\n pc_sent.update_scalarmappable()\n pc = plt.pcolor(attention_weights, edgecolors='k', linewidths=4,\n cmap='Blues', vmin=0.0, vmax=1.0)\n pc.update_scalarmappable()\n ax = pc.axes\n for p, color, value in zip(pc.get_paths(), pc.get_facecolors(), pc.\n get_array()):\n x, y = p.vertices[:-2, :].mean(0)\n if np.all(color[:3] > 0.5):\n color = 0.0, 0.0, 0.0\n else:\n color = 1.0, 1.0, 1.0\n j, i = int(floor(x)), int(floor(y))\n if sentence[i, j] != 'PAD':\n word = sentence[i, j]\n else:\n word = ''\n fontsize = _font_size(len(word))\n ax.text(x, y, word, ha='center', va='center', color=color, size\n =fontsize)\n idx = [(i + 0.5) for i in range(attention_weights_sent.shape[0])]\n plt.yticks(idx, attention_weights_sent)\n for l, i in zip(ax.yaxis.get_ticklabels(), pc_sent.get_facecolors()):\n l.set_color(i)\n l.set_backgroundcolor(i)\n l.set_fontsize(15)\n plt.colorbar(pc)\n plt.savefig(fname)\n plot_attention('attention_real_han.png', attention_weights_word, np.\n array([[x] for x in attention_weights_sent]), sentence)\n\n\ndef plot_confusion_matrix(cm, classes, normalize=False, title=\n 'Confusion matrix', cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print('Normalized confusion matrix')\n else:\n print('Confusion matrix, without normalization')\n print(cm)\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.0\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt), horizontalalignment='center',\n color='white' if cm[i, j] > thresh else 'black')\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n\n\ndef get_confusion(data, embds):\n tf.reset_default_graph()\n now = 'banl2norm_100d_163b_[10,10,10,10]cx_0.0001_0.5d_accstop'\n tf.reset_default_graph()\n with tf.Session() as sess:\n model = BucketizedAttention(num_classes=2, vocab_size=embds.shape[0\n ], embedding_size=embds.shape[1])\n root_logdir = 'logs'\n logdir = '{}/run-{}-{}/'.format(root_logdir, now, 0)\n checkpoint_dir = '{}checkpoints'.format(logdir)\n saver = tf.train.Saver()\n sess.run(tf.global_variables_initializer())\n sess.run(model.embedding_init, feed_dict={model.embedding_placeholder:\n embds})\n saver.restore(sess, checkpoint_dir)\n predictions = model.predict()\n x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_test()\n feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths:\n sent_lengths_val, model.seq_lengths: seq_lengths_val, model.\n dropout_keep_prob: 1, model.max_seq_length: data.\n test_max_seq_length, model.max_sent_length: data.test_max_sent_length}\n pred = sess.run(predictions, feed_dict=feed_dict)\n\n def fn(x):\n if x == 0:\n return 3\n elif x == 1:\n return 4\n elif x == 2:\n return 2\n elif x == 3:\n return 1\n elif x == 4:\n return 5\n elif x == 5:\n return 0\n else:\n return -1\n labels = list(map(fn, pred['labels']))\n predicts = list(map(fn, pred['predictions']))\n cnf_matrix = metrics.confusion_matrix(labels, predicts)\n plt.figure()\n classes = ['True', 'False']\n plot_confusion_matrix(cnf_matrix, classes=classes, title=\n 'Confusion matrix, without normalization')\n plt.figure()\n plot_confusion_matrix(cnf_matrix, classes=classes, normalize=True,\n title='Normalized confusion matrix')\n plt.show()\n\n\ndef t_test(data, embds):\n tf.reset_default_graph()\n acc_ban = []\n f1_ban = []\n now = 'banl2norm_100d_163b_[10,10,10,10]cx_0.0001_0.5d_accstop'\n for it in range(30):\n tf.reset_default_graph()\n with tf.Session() as sess:\n lstm = BucketizedAttention(num_classes=2, vocab_size=embds.\n shape[0], embedding_size=embds.shape[1])\n root_logdir = 'logs'\n logdir = '{}/run-{}-{}/'.format(root_logdir, now, it)\n (acc, macro_f1, f1_0, f1_1, macro_precision, precision_0,\n precision_1, macro_recall, recall_0, recall_1) = evaluate(sess,\n data, embds, lstm, logdir)\n print(acc)\n acc_ban.append(acc)\n f1_ban.append(macro_f1)\n tf.reset_default_graph()\n acc_cnn = [0.6313328137178488, 0.6157443491816056, 0.6110678098207326, \n 0.6141855027279813, 0.6165237724084178, 0.627435697583788, \n 0.6297739672642245, 0.6102883865939205, 0.6219797349961029, \n 0.6157443491816056, 0.6188620420888542, 0.6087295401402962, \n 0.6071706936866719, 0.6118472330475448, 0.6336710833982853, \n 0.6243180046765393, 0.6056118472330475, 0.6180826188620421, \n 0.6243180046765393, 0.6180826188620421, 0.6250974279033515, \n 0.6180826188620421, 0.6219797349961029, 0.6056118472330475, \n 0.6188620420888542, 0.6235385814497272, 0.6063912704598597, \n 0.5962587685113017, 0.6313328137178488, 0.6149649259547935]\n f1_cnn = [0.625208977558574, 0.6067531970160148, 0.6109316669026621, \n 0.6020553751990241, 0.6090837028412892, 0.6094950282209589, \n 0.6172590617767771, 0.607132008544496, 0.6080345191414308, \n 0.5998115849326153, 0.6085742361143607, 0.6078430656223209, \n 0.5935340795944845, 0.5862705332027911, 0.6173464207571212, \n 0.6042373835890662, 0.6010630976083375, 0.5991259035560702, \n 0.5946686067851712, 0.5925791031776069, 0.6052042516849045, \n 0.6115004325794092, 0.6152243182460431, 0.6045333820662768, \n 0.6009255107006212, 0.6008323601423038, 0.5949095710792511, \n 0.59088816113464, 0.6062203096074071, 0.6064241216914394]\n print(stats.ttest_ind(acc_ban, acc_cnn, equal_var=False))\n print(stats.ttest_ind(f1_ban, f1_cnn, equal_var=False))\n",
"step-4": "import tensorflow as tf\nimport numpy as np\nfrom datetime import datetime\nimport os\nfrom CNN import CNN\nfrom LSTM import LSTM\nfrom BiLSTM import BiLSTM\nfrom SLAN import Attention\nfrom HAN2 import HierarchicalAttention\nimport sklearn.metrics as metrics\nimport DataProcessor as dp\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport itertools\nfrom scipy import stats\nfrom math import floor\nfrom BAN import BucketizedAttention\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\n\n\ndef evaluate(sess, data, embds, model, logdir):\n checkpoint_dir = '{}checkpoints'.format(logdir)\n saver = tf.train.Saver()\n sess.run(tf.global_variables_initializer())\n sess.run(model.embedding_init, feed_dict={model.embedding_placeholder:\n embds})\n saver.restore(sess, checkpoint_dir)\n predictions = model.predict()\n x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_test()\n feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths:\n sent_lengths_val, model.seq_lengths: seq_lengths_val, model.\n dropout_keep_prob: 1, model.max_seq_length: data.\n test_max_seq_length, model.max_sent_length: data.test_max_sent_length}\n pred = sess.run(predictions, feed_dict=feed_dict)\n acc = metrics.accuracy_score(pred['labels'], pred['predictions'])\n macro_f1 = metrics.f1_score(pred['labels'], pred['predictions'],\n average='macro')\n f1_0 = metrics.f1_score(pred['labels'], pred['predictions'], pos_label=0)\n f1_1 = metrics.f1_score(pred['labels'], pred['predictions'], pos_label=1)\n macro_precision = metrics.precision_score(pred['labels'], pred[\n 'predictions'], average='macro')\n precision_0 = metrics.precision_score(pred['labels'], pred[\n 'predictions'], pos_label=0)\n precision_1 = metrics.precision_score(pred['labels'], pred[\n 'predictions'], pos_label=1)\n macro_recall = metrics.recall_score(pred['labels'], pred['predictions'],\n average='macro')\n recall_0 = metrics.recall_score(pred['labels'], pred['predictions'],\n pos_label=0)\n recall_1 = metrics.recall_score(pred['labels'], pred['predictions'],\n pos_label=1)\n return (acc, macro_f1, f1_0, f1_1, macro_precision, precision_0,\n precision_1, macro_recall, recall_0, recall_1)\n\n\ndef run_std(data, embds):\n selection = get_attention_weights(data, embds)\n visualize_attention(selection)\n tf.reset_default_graph()\n results = []\n now = 'han_100d_163b_50cx_0.0001_0.5d'\n result = []\n for it in range(5):\n tf.reset_default_graph()\n with tf.Session() as sess:\n lstm = HierarchicalAttention(num_classes=2, vocab_size=embds.\n shape[0], embedding_size=embds.shape[1])\n root_logdir = 'logs'\n logdir = '{}/run-{}-{}/'.format(root_logdir, now, it)\n (acc, macro_f1, f1_0, f1_1, macro_precision, precision_0,\n precision_1, macro_recall, recall_0, recall_1) = evaluate(sess,\n data, embds, lstm, logdir)\n print(logdir)\n print(acc, ' ', macro_f1, ' ', f1_0, ' ', f1_1, ' ',\n macro_precision, ' ', precision_0, ' ', precision_1, ' ',\n macro_recall, ' ', recall_0, ' ', recall_1)\n result.append([acc, macro_f1, f1_0, f1_1, macro_precision,\n precision_0, precision_1, macro_recall, recall_0, recall_1])\n result_averages = np.mean(result, axis=0)\n print(result_averages)\n result_stds = np.std(result, axis=0)\n print(result_stds)\n result = list(zip(result_averages, result_stds))\n result.insert(0, now)\n results.append(result)\n print(result)\n print('averages-------')\n print(results)\n print('------------')\n\n\ndef get_attention_weights(data, embds):\n tf.reset_default_graph()\n it = 0\n now = 'han_100d_163b_50cx_0.0001_0.5d'\n with tf.Session() as sess:\n model = HierarchicalAttention(num_classes=2, vocab_size=embds.shape\n [0], embedding_size=embds.shape[1])\n root_logdir = 'logs'\n logdir = '{}/run-{}-{}/'.format(root_logdir, now, it)\n checkpoint_dir = '{}checkpoints'.format(logdir)\n saver = tf.train.Saver()\n sess.run(tf.global_variables_initializer())\n sess.run(model.embedding_init, feed_dict={model.embedding_placeholder:\n embds})\n saver.restore(sess, checkpoint_dir)\n predictions = model.predict()\n x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_val()\n feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths:\n sent_lengths_val, model.seq_lengths: seq_lengths_val, model.\n dropout_keep_prob: 1, model.max_seq_length: data.val_max_seq_length,\n model.max_sent_length: data.val_max_sent_length}\n pred, a_word, a_sent = sess.run([predictions, model.alphas_word, model.\n alphas_sent], feed_dict=feed_dict)\n a_word = np.reshape(a_word, [-1, data.val_max_seq_length, data.\n val_max_sent_length, 1])\n zipped = list(zip(x_val, pred['labels'], pred['predictions'], pred[\n 'probabilities'], a_word, a_sent))\n selection = [list(x) for x in zipped][133]\n zipped_correct = [list(x) for x in zipped if x[1] == x[2] and x[1] == 1]\n\n def get_predicted_prob(x):\n return x[3][x[2]]\n sorted_correct = sorted(zipped_correct, key=get_predicted_prob, reverse\n =True)\n print(sorted_correct[0:2])\n selection_zipped_tuple = list(zip(selection[0], selection[4], selection[5])\n )\n selection_zipped = [list(x) for x in selection_zipped_tuple]\n for s in selection_zipped:\n s[0] = dp.translate_to_voc(s[0])\n return selection_zipped\n\n\ndef visualize_attention(data):\n data.reverse()\n attention_weights_word = np.array([np.squeeze(x[1]) for x in data])\n attention_weights_sent = np.array([np.squeeze(x[2]) for x in data])\n sentence = np.array([x[0] for x in data])\n max_idx = 0\n empty_rows = 0\n for i, s in enumerate(sentence):\n idx = list(s).index('PAD')\n attention_weights_word[i, idx:] = 0\n if idx > max_idx:\n max_idx = idx\n if idx == 0:\n empty_rows += 1\n sentence = sentence[empty_rows:, 0:max_idx]\n attention_weights_word = attention_weights_word[empty_rows:, 0:max_idx]\n attention_weights_sent = attention_weights_sent[empty_rows:]\n max_weight1 = attention_weights_word.max()\n attention_weights_word = attention_weights_word / max_weight1\n max_weight2 = attention_weights_sent.max()\n attention_weights_sent = attention_weights_sent / max_weight2\n print(np.shape(sentence))\n MAX_FONTSIZE = 15\n MIN_FONTSIZE = 10\n\n def _font_size(word_len):\n return max(int(round(MAX_FONTSIZE - 0.5 * word_len)), MIN_FONTSIZE)\n\n def plot_attention(fname, attention_weights, attention_weights_sent,\n sentence):\n length = np.vectorize(lambda s: len(s))\n max_word_len = length(sentence).max()\n font_size_max_len = _font_size(max_word_len)\n plt.figure(figsize=(attention_weights.shape[-1] * (max_word_len *\n font_size_max_len / 100 + 0.5), attention_weights.shape[0]))\n plt.title('Attention')\n plt.xlabel('words')\n plt.ylabel('batch')\n pc_sent = plt.pcolor(attention_weights_sent, edgecolors='k',\n linewidths=4, cmap='Reds', vmin=0.0, vmax=1.0)\n pc_sent.update_scalarmappable()\n pc = plt.pcolor(attention_weights, edgecolors='k', linewidths=4,\n cmap='Blues', vmin=0.0, vmax=1.0)\n pc.update_scalarmappable()\n ax = pc.axes\n for p, color, value in zip(pc.get_paths(), pc.get_facecolors(), pc.\n get_array()):\n x, y = p.vertices[:-2, :].mean(0)\n if np.all(color[:3] > 0.5):\n color = 0.0, 0.0, 0.0\n else:\n color = 1.0, 1.0, 1.0\n j, i = int(floor(x)), int(floor(y))\n if sentence[i, j] != 'PAD':\n word = sentence[i, j]\n else:\n word = ''\n fontsize = _font_size(len(word))\n ax.text(x, y, word, ha='center', va='center', color=color, size\n =fontsize)\n idx = [(i + 0.5) for i in range(attention_weights_sent.shape[0])]\n plt.yticks(idx, attention_weights_sent)\n for l, i in zip(ax.yaxis.get_ticklabels(), pc_sent.get_facecolors()):\n l.set_color(i)\n l.set_backgroundcolor(i)\n l.set_fontsize(15)\n plt.colorbar(pc)\n plt.savefig(fname)\n plot_attention('attention_real_han.png', attention_weights_word, np.\n array([[x] for x in attention_weights_sent]), sentence)\n\n\ndef plot_confusion_matrix(cm, classes, normalize=False, title=\n 'Confusion matrix', cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print('Normalized confusion matrix')\n else:\n print('Confusion matrix, without normalization')\n print(cm)\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.0\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt), horizontalalignment='center',\n color='white' if cm[i, j] > thresh else 'black')\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n\n\ndef get_confusion(data, embds):\n tf.reset_default_graph()\n now = 'banl2norm_100d_163b_[10,10,10,10]cx_0.0001_0.5d_accstop'\n tf.reset_default_graph()\n with tf.Session() as sess:\n model = BucketizedAttention(num_classes=2, vocab_size=embds.shape[0\n ], embedding_size=embds.shape[1])\n root_logdir = 'logs'\n logdir = '{}/run-{}-{}/'.format(root_logdir, now, 0)\n checkpoint_dir = '{}checkpoints'.format(logdir)\n saver = tf.train.Saver()\n sess.run(tf.global_variables_initializer())\n sess.run(model.embedding_init, feed_dict={model.embedding_placeholder:\n embds})\n saver.restore(sess, checkpoint_dir)\n predictions = model.predict()\n x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_test()\n feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths:\n sent_lengths_val, model.seq_lengths: seq_lengths_val, model.\n dropout_keep_prob: 1, model.max_seq_length: data.\n test_max_seq_length, model.max_sent_length: data.test_max_sent_length}\n pred = sess.run(predictions, feed_dict=feed_dict)\n\n def fn(x):\n if x == 0:\n return 3\n elif x == 1:\n return 4\n elif x == 2:\n return 2\n elif x == 3:\n return 1\n elif x == 4:\n return 5\n elif x == 5:\n return 0\n else:\n return -1\n labels = list(map(fn, pred['labels']))\n predicts = list(map(fn, pred['predictions']))\n cnf_matrix = metrics.confusion_matrix(labels, predicts)\n plt.figure()\n classes = ['True', 'False']\n plot_confusion_matrix(cnf_matrix, classes=classes, title=\n 'Confusion matrix, without normalization')\n plt.figure()\n plot_confusion_matrix(cnf_matrix, classes=classes, normalize=True,\n title='Normalized confusion matrix')\n plt.show()\n\n\ndef t_test(data, embds):\n tf.reset_default_graph()\n acc_ban = []\n f1_ban = []\n now = 'banl2norm_100d_163b_[10,10,10,10]cx_0.0001_0.5d_accstop'\n for it in range(30):\n tf.reset_default_graph()\n with tf.Session() as sess:\n lstm = BucketizedAttention(num_classes=2, vocab_size=embds.\n shape[0], embedding_size=embds.shape[1])\n root_logdir = 'logs'\n logdir = '{}/run-{}-{}/'.format(root_logdir, now, it)\n (acc, macro_f1, f1_0, f1_1, macro_precision, precision_0,\n precision_1, macro_recall, recall_0, recall_1) = evaluate(sess,\n data, embds, lstm, logdir)\n print(acc)\n acc_ban.append(acc)\n f1_ban.append(macro_f1)\n tf.reset_default_graph()\n acc_cnn = [0.6313328137178488, 0.6157443491816056, 0.6110678098207326, \n 0.6141855027279813, 0.6165237724084178, 0.627435697583788, \n 0.6297739672642245, 0.6102883865939205, 0.6219797349961029, \n 0.6157443491816056, 0.6188620420888542, 0.6087295401402962, \n 0.6071706936866719, 0.6118472330475448, 0.6336710833982853, \n 0.6243180046765393, 0.6056118472330475, 0.6180826188620421, \n 0.6243180046765393, 0.6180826188620421, 0.6250974279033515, \n 0.6180826188620421, 0.6219797349961029, 0.6056118472330475, \n 0.6188620420888542, 0.6235385814497272, 0.6063912704598597, \n 0.5962587685113017, 0.6313328137178488, 0.6149649259547935]\n f1_cnn = [0.625208977558574, 0.6067531970160148, 0.6109316669026621, \n 0.6020553751990241, 0.6090837028412892, 0.6094950282209589, \n 0.6172590617767771, 0.607132008544496, 0.6080345191414308, \n 0.5998115849326153, 0.6085742361143607, 0.6078430656223209, \n 0.5935340795944845, 0.5862705332027911, 0.6173464207571212, \n 0.6042373835890662, 0.6010630976083375, 0.5991259035560702, \n 0.5946686067851712, 0.5925791031776069, 0.6052042516849045, \n 0.6115004325794092, 0.6152243182460431, 0.6045333820662768, \n 0.6009255107006212, 0.6008323601423038, 0.5949095710792511, \n 0.59088816113464, 0.6062203096074071, 0.6064241216914394]\n print(stats.ttest_ind(acc_ban, acc_cnn, equal_var=False))\n print(stats.ttest_ind(f1_ban, f1_cnn, equal_var=False))\n",
"step-5": "import tensorflow as tf\nimport numpy as np\nfrom datetime import datetime\nimport os\nfrom CNN import CNN\nfrom LSTM import LSTM\nfrom BiLSTM import BiLSTM\nfrom SLAN import Attention\nfrom HAN2 import HierarchicalAttention\nimport sklearn.metrics as metrics\nimport DataProcessor as dp\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport itertools\nfrom scipy import stats\n\nfrom math import floor\nfrom BAN import BucketizedAttention\n\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\n\n\ndef evaluate(sess, data, embds, model, logdir):\n checkpoint_dir = \"{}checkpoints\".format(logdir)\n saver = tf.train.Saver()\n #saver = tf.train.import_meta_graph(\"{}.meta\".format(checkpoint_dir))\n # Training model\n #training_op, global_step = model.optimize()\n sess.run(tf.global_variables_initializer())\n sess.run(model.embedding_init, feed_dict={model.embedding_placeholder: embds})\n saver.restore(sess, checkpoint_dir)\n predictions = model.predict()\n\n #print(\"Evaluation:\")\n\n x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_test()\n feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths: sent_lengths_val,\n model.seq_lengths: seq_lengths_val, model.dropout_keep_prob: 1,\n model.max_seq_length: data.test_max_seq_length,\n model.max_sent_length: data.test_max_sent_length\n }\n pred = sess.run(predictions, feed_dict=feed_dict)\n\n acc = metrics.accuracy_score(pred['labels'], pred['predictions'])\n macro_f1 = metrics.f1_score(pred['labels'], pred['predictions'], average=\"macro\")\n f1_0 = metrics.f1_score(pred['labels'], pred['predictions'], pos_label=0)\n f1_1 = metrics.f1_score(pred['labels'], pred['predictions'], pos_label=1)\n macro_precision = metrics.precision_score(pred['labels'], pred['predictions'], average=\"macro\")\n precision_0 = metrics.precision_score(pred['labels'], pred['predictions'], pos_label=0)\n precision_1 = metrics.precision_score(pred['labels'], pred['predictions'], pos_label=1)\n macro_recall = metrics.recall_score(pred['labels'], pred['predictions'], average=\"macro\")\n recall_0 = metrics.recall_score(pred['labels'], pred['predictions'], pos_label=0)\n recall_1 = metrics.recall_score(pred['labels'], pred['predictions'], pos_label=1)\n\n\n return (acc, macro_f1, f1_0, f1_1, macro_precision, precision_0, precision_1, macro_recall, recall_0, recall_1)\n #return (acc, macro_f1, 1, 1, macro_precision, 1, 1, macro_recall, 1, 1)\n\n\ndef run_std(data, embds):\n selection = get_attention_weights(data, embds)\n visualize_attention(selection)\n tf.reset_default_graph()\n\n results = []\n now = \"han_100d_163b_50cx_0.0001_0.5d\"\n result = []\n for it in range(5):\n tf.reset_default_graph()\n with tf.Session() as sess:\n lstm = HierarchicalAttention(\n num_classes=2,\n vocab_size=embds.shape[0],\n embedding_size=embds.shape[1]\n )\n root_logdir = \"logs\"\n logdir = \"{}/run-{}-{}/\".format(root_logdir, now, it)\n acc, macro_f1, f1_0, f1_1, macro_precision, precision_0, precision_1, macro_recall, recall_0, recall_1 = evaluate(\n sess, data, embds, lstm, logdir)\n print(logdir)\n print(acc, \" \", macro_f1, \" \", f1_0, \" \", f1_1, \" \", macro_precision, \" \", precision_0, \" \",\n precision_1, \" \", macro_recall, \" \", recall_0, \" \", recall_1)\n result.append(\n [acc, macro_f1, f1_0, f1_1, macro_precision, precision_0, precision_1, macro_recall,\n recall_0, recall_1])\n result_averages = np.mean(result, axis=0)\n print(result_averages)\n result_stds = np.std(result, axis=0)\n print(result_stds)\n result = list(zip(result_averages, result_stds))\n result.insert(0, now)\n results.append(result)\n print(result)\n\n print(\"averages-------\")\n print(results)\n print(\"------------\")\n\n\ndef get_attention_weights(data, embds):\n tf.reset_default_graph()\n\n it = 0\n\n now = \"han_100d_163b_50cx_0.0001_0.5d\"\n with tf.Session() as sess:\n model = HierarchicalAttention(\n num_classes=2,\n vocab_size=embds.shape[0],\n embedding_size=embds.shape[1]\n )\n root_logdir = \"logs\"\n logdir = \"{}/run-{}-{}/\".format(root_logdir, now, it)\n\n checkpoint_dir = \"{}checkpoints\".format(logdir)\n saver = tf.train.Saver()\n # saver = tf.train.import_meta_graph(\"{}.meta\".format(checkpoint_dir))\n # Training model\n # training_op, global_step = model.optimize()\n sess.run(tf.global_variables_initializer())\n sess.run(model.embedding_init, feed_dict={model.embedding_placeholder: embds})\n saver.restore(sess, checkpoint_dir)\n predictions = model.predict()\n\n # print(\"Evaluation:\")\n x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_val()\n feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths: sent_lengths_val,\n model.seq_lengths: seq_lengths_val, model.dropout_keep_prob: 1,\n model.max_seq_length: data.val_max_seq_length,\n model.max_sent_length: data.val_max_sent_length\n }\n pred, a_word, a_sent = sess.run([predictions, model.alphas_word, model.alphas_sent], feed_dict=feed_dict)\n #pred, a1, A = sess.run([predictions, model.alphas1, model.alphas2, model.alphas3, model.alphas4],\n #feed_dict=feed_dict)\n a_word = np.reshape(a_word, [-1, data.val_max_seq_length, data.val_max_sent_length, 1])\n\n # filter on correct predictions\n zipped = list(zip(x_val, pred['labels'], pred['predictions'], pred['probabilities'], a_word, a_sent))\n # print(zipped[0:2])\n selection = [list(x) for x in zipped][133]\n zipped_correct = [list(x) for x in zipped if x[1]==x[2] and x[1] == 1]\n # print(zipped_correct[0:2])\n\n def get_predicted_prob(x):\n return (x[3])[(x[2])]\n\n sorted_correct = sorted(zipped_correct, key=get_predicted_prob, reverse=True)\n print(sorted_correct[0:2])\n\n #selection = sorted_correct[1]\n selection_zipped_tuple = list(zip(selection[0], selection[4], selection[5]))\n #selection_zipped_tuple = list(zip(selection[0], selection[4]))\n selection_zipped = [list(x) for x in selection_zipped_tuple]\n for s in selection_zipped:\n s[0] = dp.translate_to_voc(s[0])\n return selection_zipped\n\ndef visualize_attention(data):\n #data = np.array(data)\n data.reverse()\n attention_weights_word = np.array([np.squeeze(x[1]) for x in data])\n attention_weights_sent = np.array([np.squeeze(x[2]) for x in data])\n #max_weight = attention_weights.max()\n #attention_weights = attention_weights/max_weight # increase weights to make visualization clearer\n #max_weight1 = np.array(attention_weights1.max(axis=-1))\n #attention_weights1 = attention_weights1 / max_weight1[:, None] # increase weights to make visualization clearer\n sentence = np.array([x[0] for x in data])\n #labels = np.array([\"label-{}, pred-{}, prob-{}\".format(x[1], x[2], max(x[3])) for x in data])\n max_idx = 0\n empty_rows = 0\n for i, s in enumerate(sentence):\n idx = list(s).index(\"PAD\")\n attention_weights_word[i, idx:] = 0\n # attention_weights3[i, idx:] = 0\n # attention_weights4[i, idx:] = 0\n if idx > max_idx:\n max_idx = idx\n if idx == 0:\n empty_rows += 1\n sentence = sentence[empty_rows:, 0:max_idx]\n attention_weights_word = attention_weights_word[empty_rows:, 0:max_idx]\n attention_weights_sent = attention_weights_sent[empty_rows:]\n # attention_weights3 = attention_weights3[empty_rows:, 0:max_idx]\n # attention_weights4 = attention_weights4[empty_rows:, 0:max_idx]\n\n max_weight1 = attention_weights_word.max()\n attention_weights_word = attention_weights_word / max_weight1 # increase weights to make visualization clearer\n max_weight2 = attention_weights_sent.max()\n attention_weights_sent = attention_weights_sent / max_weight2 # increase weights to make visualization clearer\n # max_weight3 = attention_weights3.max()\n # attention_weights3 = attention_weights3 / max_weight3 # increase weights to make visualization clearer\n # max_weight4 = attention_weights4.max()\n # attention_weights4 = attention_weights4 / max_weight4 # increase weights to make visualization clearer\n\n #print(np.shape(attention_weights1))\n print(np.shape(sentence))\n #print(np.shape(labels))\n\n MAX_FONTSIZE = 15\n MIN_FONTSIZE = 10\n\n def _font_size(word_len):\n return max(int(round(MAX_FONTSIZE - 0.5 * word_len)), MIN_FONTSIZE)\n\n def plot_attention(fname, attention_weights, attention_weights_sent, sentence):\n\n length = np.vectorize(lambda s: len(s))\n max_word_len = length(sentence).max()\n font_size_max_len = _font_size(max_word_len)\n\n plt.figure(figsize=(\n attention_weights.shape[-1] * (max_word_len * font_size_max_len / 100 + 0.5), attention_weights.shape[0]))\n\n plt.title(\"Attention\")\n plt.xlabel(\"words\")\n plt.ylabel(\"batch\")\n\n pc_sent = plt.pcolor(attention_weights_sent, edgecolors='k', linewidths=4, cmap='Reds', vmin=0.0, vmax=1.0)\n pc_sent.update_scalarmappable()\n\n pc = plt.pcolor(attention_weights, edgecolors='k', linewidths=4, cmap='Blues', vmin=0.0, vmax=1.0)\n pc.update_scalarmappable()\n ax = pc.axes\n for p, color, value in zip(pc.get_paths(), pc.get_facecolors(), pc.get_array()):\n x, y = p.vertices[:-2, :].mean(0)\n if np.all(color[:3] > 0.5):\n color = (0.0, 0.0, 0.0)\n else:\n color = (1.0, 1.0, 1.0)\n j, i = int(floor(x)), int(floor(y))\n if sentence[i, j] != \"PAD\":\n word = sentence[i, j]\n else:\n word = \"\"\n fontsize = _font_size(len(word))\n ax.text(x, y, word, ha=\"center\", va=\"center\", color=color, size=fontsize)\n idx = [i + 0.5 for i in range(attention_weights_sent.shape[0])]\n plt.yticks(idx, attention_weights_sent)\n\n for l, i in zip(ax.yaxis.get_ticklabels(), pc_sent.get_facecolors()):\n l.set_color(i)\n l.set_backgroundcolor(i)\n l.set_fontsize(15)\n\n plt.colorbar(pc)\n plt.savefig(fname)\n\n plot_attention(\"attention_real_han.png\", attention_weights_word, np.array([[x] for x in attention_weights_sent]), sentence)\n # plot_attention(\"attention_real3.png\", attention_weights3, sentence)\n # plot_attention(\"attention_real4.png\", attention_weights4, sentence)\n\n\ndef plot_confusion_matrix(cm, classes,\n normalize=False,\n title='Confusion matrix',\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print('Confusion matrix, without normalization')\n\n print(cm)\n\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n\ndef get_confusion(data, embds):\n tf.reset_default_graph()\n\n now = \"banl2norm_100d_163b_[10,10,10,10]cx_0.0001_0.5d_accstop\"\n tf.reset_default_graph()\n with tf.Session() as sess:\n model = BucketizedAttention(\n num_classes=2,\n vocab_size=embds.shape[0],\n embedding_size=embds.shape[1]\n )\n root_logdir = \"logs\"\n logdir = \"{}/run-{}-{}/\".format(root_logdir, now, 0)\n\n checkpoint_dir = \"{}checkpoints\".format(logdir)\n saver = tf.train.Saver()\n\n sess.run(tf.global_variables_initializer())\n sess.run(model.embedding_init, feed_dict={model.embedding_placeholder: embds})\n saver.restore(sess, checkpoint_dir)\n predictions = model.predict()\n\n x_val, y_val, sent_lengths_val, seq_lengths_val = data.fetch_test()\n feed_dict = {model.x: x_val, model.y: y_val, model.sent_lengths: sent_lengths_val,\n model.seq_lengths: seq_lengths_val, model.dropout_keep_prob: 1,\n model.max_seq_length: data.test_max_seq_length,\n model.max_sent_length: data.test_max_sent_length\n }\n pred = sess.run(predictions, feed_dict=feed_dict)\n def fn(x):\n if x == 0:\n return 3\n elif x == 1:\n return 4\n elif x == 2:\n return 2\n elif x == 3:\n return 1\n elif x == 4:\n return 5\n elif x == 5:\n return 0\n else:\n return -1\n\n labels = list(map(fn, pred['labels']))\n predicts = list(map(fn, pred['predictions']))\n cnf_matrix = metrics.confusion_matrix(labels, predicts)\n # Plot non-normalized confusion matrix\n plt.figure()\n #classes = [\"True\", \"Mostly-true\", \"Half-true\", \"Barely-true\", \"False\", \"Pants-on-fire\"]\n classes = [\"True\", \"False\"]\n plot_confusion_matrix(cnf_matrix, classes=classes,\n title='Confusion matrix, without normalization')\n\n # Plot normalized confusion matrix\n plt.figure()\n plot_confusion_matrix(cnf_matrix, classes=classes, normalize=True,\n title='Normalized confusion matrix')\n\n plt.show()\n\n\ndef t_test(data, embds):\n tf.reset_default_graph()\n\n acc_ban = []\n f1_ban = []\n now = \"banl2norm_100d_163b_[10,10,10,10]cx_0.0001_0.5d_accstop\"\n for it in range(30):\n tf.reset_default_graph()\n with tf.Session() as sess:\n lstm = BucketizedAttention(\n num_classes=2,\n vocab_size=embds.shape[0],\n embedding_size=embds.shape[1]\n )\n root_logdir = \"logs\"\n logdir = \"{}/run-{}-{}/\".format(root_logdir, now, it)\n acc, macro_f1, f1_0, f1_1, macro_precision, precision_0, precision_1, macro_recall, recall_0, recall_1 = evaluate(\n sess, data, embds, lstm, logdir)\n print(acc)\n acc_ban.append(acc)\n f1_ban.append(macro_f1)\n\n tf.reset_default_graph()\n\n acc_cnn = [0.6313328137178488, 0.6157443491816056, 0.6110678098207326, 0.6141855027279813, 0.6165237724084178, 0.627435697583788, 0.6297739672642245, 0.6102883865939205, 0.6219797349961029, 0.6157443491816056, 0.6188620420888542, 0.6087295401402962, 0.6071706936866719, 0.6118472330475448, 0.6336710833982853, 0.6243180046765393, 0.6056118472330475, 0.6180826188620421, 0.6243180046765393, 0.6180826188620421, 0.6250974279033515, 0.6180826188620421, 0.6219797349961029, 0.6056118472330475, 0.6188620420888542, 0.6235385814497272, 0.6063912704598597, 0.5962587685113017, 0.6313328137178488, 0.6149649259547935]\n\n f1_cnn = [0.625208977558574, 0.6067531970160148, 0.6109316669026621, 0.6020553751990241, 0.6090837028412892, 0.6094950282209589, 0.6172590617767771, 0.607132008544496, 0.6080345191414308, 0.5998115849326153, 0.6085742361143607, 0.6078430656223209, 0.5935340795944845, 0.5862705332027911, 0.6173464207571212, 0.6042373835890662, 0.6010630976083375, 0.5991259035560702, 0.5946686067851712, 0.5925791031776069, 0.6052042516849045, 0.6115004325794092, 0.6152243182460431, 0.6045333820662768, 0.6009255107006212, 0.6008323601423038, 0.5949095710792511, 0.59088816113464, 0.6062203096074071, 0.6064241216914394]\n\n # now = \"han_100d_163b_50cx_0.0001_0.5d\"\n # for it in range(30):\n # tf.reset_default_graph()\n # with tf.Session() as sess:\n # lstm = HierarchicalAttention(\n # num_classes=2,\n # vocab_size=embds.shape[0],\n # embedding_size=embds.shape[1]\n # )\n # root_logdir = \"logs\"\n # logdir = \"{}/run-{}-{}/\".format(root_logdir, now, it)\n # acc, macro_f1, f1_0, f1_1, macro_precision, precision_0, precision_1, macro_recall, recall_0, recall_1 = evaluate(\n # sess, data, embds, lstm, logdir)\n # print(acc)\n # acc_han.append(acc)\n # f1_han.append(macro_f1)\n\n print(stats.ttest_ind(acc_ban, acc_cnn, equal_var=False))\n print(stats.ttest_ind(f1_ban, f1_cnn, equal_var=False))",
"step-ids": [
5,
6,
8,
9,
10
]
}
|
[
5,
6,
8,
9,
10
] |
<|reserved_special_token_0|>
def mesh_add_vertex_to_face_edge(mesh, key, fkey, v):
"""Add an existing vertex of the mesh to an existing face.
Parameters
----------
mesh : compas.datastructures.Mesh
The mesh data structure.
key : hashable
The identifier of the vertex.
fkey : hashable
The identifier of the face.
v : hashable
The identifier of the vertex before which the new vertex should be added.
Notes
-----
The algorithm is merely there for convenience.
It does not check if the resulting mesh is still valid.
Examples
--------
Consider the following points and one face definition and the resulting mesh.
>>> points = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.5, 0.0, 0.0]]
>>> faces = [[0, 1, 2, 3]]
>>> mesh = Mesh.from_vertices_and_faces(points, faces)
>>> mesh.number_of_vertices()
5
>>> mesh.number_of_faces()
1
>>> mesh.face_degree(0)
4
>>> mesh.vertex_degree(4)
0
To add the isolated vertex to the single mesh face
>>> mesh_add_vertex_to_face_edge(mesh, 4, 0, 0, 1)
>>> mesh.face_degree(0)
5
>>> mesh.vertex_degree(4)
2
"""
vertices = mesh.face_vertices(fkey)
i = vertices.index(v)
u = vertices[i - 1]
vertices.insert(key, i - 1)
mesh.halfedge[u][key] = fkey
mesh.halfedge[key][v] = fkey
if u not in mesh.halfedge[key]:
mesh.halfedge[key][u] = None
if key not in mesh.halfedge[v]:
mesh.halfedge[v][key] = None
del mesh.halfedge[u][v]
if u in mesh.halfedge[v]:
del mesh.halfedge[v][u]
if (u, v) in mesh.edgedata:
del mesh.edgedata[u, v]
if (v, u) in mesh.edgedata:
del mesh.edgedata[v, u]
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def mesh_add_vertex_to_face_edge(mesh, key, fkey, v):
"""Add an existing vertex of the mesh to an existing face.
Parameters
----------
mesh : compas.datastructures.Mesh
The mesh data structure.
key : hashable
The identifier of the vertex.
fkey : hashable
The identifier of the face.
v : hashable
The identifier of the vertex before which the new vertex should be added.
Notes
-----
The algorithm is merely there for convenience.
It does not check if the resulting mesh is still valid.
Examples
--------
Consider the following points and one face definition and the resulting mesh.
>>> points = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.5, 0.0, 0.0]]
>>> faces = [[0, 1, 2, 3]]
>>> mesh = Mesh.from_vertices_and_faces(points, faces)
>>> mesh.number_of_vertices()
5
>>> mesh.number_of_faces()
1
>>> mesh.face_degree(0)
4
>>> mesh.vertex_degree(4)
0
To add the isolated vertex to the single mesh face
>>> mesh_add_vertex_to_face_edge(mesh, 4, 0, 0, 1)
>>> mesh.face_degree(0)
5
>>> mesh.vertex_degree(4)
2
"""
vertices = mesh.face_vertices(fkey)
i = vertices.index(v)
u = vertices[i - 1]
vertices.insert(key, i - 1)
mesh.halfedge[u][key] = fkey
mesh.halfedge[key][v] = fkey
if u not in mesh.halfedge[key]:
mesh.halfedge[key][u] = None
if key not in mesh.halfedge[v]:
mesh.halfedge[v][key] = None
del mesh.halfedge[u][v]
if u in mesh.halfedge[v]:
del mesh.halfedge[v][u]
if (u, v) in mesh.edgedata:
del mesh.edgedata[u, v]
if (v, u) in mesh.edgedata:
del mesh.edgedata[v, u]
if __name__ == '__main__':
pass
<|reserved_special_token_1|>
<|reserved_special_token_0|>
__all__ = ['mesh_add_vertex_to_face_edge']
def mesh_add_vertex_to_face_edge(mesh, key, fkey, v):
"""Add an existing vertex of the mesh to an existing face.
Parameters
----------
mesh : compas.datastructures.Mesh
The mesh data structure.
key : hashable
The identifier of the vertex.
fkey : hashable
The identifier of the face.
v : hashable
The identifier of the vertex before which the new vertex should be added.
Notes
-----
The algorithm is merely there for convenience.
It does not check if the resulting mesh is still valid.
Examples
--------
Consider the following points and one face definition and the resulting mesh.
>>> points = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.5, 0.0, 0.0]]
>>> faces = [[0, 1, 2, 3]]
>>> mesh = Mesh.from_vertices_and_faces(points, faces)
>>> mesh.number_of_vertices()
5
>>> mesh.number_of_faces()
1
>>> mesh.face_degree(0)
4
>>> mesh.vertex_degree(4)
0
To add the isolated vertex to the single mesh face
>>> mesh_add_vertex_to_face_edge(mesh, 4, 0, 0, 1)
>>> mesh.face_degree(0)
5
>>> mesh.vertex_degree(4)
2
"""
vertices = mesh.face_vertices(fkey)
i = vertices.index(v)
u = vertices[i - 1]
vertices.insert(key, i - 1)
mesh.halfedge[u][key] = fkey
mesh.halfedge[key][v] = fkey
if u not in mesh.halfedge[key]:
mesh.halfedge[key][u] = None
if key not in mesh.halfedge[v]:
mesh.halfedge[v][key] = None
del mesh.halfedge[u][v]
if u in mesh.halfedge[v]:
del mesh.halfedge[v][u]
if (u, v) in mesh.edgedata:
del mesh.edgedata[u, v]
if (v, u) in mesh.edgedata:
del mesh.edgedata[v, u]
if __name__ == '__main__':
pass
<|reserved_special_token_1|>
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
__all__ = ['mesh_add_vertex_to_face_edge']
def mesh_add_vertex_to_face_edge(mesh, key, fkey, v):
"""Add an existing vertex of the mesh to an existing face.
Parameters
----------
mesh : compas.datastructures.Mesh
The mesh data structure.
key : hashable
The identifier of the vertex.
fkey : hashable
The identifier of the face.
v : hashable
The identifier of the vertex before which the new vertex should be added.
Notes
-----
The algorithm is merely there for convenience.
It does not check if the resulting mesh is still valid.
Examples
--------
Consider the following points and one face definition and the resulting mesh.
>>> points = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.5, 0.0, 0.0]]
>>> faces = [[0, 1, 2, 3]]
>>> mesh = Mesh.from_vertices_and_faces(points, faces)
>>> mesh.number_of_vertices()
5
>>> mesh.number_of_faces()
1
>>> mesh.face_degree(0)
4
>>> mesh.vertex_degree(4)
0
To add the isolated vertex to the single mesh face
>>> mesh_add_vertex_to_face_edge(mesh, 4, 0, 0, 1)
>>> mesh.face_degree(0)
5
>>> mesh.vertex_degree(4)
2
"""
vertices = mesh.face_vertices(fkey)
i = vertices.index(v)
u = vertices[i - 1]
vertices.insert(key, i - 1)
mesh.halfedge[u][key] = fkey
mesh.halfedge[key][v] = fkey
if u not in mesh.halfedge[key]:
mesh.halfedge[key][u] = None
if key not in mesh.halfedge[v]:
mesh.halfedge[v][key] = None
del mesh.halfedge[u][v]
if u in mesh.halfedge[v]:
del mesh.halfedge[v][u]
if (u, v) in mesh.edgedata:
del mesh.edgedata[u, v]
if (v, u) in mesh.edgedata:
del mesh.edgedata[v, u]
if __name__ == '__main__':
pass
<|reserved_special_token_1|>
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
__all__ = [
'mesh_add_vertex_to_face_edge'
]
def mesh_add_vertex_to_face_edge(mesh, key, fkey, v):
"""Add an existing vertex of the mesh to an existing face.
Parameters
----------
mesh : compas.datastructures.Mesh
The mesh data structure.
key : hashable
The identifier of the vertex.
fkey : hashable
The identifier of the face.
v : hashable
The identifier of the vertex before which the new vertex should be added.
Notes
-----
The algorithm is merely there for convenience.
It does not check if the resulting mesh is still valid.
Examples
--------
Consider the following points and one face definition and the resulting mesh.
>>> points = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.5, 0.0, 0.0]]
>>> faces = [[0, 1, 2, 3]]
>>> mesh = Mesh.from_vertices_and_faces(points, faces)
>>> mesh.number_of_vertices()
5
>>> mesh.number_of_faces()
1
>>> mesh.face_degree(0)
4
>>> mesh.vertex_degree(4)
0
To add the isolated vertex to the single mesh face
>>> mesh_add_vertex_to_face_edge(mesh, 4, 0, 0, 1)
>>> mesh.face_degree(0)
5
>>> mesh.vertex_degree(4)
2
"""
vertices = mesh.face_vertices(fkey)
i = vertices.index(v)
u = vertices[i - 1]
vertices.insert(key, i - 1)
mesh.halfedge[u][key] = fkey
mesh.halfedge[key][v] = fkey
if u not in mesh.halfedge[key]:
mesh.halfedge[key][u] = None
if key not in mesh.halfedge[v]:
mesh.halfedge[v][key] = None
del mesh.halfedge[u][v]
if u in mesh.halfedge[v]:
del mesh.halfedge[v][u]
if (u, v) in mesh.edgedata:
del mesh.edgedata[u, v]
if (v, u) in mesh.edgedata:
del mesh.edgedata[v, u]
# ==============================================================================
# Main
# ==============================================================================
if __name__ == "__main__":
pass
|
flexible
|
{
"blob_id": "d9b6efce92e30267a9f992c4fea698fe14e0c3e4",
"index": 1398,
"step-1": "<mask token>\n\n\ndef mesh_add_vertex_to_face_edge(mesh, key, fkey, v):\n \"\"\"Add an existing vertex of the mesh to an existing face.\n\n Parameters\n ----------\n mesh : compas.datastructures.Mesh\n The mesh data structure.\n key : hashable\n The identifier of the vertex.\n fkey : hashable\n The identifier of the face.\n v : hashable\n The identifier of the vertex before which the new vertex should be added.\n\n Notes\n -----\n The algorithm is merely there for convenience.\n It does not check if the resulting mesh is still valid.\n\n Examples\n --------\n Consider the following points and one face definition and the resulting mesh.\n\n >>> points = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.5, 0.0, 0.0]]\n >>> faces = [[0, 1, 2, 3]]\n >>> mesh = Mesh.from_vertices_and_faces(points, faces)\n >>> mesh.number_of_vertices()\n 5\n >>> mesh.number_of_faces()\n 1\n >>> mesh.face_degree(0)\n 4\n >>> mesh.vertex_degree(4)\n 0\n\n To add the isolated vertex to the single mesh face\n\n >>> mesh_add_vertex_to_face_edge(mesh, 4, 0, 0, 1)\n >>> mesh.face_degree(0)\n 5\n >>> mesh.vertex_degree(4)\n 2\n\n \"\"\"\n vertices = mesh.face_vertices(fkey)\n i = vertices.index(v)\n u = vertices[i - 1]\n vertices.insert(key, i - 1)\n mesh.halfedge[u][key] = fkey\n mesh.halfedge[key][v] = fkey\n if u not in mesh.halfedge[key]:\n mesh.halfedge[key][u] = None\n if key not in mesh.halfedge[v]:\n mesh.halfedge[v][key] = None\n del mesh.halfedge[u][v]\n if u in mesh.halfedge[v]:\n del mesh.halfedge[v][u]\n if (u, v) in mesh.edgedata:\n del mesh.edgedata[u, v]\n if (v, u) in mesh.edgedata:\n del mesh.edgedata[v, u]\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef mesh_add_vertex_to_face_edge(mesh, key, fkey, v):\n \"\"\"Add an existing vertex of the mesh to an existing face.\n\n Parameters\n ----------\n mesh : compas.datastructures.Mesh\n The mesh data structure.\n key : hashable\n The identifier of the vertex.\n fkey : hashable\n The identifier of the face.\n v : hashable\n The identifier of the vertex before which the new vertex should be added.\n\n Notes\n -----\n The algorithm is merely there for convenience.\n It does not check if the resulting mesh is still valid.\n\n Examples\n --------\n Consider the following points and one face definition and the resulting mesh.\n\n >>> points = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.5, 0.0, 0.0]]\n >>> faces = [[0, 1, 2, 3]]\n >>> mesh = Mesh.from_vertices_and_faces(points, faces)\n >>> mesh.number_of_vertices()\n 5\n >>> mesh.number_of_faces()\n 1\n >>> mesh.face_degree(0)\n 4\n >>> mesh.vertex_degree(4)\n 0\n\n To add the isolated vertex to the single mesh face\n\n >>> mesh_add_vertex_to_face_edge(mesh, 4, 0, 0, 1)\n >>> mesh.face_degree(0)\n 5\n >>> mesh.vertex_degree(4)\n 2\n\n \"\"\"\n vertices = mesh.face_vertices(fkey)\n i = vertices.index(v)\n u = vertices[i - 1]\n vertices.insert(key, i - 1)\n mesh.halfedge[u][key] = fkey\n mesh.halfedge[key][v] = fkey\n if u not in mesh.halfedge[key]:\n mesh.halfedge[key][u] = None\n if key not in mesh.halfedge[v]:\n mesh.halfedge[v][key] = None\n del mesh.halfedge[u][v]\n if u in mesh.halfedge[v]:\n del mesh.halfedge[v][u]\n if (u, v) in mesh.edgedata:\n del mesh.edgedata[u, v]\n if (v, u) in mesh.edgedata:\n del mesh.edgedata[v, u]\n\n\nif __name__ == '__main__':\n pass\n",
"step-3": "<mask token>\n__all__ = ['mesh_add_vertex_to_face_edge']\n\n\ndef mesh_add_vertex_to_face_edge(mesh, key, fkey, v):\n \"\"\"Add an existing vertex of the mesh to an existing face.\n\n Parameters\n ----------\n mesh : compas.datastructures.Mesh\n The mesh data structure.\n key : hashable\n The identifier of the vertex.\n fkey : hashable\n The identifier of the face.\n v : hashable\n The identifier of the vertex before which the new vertex should be added.\n\n Notes\n -----\n The algorithm is merely there for convenience.\n It does not check if the resulting mesh is still valid.\n\n Examples\n --------\n Consider the following points and one face definition and the resulting mesh.\n\n >>> points = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.5, 0.0, 0.0]]\n >>> faces = [[0, 1, 2, 3]]\n >>> mesh = Mesh.from_vertices_and_faces(points, faces)\n >>> mesh.number_of_vertices()\n 5\n >>> mesh.number_of_faces()\n 1\n >>> mesh.face_degree(0)\n 4\n >>> mesh.vertex_degree(4)\n 0\n\n To add the isolated vertex to the single mesh face\n\n >>> mesh_add_vertex_to_face_edge(mesh, 4, 0, 0, 1)\n >>> mesh.face_degree(0)\n 5\n >>> mesh.vertex_degree(4)\n 2\n\n \"\"\"\n vertices = mesh.face_vertices(fkey)\n i = vertices.index(v)\n u = vertices[i - 1]\n vertices.insert(key, i - 1)\n mesh.halfedge[u][key] = fkey\n mesh.halfedge[key][v] = fkey\n if u not in mesh.halfedge[key]:\n mesh.halfedge[key][u] = None\n if key not in mesh.halfedge[v]:\n mesh.halfedge[v][key] = None\n del mesh.halfedge[u][v]\n if u in mesh.halfedge[v]:\n del mesh.halfedge[v][u]\n if (u, v) in mesh.edgedata:\n del mesh.edgedata[u, v]\n if (v, u) in mesh.edgedata:\n del mesh.edgedata[v, u]\n\n\nif __name__ == '__main__':\n pass\n",
"step-4": "from __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import division\n__all__ = ['mesh_add_vertex_to_face_edge']\n\n\ndef mesh_add_vertex_to_face_edge(mesh, key, fkey, v):\n \"\"\"Add an existing vertex of the mesh to an existing face.\n\n Parameters\n ----------\n mesh : compas.datastructures.Mesh\n The mesh data structure.\n key : hashable\n The identifier of the vertex.\n fkey : hashable\n The identifier of the face.\n v : hashable\n The identifier of the vertex before which the new vertex should be added.\n\n Notes\n -----\n The algorithm is merely there for convenience.\n It does not check if the resulting mesh is still valid.\n\n Examples\n --------\n Consider the following points and one face definition and the resulting mesh.\n\n >>> points = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.5, 0.0, 0.0]]\n >>> faces = [[0, 1, 2, 3]]\n >>> mesh = Mesh.from_vertices_and_faces(points, faces)\n >>> mesh.number_of_vertices()\n 5\n >>> mesh.number_of_faces()\n 1\n >>> mesh.face_degree(0)\n 4\n >>> mesh.vertex_degree(4)\n 0\n\n To add the isolated vertex to the single mesh face\n\n >>> mesh_add_vertex_to_face_edge(mesh, 4, 0, 0, 1)\n >>> mesh.face_degree(0)\n 5\n >>> mesh.vertex_degree(4)\n 2\n\n \"\"\"\n vertices = mesh.face_vertices(fkey)\n i = vertices.index(v)\n u = vertices[i - 1]\n vertices.insert(key, i - 1)\n mesh.halfedge[u][key] = fkey\n mesh.halfedge[key][v] = fkey\n if u not in mesh.halfedge[key]:\n mesh.halfedge[key][u] = None\n if key not in mesh.halfedge[v]:\n mesh.halfedge[v][key] = None\n del mesh.halfedge[u][v]\n if u in mesh.halfedge[v]:\n del mesh.halfedge[v][u]\n if (u, v) in mesh.edgedata:\n del mesh.edgedata[u, v]\n if (v, u) in mesh.edgedata:\n del mesh.edgedata[v, u]\n\n\nif __name__ == '__main__':\n pass\n",
"step-5": "from __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import division\n\n\n__all__ = [\n 'mesh_add_vertex_to_face_edge'\n]\n\n\ndef mesh_add_vertex_to_face_edge(mesh, key, fkey, v):\n \"\"\"Add an existing vertex of the mesh to an existing face.\n\n Parameters\n ----------\n mesh : compas.datastructures.Mesh\n The mesh data structure.\n key : hashable\n The identifier of the vertex.\n fkey : hashable\n The identifier of the face.\n v : hashable\n The identifier of the vertex before which the new vertex should be added.\n\n Notes\n -----\n The algorithm is merely there for convenience.\n It does not check if the resulting mesh is still valid.\n\n Examples\n --------\n Consider the following points and one face definition and the resulting mesh.\n\n >>> points = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.5, 0.0, 0.0]]\n >>> faces = [[0, 1, 2, 3]]\n >>> mesh = Mesh.from_vertices_and_faces(points, faces)\n >>> mesh.number_of_vertices()\n 5\n >>> mesh.number_of_faces()\n 1\n >>> mesh.face_degree(0)\n 4\n >>> mesh.vertex_degree(4)\n 0\n\n To add the isolated vertex to the single mesh face\n\n >>> mesh_add_vertex_to_face_edge(mesh, 4, 0, 0, 1)\n >>> mesh.face_degree(0)\n 5\n >>> mesh.vertex_degree(4)\n 2\n\n \"\"\"\n vertices = mesh.face_vertices(fkey)\n i = vertices.index(v)\n u = vertices[i - 1]\n vertices.insert(key, i - 1)\n mesh.halfedge[u][key] = fkey\n mesh.halfedge[key][v] = fkey\n if u not in mesh.halfedge[key]:\n mesh.halfedge[key][u] = None\n if key not in mesh.halfedge[v]:\n mesh.halfedge[v][key] = None\n del mesh.halfedge[u][v]\n if u in mesh.halfedge[v]:\n del mesh.halfedge[v][u]\n if (u, v) in mesh.edgedata:\n del mesh.edgedata[u, v]\n if (v, u) in mesh.edgedata:\n del mesh.edgedata[v, u]\n\n\n# ==============================================================================\n# Main\n# ==============================================================================\n\nif __name__ == \"__main__\":\n pass\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
# Generated by Django 2.0 on 2018-03-06 16:21
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('digressions', '0004_auto_20180303_1158'),
]
operations = [
migrations.RemoveField(
model_name='extraits',
name='extraits_livre_id',
),
migrations.AddField(
model_name='extraits',
name='extraits_livre_id',
field=models.ForeignKey(default='du coté de chez Swann', on_delete=django.db.models.deletion.CASCADE, to='digressions.Livre'),
preserve_default=False,
),
]
|
normal
|
{
"blob_id": "38c21fb959d8b98b616006ea48bd720cc6f9995c",
"index": 1462,
"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 = [('digressions', '0004_auto_20180303_1158')]\n operations = [migrations.RemoveField(model_name='extraits', name=\n 'extraits_livre_id'), migrations.AddField(model_name='extraits',\n name='extraits_livre_id', field=models.ForeignKey(default=\n 'du coté de chez Swann', on_delete=django.db.models.deletion.\n CASCADE, to='digressions.Livre'), preserve_default=False)]\n",
"step-4": "from django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n dependencies = [('digressions', '0004_auto_20180303_1158')]\n operations = [migrations.RemoveField(model_name='extraits', name=\n 'extraits_livre_id'), migrations.AddField(model_name='extraits',\n name='extraits_livre_id', field=models.ForeignKey(default=\n 'du coté de chez Swann', on_delete=django.db.models.deletion.\n CASCADE, to='digressions.Livre'), preserve_default=False)]\n",
"step-5": "# Generated by Django 2.0 on 2018-03-06 16:21\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('digressions', '0004_auto_20180303_1158'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='extraits',\n name='extraits_livre_id',\n ),\n migrations.AddField(\n model_name='extraits',\n name='extraits_livre_id',\n field=models.ForeignKey(default='du coté de chez Swann', on_delete=django.db.models.deletion.CASCADE, to='digressions.Livre'),\n preserve_default=False,\n ),\n ]\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def tnrange(*args, **kwargs):
...
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def tqdm_notebook(*args, **kwargs):
...
def tnrange(*args, **kwargs):
...
<|reserved_special_token_1|>
from ._monitor import TMonitor as TMonitor, TqdmSynchronisationWarning as TqdmSynchronisationWarning
from ._tqdm_pandas import tqdm_pandas as tqdm_pandas
from .cli import main as main
from .gui import tqdm as tqdm_gui, trange as tgrange
from .std import TqdmDeprecationWarning as TqdmDeprecationWarning, TqdmExperimentalWarning as TqdmExperimentalWarning, TqdmKeyError as TqdmKeyError, TqdmMonitorWarning as TqdmMonitorWarning, TqdmTypeError as TqdmTypeError, TqdmWarning as TqdmWarning, tqdm as tqdm, trange as trange
def tqdm_notebook(*args, **kwargs):
...
def tnrange(*args, **kwargs):
...
|
flexible
|
{
"blob_id": "25b7af2a8036f35a0bca665867d1729b7c9c113c",
"index": 5846,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef tnrange(*args, **kwargs):\n ...\n",
"step-3": "<mask token>\n\n\ndef tqdm_notebook(*args, **kwargs):\n ...\n\n\ndef tnrange(*args, **kwargs):\n ...\n",
"step-4": "from ._monitor import TMonitor as TMonitor, TqdmSynchronisationWarning as TqdmSynchronisationWarning\nfrom ._tqdm_pandas import tqdm_pandas as tqdm_pandas\nfrom .cli import main as main\nfrom .gui import tqdm as tqdm_gui, trange as tgrange\nfrom .std import TqdmDeprecationWarning as TqdmDeprecationWarning, TqdmExperimentalWarning as TqdmExperimentalWarning, TqdmKeyError as TqdmKeyError, TqdmMonitorWarning as TqdmMonitorWarning, TqdmTypeError as TqdmTypeError, TqdmWarning as TqdmWarning, tqdm as tqdm, trange as trange\n\n\ndef tqdm_notebook(*args, **kwargs):\n ...\n\n\ndef tnrange(*args, **kwargs):\n ...\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
def f(x):
return np.sin(x / 5) * np.exp(x / 10) + 5 * np.exp(-x / 2)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def f(x):
return np.sin(x / 5) * np.exp(x / 10) + 5 * np.exp(-x / 2)
<|reserved_special_token_0|>
plt.plot(xx, y1, '-', xx, yy, '-')
plt.show()
<|reserved_special_token_0|>
plt.plot(xx, y2, '-', xx, yy, '-')
plt.show()
<|reserved_special_token_0|>
plt.plot(xx, y3, '-', xx, yy, '-')
plt.show()
print('w 0:4 : ', ' '.join(map(str, np.round(w, 2))))
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def f(x):
return np.sin(x / 5) * np.exp(x / 10) + 5 * np.exp(-x / 2)
xx = np.arange(1, 15, 0.1)
yy = f(xx)
x = np.array([1, 15])
y = f(x)
A = np.array([[1, 1], [1, 15]])
w = solve(A, y)
y1 = w[0] + w[1] * xx
plt.plot(xx, y1, '-', xx, yy, '-')
plt.show()
x = np.array([1, 8, 15])
y = f(x)
A = np.array([[1, 1, 1], [1, 8, 64], [1, 15, 225]])
w = solve(A, y)
y2 = w[0] + w[1] * xx + w[2] * xx ** 2
plt.plot(xx, y2, '-', xx, yy, '-')
plt.show()
x = np.array([1, 4, 10, 15])
y = f(x)
A = np.array([[1, 1, 1, 1], [1, 4, 16, 64], [1, 10, 100, 1000], [1, 15, 225,
225 * 15]])
w = solve(A, y)
y3 = w[0] + w[1] * xx + w[2] * xx ** 2 + w[3] * xx ** 3
plt.plot(xx, y3, '-', xx, yy, '-')
plt.show()
print('w 0:4 : ', ' '.join(map(str, np.round(w, 2))))
<|reserved_special_token_1|>
import numpy as np
from scipy.linalg import solve
from matplotlib import pylab as plt
def f(x):
return np.sin(x / 5) * np.exp(x / 10) + 5 * np.exp(-x / 2)
xx = np.arange(1, 15, 0.1)
yy = f(xx)
x = np.array([1, 15])
y = f(x)
A = np.array([[1, 1], [1, 15]])
w = solve(A, y)
y1 = w[0] + w[1] * xx
plt.plot(xx, y1, '-', xx, yy, '-')
plt.show()
x = np.array([1, 8, 15])
y = f(x)
A = np.array([[1, 1, 1], [1, 8, 64], [1, 15, 225]])
w = solve(A, y)
y2 = w[0] + w[1] * xx + w[2] * xx ** 2
plt.plot(xx, y2, '-', xx, yy, '-')
plt.show()
x = np.array([1, 4, 10, 15])
y = f(x)
A = np.array([[1, 1, 1, 1], [1, 4, 16, 64], [1, 10, 100, 1000], [1, 15, 225,
225 * 15]])
w = solve(A, y)
y3 = w[0] + w[1] * xx + w[2] * xx ** 2 + w[3] * xx ** 3
plt.plot(xx, y3, '-', xx, yy, '-')
plt.show()
print('w 0:4 : ', ' '.join(map(str, np.round(w, 2))))
<|reserved_special_token_1|>
import numpy as np
from scipy.linalg import solve
from matplotlib import pylab as plt
def f(x):
return (np.sin(x / 5) * np.exp(x / 10) + 5 * np.exp(-x / 2))
xx = np.arange(1, 15, 0.1)
yy = f(xx)
# 1 степень
x = np.array([1,15])
y = f(x)
A = np.array([[1,1], [1,15]])
w = solve(A, y)
y1 = w[0] + w[1]*xx
plt.plot(xx, y1, '-', xx, yy, '-')
plt.show()
# 2 степень
x = np.array([1, 8, 15])
y = f(x)
A = np.array([[1,1,1], [1,8,64], [1,15,225]])
w = solve(A, y)
y2 = w[0] + w[1]*xx + w[2]*(xx**2)
plt.plot(xx, y2, '-', xx, yy, '-')
plt.show()
# 3 степень
x = np.array([1, 4, 10, 15])
y = f(x)
A = np.array([[1,1,1,1], [1,4,16,64], [1,10,100,1000], [1,15,225,225*15]])
w = solve(A, y)
y3 = w[0] + w[1]*xx + w[2]*(xx**2) + w[3]*(xx**3)
plt.plot(xx, y3, '-', xx, yy, '-')
plt.show()
print("w 0:4 : ", " ".join(map(str, np.round(w, 2))))
|
flexible
|
{
"blob_id": "a610ccf4fe154ee12de9212a10958fda2000b425",
"index": 7122,
"step-1": "<mask token>\n\n\ndef f(x):\n return np.sin(x / 5) * np.exp(x / 10) + 5 * np.exp(-x / 2)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef f(x):\n return np.sin(x / 5) * np.exp(x / 10) + 5 * np.exp(-x / 2)\n\n\n<mask token>\nplt.plot(xx, y1, '-', xx, yy, '-')\nplt.show()\n<mask token>\nplt.plot(xx, y2, '-', xx, yy, '-')\nplt.show()\n<mask token>\nplt.plot(xx, y3, '-', xx, yy, '-')\nplt.show()\nprint('w 0:4 : ', ' '.join(map(str, np.round(w, 2))))\n",
"step-3": "<mask token>\n\n\ndef f(x):\n return np.sin(x / 5) * np.exp(x / 10) + 5 * np.exp(-x / 2)\n\n\nxx = np.arange(1, 15, 0.1)\nyy = f(xx)\nx = np.array([1, 15])\ny = f(x)\nA = np.array([[1, 1], [1, 15]])\nw = solve(A, y)\ny1 = w[0] + w[1] * xx\nplt.plot(xx, y1, '-', xx, yy, '-')\nplt.show()\nx = np.array([1, 8, 15])\ny = f(x)\nA = np.array([[1, 1, 1], [1, 8, 64], [1, 15, 225]])\nw = solve(A, y)\ny2 = w[0] + w[1] * xx + w[2] * xx ** 2\nplt.plot(xx, y2, '-', xx, yy, '-')\nplt.show()\nx = np.array([1, 4, 10, 15])\ny = f(x)\nA = np.array([[1, 1, 1, 1], [1, 4, 16, 64], [1, 10, 100, 1000], [1, 15, 225,\n 225 * 15]])\nw = solve(A, y)\ny3 = w[0] + w[1] * xx + w[2] * xx ** 2 + w[3] * xx ** 3\nplt.plot(xx, y3, '-', xx, yy, '-')\nplt.show()\nprint('w 0:4 : ', ' '.join(map(str, np.round(w, 2))))\n",
"step-4": "import numpy as np\nfrom scipy.linalg import solve\nfrom matplotlib import pylab as plt\n\n\ndef f(x):\n return np.sin(x / 5) * np.exp(x / 10) + 5 * np.exp(-x / 2)\n\n\nxx = np.arange(1, 15, 0.1)\nyy = f(xx)\nx = np.array([1, 15])\ny = f(x)\nA = np.array([[1, 1], [1, 15]])\nw = solve(A, y)\ny1 = w[0] + w[1] * xx\nplt.plot(xx, y1, '-', xx, yy, '-')\nplt.show()\nx = np.array([1, 8, 15])\ny = f(x)\nA = np.array([[1, 1, 1], [1, 8, 64], [1, 15, 225]])\nw = solve(A, y)\ny2 = w[0] + w[1] * xx + w[2] * xx ** 2\nplt.plot(xx, y2, '-', xx, yy, '-')\nplt.show()\nx = np.array([1, 4, 10, 15])\ny = f(x)\nA = np.array([[1, 1, 1, 1], [1, 4, 16, 64], [1, 10, 100, 1000], [1, 15, 225,\n 225 * 15]])\nw = solve(A, y)\ny3 = w[0] + w[1] * xx + w[2] * xx ** 2 + w[3] * xx ** 3\nplt.plot(xx, y3, '-', xx, yy, '-')\nplt.show()\nprint('w 0:4 : ', ' '.join(map(str, np.round(w, 2))))\n",
"step-5": "import numpy as np\r\nfrom scipy.linalg import solve\r\nfrom matplotlib import pylab as plt\r\n\r\ndef f(x):\r\n return (np.sin(x / 5) * np.exp(x / 10) + 5 * np.exp(-x / 2))\r\n\r\nxx = np.arange(1, 15, 0.1)\r\nyy = f(xx)\r\n\r\n# 1 степень\r\nx = np.array([1,15])\r\ny = f(x)\r\n\r\nA = np.array([[1,1], [1,15]])\r\nw = solve(A, y)\r\n\r\ny1 = w[0] + w[1]*xx\r\n\r\nplt.plot(xx, y1, '-', xx, yy, '-')\r\nplt.show()\r\n\r\n# 2 степень\r\nx = np.array([1, 8, 15])\r\ny = f(x)\r\n\r\nA = np.array([[1,1,1], [1,8,64], [1,15,225]])\r\nw = solve(A, y)\r\n\r\ny2 = w[0] + w[1]*xx + w[2]*(xx**2)\r\n\r\nplt.plot(xx, y2, '-', xx, yy, '-')\r\nplt.show()\r\n\r\n# 3 степень\r\nx = np.array([1, 4, 10, 15])\r\ny = f(x)\r\n\r\nA = np.array([[1,1,1,1], [1,4,16,64], [1,10,100,1000], [1,15,225,225*15]])\r\nw = solve(A, y)\r\n\r\ny3 = w[0] + w[1]*xx + w[2]*(xx**2) + w[3]*(xx**3)\r\n\r\nplt.plot(xx, y3, '-', xx, yy, '-')\r\nplt.show()\r\n\r\nprint(\"w 0:4 : \", \" \".join(map(str, np.round(w, 2))))",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
<|reserved_special_token_0|>
def dropper():
for ex in affected['word']:
if ex not in model.vocab:
idx_to_drop.append(affected.loc[affected.word == ex].index[0])
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
print('loading & cleaning the data...')
<|reserved_special_token_0|>
em_words.drop('remove', axis=1, inplace=True)
<|reserved_special_token_0|>
em_words.drop(['toss1', 'toss2', 'toss3', 'toss4', 'toss5', 'toss6',
'toss7', 'toss8', 'toss9'], axis=1, inplace=True)
<|reserved_special_token_0|>
print("training the word2vec model from google's corpus")
<|reserved_special_token_0|>
def dropper():
for ex in affected['word']:
if ex not in model.vocab:
idx_to_drop.append(affected.loc[affected.word == ex].index[0])
dropper()
<|reserved_special_token_0|>
print('splitting into train/test groups...')
<|reserved_special_token_0|>
print("creating a model with the best stuff we've got...")
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
loc = (
'https://s3-us-west-1.amazonaws.com/victorsdatasets/NRCEmotionLexiconv092AnnotatorandSenseLevel.txt'
)
print('loading & cleaning the data...')
em_words = pd.read_csv(loc, sep='\t', names=['annotator_id', 'remove',
'word', 'joy', 'sadness', 'fear', 'anger', 'trust', 'disgust',
'surprise', 'anticipation', 'POS'])
em_words.drop('remove', axis=1, inplace=True)
em_words['word'], em_words['synonym'] = em_words['word'].str.split('--').str
em_words['toss1'], em_words['joy'] = em_words['joy'].str.split('-').str
em_words['toss2'], em_words['sadness'] = em_words['sadness'].str.split('-').str
em_words['toss3'], em_words['fear'] = em_words['fear'].str.split('-').str
em_words['toss4'], em_words['anger'] = em_words['anger'].str.split('-').str
em_words['toss5'], em_words['trust'] = em_words['trust'].str.split('-').str
em_words['toss6'], em_words['disgust'] = em_words['disgust'].str.split('-').str
em_words['toss7'], em_words['surprise'] = em_words['surprise'].str.split('-'
).str
em_words['toss8'], em_words['anticipation'] = em_words['anticipation'
].str.split('-').str
em_words['toss9'], em_words['POS'] = em_words['POS'].str.split('-').str
em_words.drop(['toss1', 'toss2', 'toss3', 'toss4', 'toss5', 'toss6',
'toss7', 'toss8', 'toss9'], axis=1, inplace=True)
new_cols = ['annotator_id', 'word', 'synonym', 'joy', 'sadness', 'fear',
'anger', 'trust', 'disgust', 'surprise', 'anticipation', 'POS']
em_words = em_words.reindex_axis(new_cols, axis=1)
emotions = em_words[['joy', 'sadness', 'fear', 'anger', 'trust', 'disgust',
'surprise', 'anticipation']]
em_words[emotions.columns] = em_words[emotions.columns].apply(pd.to_numeric)
affected = em_words[emotions.columns].groupby([em_words['word']], sort=False
).mean().reset_index()
print("training the word2vec model from google's corpus")
model = gensim.models.Word2Vec.load_word2vec_format(
'../GoogleNews-vectors-negative300.bin', binary=True)
idx_to_drop = []
def dropper():
for ex in affected['word']:
if ex not in model.vocab:
idx_to_drop.append(affected.loc[affected.word == ex].index[0])
dropper()
affected = affected.drop(idx_to_drop, axis=0)
G_vectors = lambda x: model[x]
affected['word_vectors'] = affected['word'].apply(G_vectors)
affected['label_vectors'] = affected[emotions.columns].values.tolist()
affected['binary'] = (affected[emotions.columns] > 0).astype(int
).values.tolist()
df1 = affected[emotions.columns].rank(method='max', axis=1).rank(method=
'first', axis=1)
ma = df1.max().max()
affected['label'] = (df1 == ma).astype(int).values.tolist()
affected['target'] = affected['label'].apply(lambda x: x.index(1))
label_dict = {(0): 'joy', (1): 'sadness', (2): 'fear', (3): 'anger', (4):
'trust', (5): 'disgust', (6): 'surprise', (7): 'anticipation'}
affected['label_name'] = affected['target'].apply(lambda x: label_dict[x])
emo2vec = affected[['word_vectors', 'label_vectors', 'binary', 'label',
'target', 'label_name']]
print('splitting into train/test groups...')
emo_X, emo_y = list(emo2vec.word_vectors), list(emo2vec.target)
emo_X_train, emo_X_test, emo_y_train, emo_y_test = train_test_split(emo_X,
emo_y, random_state=42)
print("creating a model with the best stuff we've got...")
OVR = OneVsRestClassifier(LinearSVC(random_state=0), n_jobs=-1)
emo_model = OVR.fit(emo_X_train, emo_y_train)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
import pandas as pd
import gensim
from sklearn.model_selection import train_test_split
from sklearn.multiclass import OneVsRestClassifier
from sklearn.svm import LinearSVC
loc = (
'https://s3-us-west-1.amazonaws.com/victorsdatasets/NRCEmotionLexiconv092AnnotatorandSenseLevel.txt'
)
print('loading & cleaning the data...')
em_words = pd.read_csv(loc, sep='\t', names=['annotator_id', 'remove',
'word', 'joy', 'sadness', 'fear', 'anger', 'trust', 'disgust',
'surprise', 'anticipation', 'POS'])
em_words.drop('remove', axis=1, inplace=True)
em_words['word'], em_words['synonym'] = em_words['word'].str.split('--').str
em_words['toss1'], em_words['joy'] = em_words['joy'].str.split('-').str
em_words['toss2'], em_words['sadness'] = em_words['sadness'].str.split('-').str
em_words['toss3'], em_words['fear'] = em_words['fear'].str.split('-').str
em_words['toss4'], em_words['anger'] = em_words['anger'].str.split('-').str
em_words['toss5'], em_words['trust'] = em_words['trust'].str.split('-').str
em_words['toss6'], em_words['disgust'] = em_words['disgust'].str.split('-').str
em_words['toss7'], em_words['surprise'] = em_words['surprise'].str.split('-'
).str
em_words['toss8'], em_words['anticipation'] = em_words['anticipation'
].str.split('-').str
em_words['toss9'], em_words['POS'] = em_words['POS'].str.split('-').str
em_words.drop(['toss1', 'toss2', 'toss3', 'toss4', 'toss5', 'toss6',
'toss7', 'toss8', 'toss9'], axis=1, inplace=True)
new_cols = ['annotator_id', 'word', 'synonym', 'joy', 'sadness', 'fear',
'anger', 'trust', 'disgust', 'surprise', 'anticipation', 'POS']
em_words = em_words.reindex_axis(new_cols, axis=1)
emotions = em_words[['joy', 'sadness', 'fear', 'anger', 'trust', 'disgust',
'surprise', 'anticipation']]
em_words[emotions.columns] = em_words[emotions.columns].apply(pd.to_numeric)
affected = em_words[emotions.columns].groupby([em_words['word']], sort=False
).mean().reset_index()
print("training the word2vec model from google's corpus")
model = gensim.models.Word2Vec.load_word2vec_format(
'../GoogleNews-vectors-negative300.bin', binary=True)
idx_to_drop = []
def dropper():
for ex in affected['word']:
if ex not in model.vocab:
idx_to_drop.append(affected.loc[affected.word == ex].index[0])
dropper()
affected = affected.drop(idx_to_drop, axis=0)
G_vectors = lambda x: model[x]
affected['word_vectors'] = affected['word'].apply(G_vectors)
affected['label_vectors'] = affected[emotions.columns].values.tolist()
affected['binary'] = (affected[emotions.columns] > 0).astype(int
).values.tolist()
df1 = affected[emotions.columns].rank(method='max', axis=1).rank(method=
'first', axis=1)
ma = df1.max().max()
affected['label'] = (df1 == ma).astype(int).values.tolist()
affected['target'] = affected['label'].apply(lambda x: x.index(1))
label_dict = {(0): 'joy', (1): 'sadness', (2): 'fear', (3): 'anger', (4):
'trust', (5): 'disgust', (6): 'surprise', (7): 'anticipation'}
affected['label_name'] = affected['target'].apply(lambda x: label_dict[x])
emo2vec = affected[['word_vectors', 'label_vectors', 'binary', 'label',
'target', 'label_name']]
print('splitting into train/test groups...')
emo_X, emo_y = list(emo2vec.word_vectors), list(emo2vec.target)
emo_X_train, emo_X_test, emo_y_train, emo_y_test = train_test_split(emo_X,
emo_y, random_state=42)
print("creating a model with the best stuff we've got...")
OVR = OneVsRestClassifier(LinearSVC(random_state=0), n_jobs=-1)
emo_model = OVR.fit(emo_X_train, emo_y_train)
<|reserved_special_token_1|>
# coding: utf-8
"""Supporting model logic for predicting emotional content of user input.
"""
import pandas as pd
import gensim
from sklearn.model_selection import train_test_split
from sklearn.multiclass import OneVsRestClassifier
from sklearn.svm import LinearSVC
#load data for emo2vec
loc = 'https://s3-us-west-1.amazonaws.com/victorsdatasets/NRCEmotionLexiconv092AnnotatorandSenseLevel.txt'
print("loading & cleaning the data...")
em_words = pd.read_csv(loc, sep='\t', names=['annotator_id',
'remove',
'word',
'joy',
'sadness',
'fear',
'anger',
'trust',
'disgust',
'surprise',
'anticipation',
'POS'])
em_words.drop('remove', axis=1, inplace=True)
em_words['word'], em_words['synonym'] = em_words['word'].str.split('--').str
em_words['toss1'], em_words['joy'] = em_words['joy'].str.split('-').str
em_words['toss2'], em_words['sadness'] = em_words['sadness'].str.split('-').str
em_words['toss3'], em_words['fear'] = em_words['fear'].str.split('-').str
em_words['toss4'], em_words['anger'] = em_words['anger'].str.split('-').str
em_words['toss5'], em_words['trust'] = em_words['trust'].str.split('-').str
em_words['toss6'], em_words['disgust'] = em_words['disgust'].str.split('-').str
em_words['toss7'], em_words['surprise'] = em_words['surprise'].str.split('-').str
em_words['toss8'], em_words['anticipation'] = em_words['anticipation'].str.split('-').str
em_words['toss9'], em_words['POS'] = em_words['POS'].str.split('-').str
em_words.drop(['toss1','toss2','toss3','toss4','toss5','toss6','toss7','toss8','toss9'],
axis=1,
inplace=True)
new_cols = ['annotator_id',
'word','synonym',
'joy',
'sadness',
'fear',
'anger',
'trust',
'disgust',
'surprise',
'anticipation',
'POS']
em_words = em_words.reindex_axis(new_cols, axis=1)
emotions = em_words[['joy',
'sadness',
'fear',
'anger',
'trust',
'disgust',
'surprise',
'anticipation']]
em_words[emotions.columns] = em_words[emotions.columns].apply(pd.to_numeric)
affected = em_words[emotions.columns].groupby([em_words['word']], sort=False).mean().reset_index()
# Load Google's pre-trained Word2Vec model.
print('training the word2vec model from google\'s corpus')
model = gensim.models.Word2Vec.load_word2vec_format('../GoogleNews-vectors-negative300.bin', binary=True)
# create list of word indicies to drop to avoid keyerrors with Google's pre-trained model.
idx_to_drop = []
def dropper():
for ex in affected['word']:
if ex not in model.vocab:
idx_to_drop.append(affected.loc[affected.word == ex].index[0])
# drop words from affected that are not in google's model
dropper()
affected = affected.drop(idx_to_drop, axis=0)
G_vectors = lambda x: model[x]
affected['word_vectors'] = affected['word'].apply(G_vectors)
affected['label_vectors'] = affected[emotions.columns].values.tolist()
affected['binary'] = (affected[emotions.columns] > 0).astype(int).values.tolist()
df1 = affected[emotions.columns].rank(method='max', axis=1).rank(method='first', axis=1)
ma = df1.max().max()
affected['label'] = (df1== ma).astype(int).values.tolist()
affected['target'] = affected['label'].apply(lambda x: x.index(1))
label_dict = {0 : 'joy',
1 : 'sadness',
2 : 'fear',
3 : 'anger',
4 : 'trust',
5 : 'disgust',
6 : 'surprise',
7 : 'anticipation'}
affected['label_name'] = affected['target'].apply(lambda x: label_dict[x])
emo2vec = affected[['word_vectors', 'label_vectors', 'binary', 'label', 'target', 'label_name']]
# # Model Testing
print("splitting into train/test groups...")
emo_X, emo_y = list(emo2vec.word_vectors), list(emo2vec.target)
emo_X_train, emo_X_test, emo_y_train, emo_y_test = train_test_split(emo_X, emo_y, random_state=42)
# ### OnevsRest with LinearSVC (best score)
print("creating a model with the best stuff we've got...")
OVR = OneVsRestClassifier(LinearSVC(random_state=0), n_jobs=-1)
emo_model = OVR.fit(emo_X_train, emo_y_train)
|
flexible
|
{
"blob_id": "f5f26819be4b98fab3d46e57e1a5431e54342aed",
"index": 414,
"step-1": "<mask token>\n\n\ndef dropper():\n for ex in affected['word']:\n if ex not in model.vocab:\n idx_to_drop.append(affected.loc[affected.word == ex].index[0])\n\n\n<mask token>\n",
"step-2": "<mask token>\nprint('loading & cleaning the data...')\n<mask token>\nem_words.drop('remove', axis=1, inplace=True)\n<mask token>\nem_words.drop(['toss1', 'toss2', 'toss3', 'toss4', 'toss5', 'toss6',\n 'toss7', 'toss8', 'toss9'], axis=1, inplace=True)\n<mask token>\nprint(\"training the word2vec model from google's corpus\")\n<mask token>\n\n\ndef dropper():\n for ex in affected['word']:\n if ex not in model.vocab:\n idx_to_drop.append(affected.loc[affected.word == ex].index[0])\n\n\ndropper()\n<mask token>\nprint('splitting into train/test groups...')\n<mask token>\nprint(\"creating a model with the best stuff we've got...\")\n<mask token>\n",
"step-3": "<mask token>\nloc = (\n 'https://s3-us-west-1.amazonaws.com/victorsdatasets/NRCEmotionLexiconv092AnnotatorandSenseLevel.txt'\n )\nprint('loading & cleaning the data...')\nem_words = pd.read_csv(loc, sep='\\t', names=['annotator_id', 'remove',\n 'word', 'joy', 'sadness', 'fear', 'anger', 'trust', 'disgust',\n 'surprise', 'anticipation', 'POS'])\nem_words.drop('remove', axis=1, inplace=True)\nem_words['word'], em_words['synonym'] = em_words['word'].str.split('--').str\nem_words['toss1'], em_words['joy'] = em_words['joy'].str.split('-').str\nem_words['toss2'], em_words['sadness'] = em_words['sadness'].str.split('-').str\nem_words['toss3'], em_words['fear'] = em_words['fear'].str.split('-').str\nem_words['toss4'], em_words['anger'] = em_words['anger'].str.split('-').str\nem_words['toss5'], em_words['trust'] = em_words['trust'].str.split('-').str\nem_words['toss6'], em_words['disgust'] = em_words['disgust'].str.split('-').str\nem_words['toss7'], em_words['surprise'] = em_words['surprise'].str.split('-'\n ).str\nem_words['toss8'], em_words['anticipation'] = em_words['anticipation'\n ].str.split('-').str\nem_words['toss9'], em_words['POS'] = em_words['POS'].str.split('-').str\nem_words.drop(['toss1', 'toss2', 'toss3', 'toss4', 'toss5', 'toss6',\n 'toss7', 'toss8', 'toss9'], axis=1, inplace=True)\nnew_cols = ['annotator_id', 'word', 'synonym', 'joy', 'sadness', 'fear',\n 'anger', 'trust', 'disgust', 'surprise', 'anticipation', 'POS']\nem_words = em_words.reindex_axis(new_cols, axis=1)\nemotions = em_words[['joy', 'sadness', 'fear', 'anger', 'trust', 'disgust',\n 'surprise', 'anticipation']]\nem_words[emotions.columns] = em_words[emotions.columns].apply(pd.to_numeric)\naffected = em_words[emotions.columns].groupby([em_words['word']], sort=False\n ).mean().reset_index()\nprint(\"training the word2vec model from google's corpus\")\nmodel = gensim.models.Word2Vec.load_word2vec_format(\n '../GoogleNews-vectors-negative300.bin', binary=True)\nidx_to_drop = []\n\n\ndef dropper():\n for ex in affected['word']:\n if ex not in model.vocab:\n idx_to_drop.append(affected.loc[affected.word == ex].index[0])\n\n\ndropper()\naffected = affected.drop(idx_to_drop, axis=0)\nG_vectors = lambda x: model[x]\naffected['word_vectors'] = affected['word'].apply(G_vectors)\naffected['label_vectors'] = affected[emotions.columns].values.tolist()\naffected['binary'] = (affected[emotions.columns] > 0).astype(int\n ).values.tolist()\ndf1 = affected[emotions.columns].rank(method='max', axis=1).rank(method=\n 'first', axis=1)\nma = df1.max().max()\naffected['label'] = (df1 == ma).astype(int).values.tolist()\naffected['target'] = affected['label'].apply(lambda x: x.index(1))\nlabel_dict = {(0): 'joy', (1): 'sadness', (2): 'fear', (3): 'anger', (4):\n 'trust', (5): 'disgust', (6): 'surprise', (7): 'anticipation'}\naffected['label_name'] = affected['target'].apply(lambda x: label_dict[x])\nemo2vec = affected[['word_vectors', 'label_vectors', 'binary', 'label',\n 'target', 'label_name']]\nprint('splitting into train/test groups...')\nemo_X, emo_y = list(emo2vec.word_vectors), list(emo2vec.target)\nemo_X_train, emo_X_test, emo_y_train, emo_y_test = train_test_split(emo_X,\n emo_y, random_state=42)\nprint(\"creating a model with the best stuff we've got...\")\nOVR = OneVsRestClassifier(LinearSVC(random_state=0), n_jobs=-1)\nemo_model = OVR.fit(emo_X_train, emo_y_train)\n",
"step-4": "<mask token>\nimport pandas as pd\nimport gensim\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.svm import LinearSVC\nloc = (\n 'https://s3-us-west-1.amazonaws.com/victorsdatasets/NRCEmotionLexiconv092AnnotatorandSenseLevel.txt'\n )\nprint('loading & cleaning the data...')\nem_words = pd.read_csv(loc, sep='\\t', names=['annotator_id', 'remove',\n 'word', 'joy', 'sadness', 'fear', 'anger', 'trust', 'disgust',\n 'surprise', 'anticipation', 'POS'])\nem_words.drop('remove', axis=1, inplace=True)\nem_words['word'], em_words['synonym'] = em_words['word'].str.split('--').str\nem_words['toss1'], em_words['joy'] = em_words['joy'].str.split('-').str\nem_words['toss2'], em_words['sadness'] = em_words['sadness'].str.split('-').str\nem_words['toss3'], em_words['fear'] = em_words['fear'].str.split('-').str\nem_words['toss4'], em_words['anger'] = em_words['anger'].str.split('-').str\nem_words['toss5'], em_words['trust'] = em_words['trust'].str.split('-').str\nem_words['toss6'], em_words['disgust'] = em_words['disgust'].str.split('-').str\nem_words['toss7'], em_words['surprise'] = em_words['surprise'].str.split('-'\n ).str\nem_words['toss8'], em_words['anticipation'] = em_words['anticipation'\n ].str.split('-').str\nem_words['toss9'], em_words['POS'] = em_words['POS'].str.split('-').str\nem_words.drop(['toss1', 'toss2', 'toss3', 'toss4', 'toss5', 'toss6',\n 'toss7', 'toss8', 'toss9'], axis=1, inplace=True)\nnew_cols = ['annotator_id', 'word', 'synonym', 'joy', 'sadness', 'fear',\n 'anger', 'trust', 'disgust', 'surprise', 'anticipation', 'POS']\nem_words = em_words.reindex_axis(new_cols, axis=1)\nemotions = em_words[['joy', 'sadness', 'fear', 'anger', 'trust', 'disgust',\n 'surprise', 'anticipation']]\nem_words[emotions.columns] = em_words[emotions.columns].apply(pd.to_numeric)\naffected = em_words[emotions.columns].groupby([em_words['word']], sort=False\n ).mean().reset_index()\nprint(\"training the word2vec model from google's corpus\")\nmodel = gensim.models.Word2Vec.load_word2vec_format(\n '../GoogleNews-vectors-negative300.bin', binary=True)\nidx_to_drop = []\n\n\ndef dropper():\n for ex in affected['word']:\n if ex not in model.vocab:\n idx_to_drop.append(affected.loc[affected.word == ex].index[0])\n\n\ndropper()\naffected = affected.drop(idx_to_drop, axis=0)\nG_vectors = lambda x: model[x]\naffected['word_vectors'] = affected['word'].apply(G_vectors)\naffected['label_vectors'] = affected[emotions.columns].values.tolist()\naffected['binary'] = (affected[emotions.columns] > 0).astype(int\n ).values.tolist()\ndf1 = affected[emotions.columns].rank(method='max', axis=1).rank(method=\n 'first', axis=1)\nma = df1.max().max()\naffected['label'] = (df1 == ma).astype(int).values.tolist()\naffected['target'] = affected['label'].apply(lambda x: x.index(1))\nlabel_dict = {(0): 'joy', (1): 'sadness', (2): 'fear', (3): 'anger', (4):\n 'trust', (5): 'disgust', (6): 'surprise', (7): 'anticipation'}\naffected['label_name'] = affected['target'].apply(lambda x: label_dict[x])\nemo2vec = affected[['word_vectors', 'label_vectors', 'binary', 'label',\n 'target', 'label_name']]\nprint('splitting into train/test groups...')\nemo_X, emo_y = list(emo2vec.word_vectors), list(emo2vec.target)\nemo_X_train, emo_X_test, emo_y_train, emo_y_test = train_test_split(emo_X,\n emo_y, random_state=42)\nprint(\"creating a model with the best stuff we've got...\")\nOVR = OneVsRestClassifier(LinearSVC(random_state=0), n_jobs=-1)\nemo_model = OVR.fit(emo_X_train, emo_y_train)\n",
"step-5": "\n# coding: utf-8\n\"\"\"Supporting model logic for predicting emotional content of user input.\n\"\"\"\nimport pandas as pd\nimport gensim\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.svm import LinearSVC\n\n#load data for emo2vec\nloc = 'https://s3-us-west-1.amazonaws.com/victorsdatasets/NRCEmotionLexiconv092AnnotatorandSenseLevel.txt'\nprint(\"loading & cleaning the data...\")\nem_words = pd.read_csv(loc, sep='\\t', names=['annotator_id',\n 'remove',\n 'word',\n 'joy',\n 'sadness',\n 'fear',\n 'anger',\n 'trust',\n 'disgust',\n 'surprise',\n 'anticipation',\n 'POS'])\n\nem_words.drop('remove', axis=1, inplace=True)\n\nem_words['word'], em_words['synonym'] = em_words['word'].str.split('--').str\n\nem_words['toss1'], em_words['joy'] = em_words['joy'].str.split('-').str\nem_words['toss2'], em_words['sadness'] = em_words['sadness'].str.split('-').str\nem_words['toss3'], em_words['fear'] = em_words['fear'].str.split('-').str\nem_words['toss4'], em_words['anger'] = em_words['anger'].str.split('-').str\nem_words['toss5'], em_words['trust'] = em_words['trust'].str.split('-').str\nem_words['toss6'], em_words['disgust'] = em_words['disgust'].str.split('-').str\nem_words['toss7'], em_words['surprise'] = em_words['surprise'].str.split('-').str\nem_words['toss8'], em_words['anticipation'] = em_words['anticipation'].str.split('-').str\nem_words['toss9'], em_words['POS'] = em_words['POS'].str.split('-').str\n\nem_words.drop(['toss1','toss2','toss3','toss4','toss5','toss6','toss7','toss8','toss9'],\n axis=1,\n inplace=True)\n\nnew_cols = ['annotator_id',\n 'word','synonym',\n 'joy',\n 'sadness',\n 'fear',\n 'anger',\n 'trust',\n 'disgust',\n 'surprise',\n 'anticipation',\n 'POS']\nem_words = em_words.reindex_axis(new_cols, axis=1)\n\nemotions = em_words[['joy',\n 'sadness',\n 'fear',\n 'anger',\n 'trust',\n 'disgust',\n 'surprise',\n 'anticipation']]\n\nem_words[emotions.columns] = em_words[emotions.columns].apply(pd.to_numeric)\n\naffected = em_words[emotions.columns].groupby([em_words['word']], sort=False).mean().reset_index()\n\n# Load Google's pre-trained Word2Vec model.\nprint('training the word2vec model from google\\'s corpus')\nmodel = gensim.models.Word2Vec.load_word2vec_format('../GoogleNews-vectors-negative300.bin', binary=True)\n\n# create list of word indicies to drop to avoid keyerrors with Google's pre-trained model.\nidx_to_drop = []\ndef dropper():\n for ex in affected['word']:\n if ex not in model.vocab:\n idx_to_drop.append(affected.loc[affected.word == ex].index[0])\n\n# drop words from affected that are not in google's model\ndropper()\naffected = affected.drop(idx_to_drop, axis=0)\n\nG_vectors = lambda x: model[x]\naffected['word_vectors'] = affected['word'].apply(G_vectors)\n\naffected['label_vectors'] = affected[emotions.columns].values.tolist()\n\naffected['binary'] = (affected[emotions.columns] > 0).astype(int).values.tolist()\n\ndf1 = affected[emotions.columns].rank(method='max', axis=1).rank(method='first', axis=1)\nma = df1.max().max()\naffected['label'] = (df1== ma).astype(int).values.tolist()\naffected['target'] = affected['label'].apply(lambda x: x.index(1))\nlabel_dict = {0 : 'joy',\n 1 : 'sadness',\n 2 : 'fear',\n 3 : 'anger',\n 4 : 'trust',\n 5 : 'disgust',\n 6 : 'surprise',\n 7 : 'anticipation'}\n\naffected['label_name'] = affected['target'].apply(lambda x: label_dict[x])\n\nemo2vec = affected[['word_vectors', 'label_vectors', 'binary', 'label', 'target', 'label_name']]\n\n# # Model Testing\nprint(\"splitting into train/test groups...\")\nemo_X, emo_y = list(emo2vec.word_vectors), list(emo2vec.target)\nemo_X_train, emo_X_test, emo_y_train, emo_y_test = train_test_split(emo_X, emo_y, random_state=42)\n\n\n# ### OnevsRest with LinearSVC (best score)\n\nprint(\"creating a model with the best stuff we've got...\")\nOVR = OneVsRestClassifier(LinearSVC(random_state=0), n_jobs=-1)\nemo_model = OVR.fit(emo_X_train, emo_y_train)\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
<|reserved_special_token_0|>
def inception(image, reuse):
preprocessed = tf.multiply(tf.subtract(tf.expand_dims(image, 0), 0.5), 2.0)
arg_scope = nets.inception.inception_v3_arg_scope(weight_decay=0.0)
with slim.arg_scope(arg_scope):
logits, end_point = nets.inception.inception_v3(preprocessed, 1001,
is_training=False, reuse=reuse)
logits = logits[:, 1:]
probs = tf.nn.softmax(logits)
return logits, probs, end_point
<|reserved_special_token_0|>
def classify(img, correct_class=None, target_class=None):
p = sess.run(probs, feed_dict={image: img})[0]
return np.argmax(p)
<|reserved_special_token_0|>
def grad_cam(x, class_num):
output, grads_val = sess.run([conv_layer, norm_grads], feed_dict={image:
x, pre_calss: class_num})
output = output[0]
grads_val = grads_val[0]
weights = np.mean(grads_val, axis=(0, 1))
cam = np.ones(output.shape[0:2], dtype=np.float32)
for i, w in enumerate(weights):
cam += w * output[:, :, i]
""""""
cam = np.maximum(cam, 0)
cam = cam / np.max(cam)
cam3 = cv2.resize(cam, (299, 299))
return cam3
def get_gard_cam(img_path, img_class):
demo_epsilon = 2.0 / 255.0
demo_lr = 0.1
demo_steps = 100
img = PIL.Image.open(img_path).convert('RGB')
big_dim = max(img.width, img.height)
wide = img.width > img.height
new_w = 299 if not wide else int(img.width * 299 / img.height)
new_h = 299 if wide else int(img.height * 299 / img.width)
img = img.resize((new_w, new_h)).crop((0, 0, 299, 299))
img = (np.asarray(img) / 255.0).astype(np.float32)
rar_gard_cam = grad_cam(img, img_class)
""""""
return img, rar_gard_cam
def show_img(file_name, img, rar, adv):
plt.figure()
plt.subplot(1, 3, 1)
plt.imshow(img)
plt.subplot(1, 3, 2)
img = cv2.resize(img, (299, 299))
img = img.astype(float)
img /= img.max()
rar = cv2.applyColorMap(np.uint8(255 * rar), cv2.COLORMAP_JET)
rar = cv2.cvtColor(rar, cv2.COLOR_BGR2RGB)
alpha = 0.0072
rar = img + alpha * rar
rar /= rar.max()
plt.imshow(rar)
plt.subplot(1, 3, 3)
adv = cv2.applyColorMap(np.uint8(255 * adv), cv2.COLORMAP_JET)
adv = cv2.cvtColor(adv, cv2.COLOR_BGR2RGB)
alpha = 0.0072
adv = img + alpha * adv
adv /= adv.max()
plt.imshow(adv)
plt.savefig(file_name)
plt.close()
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def inception(image, reuse):
preprocessed = tf.multiply(tf.subtract(tf.expand_dims(image, 0), 0.5), 2.0)
arg_scope = nets.inception.inception_v3_arg_scope(weight_decay=0.0)
with slim.arg_scope(arg_scope):
logits, end_point = nets.inception.inception_v3(preprocessed, 1001,
is_training=False, reuse=reuse)
logits = logits[:, 1:]
probs = tf.nn.softmax(logits)
return logits, probs, end_point
<|reserved_special_token_0|>
def classify(img, correct_class=None, target_class=None):
p = sess.run(probs, feed_dict={image: img})[0]
return np.argmax(p)
<|reserved_special_token_0|>
def grad_cam(x, class_num):
output, grads_val = sess.run([conv_layer, norm_grads], feed_dict={image:
x, pre_calss: class_num})
output = output[0]
grads_val = grads_val[0]
weights = np.mean(grads_val, axis=(0, 1))
cam = np.ones(output.shape[0:2], dtype=np.float32)
for i, w in enumerate(weights):
cam += w * output[:, :, i]
""""""
cam = np.maximum(cam, 0)
cam = cam / np.max(cam)
cam3 = cv2.resize(cam, (299, 299))
return cam3
def get_gard_cam(img_path, img_class):
demo_epsilon = 2.0 / 255.0
demo_lr = 0.1
demo_steps = 100
img = PIL.Image.open(img_path).convert('RGB')
big_dim = max(img.width, img.height)
wide = img.width > img.height
new_w = 299 if not wide else int(img.width * 299 / img.height)
new_h = 299 if wide else int(img.height * 299 / img.width)
img = img.resize((new_w, new_h)).crop((0, 0, 299, 299))
img = (np.asarray(img) / 255.0).astype(np.float32)
rar_gard_cam = grad_cam(img, img_class)
""""""
return img, rar_gard_cam
def show_img(file_name, img, rar, adv):
plt.figure()
plt.subplot(1, 3, 1)
plt.imshow(img)
plt.subplot(1, 3, 2)
img = cv2.resize(img, (299, 299))
img = img.astype(float)
img /= img.max()
rar = cv2.applyColorMap(np.uint8(255 * rar), cv2.COLORMAP_JET)
rar = cv2.cvtColor(rar, cv2.COLOR_BGR2RGB)
alpha = 0.0072
rar = img + alpha * rar
rar /= rar.max()
plt.imshow(rar)
plt.subplot(1, 3, 3)
adv = cv2.applyColorMap(np.uint8(255 * adv), cv2.COLORMAP_JET)
adv = cv2.cvtColor(adv, cv2.COLOR_BGR2RGB)
alpha = 0.0072
adv = img + alpha * adv
adv /= adv.max()
plt.imshow(adv)
plt.savefig(file_name)
plt.close()
<|reserved_special_token_0|>
def get_label_name(index):
with open('imagenet_labels.txt', 'r', encoding='utf8') as f:
data = f.read(index + 1)
return data
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def inception(image, reuse):
preprocessed = tf.multiply(tf.subtract(tf.expand_dims(image, 0), 0.5), 2.0)
arg_scope = nets.inception.inception_v3_arg_scope(weight_decay=0.0)
with slim.arg_scope(arg_scope):
logits, end_point = nets.inception.inception_v3(preprocessed, 1001,
is_training=False, reuse=reuse)
logits = logits[:, 1:]
probs = tf.nn.softmax(logits)
return logits, probs, end_point
<|reserved_special_token_0|>
saver.restore(sess, 'inception_v3.ckpt')
<|reserved_special_token_0|>
with open(imagenet_json) as f:
imagenet_labels = json.load(f)
def classify(img, correct_class=None, target_class=None):
p = sess.run(probs, feed_dict={image: img})[0]
return np.argmax(p)
<|reserved_special_token_0|>
def grad_cam(x, class_num):
output, grads_val = sess.run([conv_layer, norm_grads], feed_dict={image:
x, pre_calss: class_num})
output = output[0]
grads_val = grads_val[0]
weights = np.mean(grads_val, axis=(0, 1))
cam = np.ones(output.shape[0:2], dtype=np.float32)
for i, w in enumerate(weights):
cam += w * output[:, :, i]
""""""
cam = np.maximum(cam, 0)
cam = cam / np.max(cam)
cam3 = cv2.resize(cam, (299, 299))
return cam3
def get_gard_cam(img_path, img_class):
demo_epsilon = 2.0 / 255.0
demo_lr = 0.1
demo_steps = 100
img = PIL.Image.open(img_path).convert('RGB')
big_dim = max(img.width, img.height)
wide = img.width > img.height
new_w = 299 if not wide else int(img.width * 299 / img.height)
new_h = 299 if wide else int(img.height * 299 / img.width)
img = img.resize((new_w, new_h)).crop((0, 0, 299, 299))
img = (np.asarray(img) / 255.0).astype(np.float32)
rar_gard_cam = grad_cam(img, img_class)
""""""
return img, rar_gard_cam
def show_img(file_name, img, rar, adv):
plt.figure()
plt.subplot(1, 3, 1)
plt.imshow(img)
plt.subplot(1, 3, 2)
img = cv2.resize(img, (299, 299))
img = img.astype(float)
img /= img.max()
rar = cv2.applyColorMap(np.uint8(255 * rar), cv2.COLORMAP_JET)
rar = cv2.cvtColor(rar, cv2.COLOR_BGR2RGB)
alpha = 0.0072
rar = img + alpha * rar
rar /= rar.max()
plt.imshow(rar)
plt.subplot(1, 3, 3)
adv = cv2.applyColorMap(np.uint8(255 * adv), cv2.COLORMAP_JET)
adv = cv2.cvtColor(adv, cv2.COLOR_BGR2RGB)
alpha = 0.0072
adv = img + alpha * adv
adv /= adv.max()
plt.imshow(adv)
plt.savefig(file_name)
plt.close()
sess.graph.finalize()
def get_label_name(index):
with open('imagenet_labels.txt', 'r', encoding='utf8') as f:
data = f.read(index + 1)
return data
if __name__ == '__main__':
print(get_label_name(0))
<|reserved_special_token_1|>
import os
import random
import cv2
import tensorflow as tf
import tensorflow.contrib.slim as slim
import tensorflow.contrib.slim.nets as nets
from skimage.transform import resize
import PIL
import numpy as np
import json
import matplotlib.pyplot as plt
sess = tf.InteractiveSession()
image = tf.Variable(tf.zeros((299, 299, 3)))
def inception(image, reuse):
preprocessed = tf.multiply(tf.subtract(tf.expand_dims(image, 0), 0.5), 2.0)
arg_scope = nets.inception.inception_v3_arg_scope(weight_decay=0.0)
with slim.arg_scope(arg_scope):
logits, end_point = nets.inception.inception_v3(preprocessed, 1001,
is_training=False, reuse=reuse)
logits = logits[:, 1:]
probs = tf.nn.softmax(logits)
return logits, probs, end_point
logits, probs, end_point = inception(image, reuse=False)
restore_vars = [var for var in tf.global_variables() if var.name.startswith
('InceptionV3/')]
saver = tf.train.Saver(restore_vars)
saver.restore(sess, 'inception_v3.ckpt')
imagenet_json = 'imagenet.json'
with open(imagenet_json) as f:
imagenet_labels = json.load(f)
def classify(img, correct_class=None, target_class=None):
p = sess.run(probs, feed_dict={image: img})[0]
return np.argmax(p)
layer_name = 'Mixed_7c'
num_class = 1000
conv_layer = end_point[layer_name]
pre_calss = tf.placeholder(tf.int32)
one_hot = tf.sparse_to_dense(pre_calss, [num_class], 1.0)
signal = tf.multiply(end_point['Logits'][:, 1:], one_hot)
loss = tf.reduce_mean(signal)
grads = tf.gradients(loss, conv_layer)[0]
norm_grads = tf.div(grads, tf.sqrt(tf.reduce_mean(tf.square(grads))) + tf.
constant(1e-05))
def grad_cam(x, class_num):
output, grads_val = sess.run([conv_layer, norm_grads], feed_dict={image:
x, pre_calss: class_num})
output = output[0]
grads_val = grads_val[0]
weights = np.mean(grads_val, axis=(0, 1))
cam = np.ones(output.shape[0:2], dtype=np.float32)
for i, w in enumerate(weights):
cam += w * output[:, :, i]
""""""
cam = np.maximum(cam, 0)
cam = cam / np.max(cam)
cam3 = cv2.resize(cam, (299, 299))
return cam3
def get_gard_cam(img_path, img_class):
demo_epsilon = 2.0 / 255.0
demo_lr = 0.1
demo_steps = 100
img = PIL.Image.open(img_path).convert('RGB')
big_dim = max(img.width, img.height)
wide = img.width > img.height
new_w = 299 if not wide else int(img.width * 299 / img.height)
new_h = 299 if wide else int(img.height * 299 / img.width)
img = img.resize((new_w, new_h)).crop((0, 0, 299, 299))
img = (np.asarray(img) / 255.0).astype(np.float32)
rar_gard_cam = grad_cam(img, img_class)
""""""
return img, rar_gard_cam
def show_img(file_name, img, rar, adv):
plt.figure()
plt.subplot(1, 3, 1)
plt.imshow(img)
plt.subplot(1, 3, 2)
img = cv2.resize(img, (299, 299))
img = img.astype(float)
img /= img.max()
rar = cv2.applyColorMap(np.uint8(255 * rar), cv2.COLORMAP_JET)
rar = cv2.cvtColor(rar, cv2.COLOR_BGR2RGB)
alpha = 0.0072
rar = img + alpha * rar
rar /= rar.max()
plt.imshow(rar)
plt.subplot(1, 3, 3)
adv = cv2.applyColorMap(np.uint8(255 * adv), cv2.COLORMAP_JET)
adv = cv2.cvtColor(adv, cv2.COLOR_BGR2RGB)
alpha = 0.0072
adv = img + alpha * adv
adv /= adv.max()
plt.imshow(adv)
plt.savefig(file_name)
plt.close()
sess.graph.finalize()
def get_label_name(index):
with open('imagenet_labels.txt', 'r', encoding='utf8') as f:
data = f.read(index + 1)
return data
if __name__ == '__main__':
print(get_label_name(0))
<|reserved_special_token_1|>
import os
import random
import cv2
import tensorflow as tf
import tensorflow.contrib.slim as slim
import tensorflow.contrib.slim.nets as nets
from skimage.transform import resize
import PIL
import numpy as np
import json
# os.environ["CUDA_VISIBLE_DEVICES"] = "1"
import matplotlib.pyplot as plt
# plt.switch_backend('agg')
sess = tf.InteractiveSession()
image = tf.Variable(tf.zeros((299, 299, 3)))
# 加载inceptionV
def inception(image, reuse):
preprocessed = tf.multiply(tf.subtract(tf.expand_dims(image, 0), 0.5), 2.0)
arg_scope = nets.inception.inception_v3_arg_scope(weight_decay=0.0)
with slim.arg_scope(arg_scope):
logits, end_point = nets.inception.inception_v3(preprocessed, 1001, is_training=False, reuse=reuse)
logits = logits[:, 1:] # ignore background class
probs = tf.nn.softmax(logits) # probabilities
return logits, probs, end_point
logits, probs, end_point = inception(image, reuse=False)
restore_vars = [
var for var in tf.global_variables()
if var.name.startswith('InceptionV3/')
]
saver = tf.train.Saver(restore_vars)
saver.restore(sess, "inception_v3.ckpt")
imagenet_json = 'imagenet.json'
with open(imagenet_json) as f:
imagenet_labels = json.load(f)
# 打印进攻前的图片
def classify(img, correct_class=None, target_class=None):
p = sess.run(probs, feed_dict={image: img})[0]
return np.argmax(p)
# TODO
# 重要代码,获取激活分布8*8
layer_name='Mixed_7c'
num_class=1000
conv_layer = end_point[layer_name]
pre_calss = tf.placeholder(tf.int32)
one_hot = tf.sparse_to_dense(pre_calss, [num_class], 1.0)
signal = tf.multiply(end_point['Logits'][:, 1:], one_hot)
loss = tf.reduce_mean(signal)
grads = tf.gradients(loss, conv_layer)[0]
norm_grads = tf.div(grads, tf.sqrt(tf.reduce_mean(tf.square(grads))) + tf.constant(1e-5))
def grad_cam(x, class_num):
output, grads_val = sess.run([conv_layer, norm_grads], feed_dict={image: x, pre_calss: class_num})
output = output[0]
grads_val = grads_val[0]
weights = np.mean(grads_val, axis=(0, 1)) # [512]
cam = np.ones(output.shape[0: 2], dtype=np.float32) # [7,7]
# Taking a weighted average
for i, w in enumerate(weights):
cam += w * output[:, :, i]
# Passing through ReLU
""""""
# cam=np.exp(cam) / np.sum(np.exp(cam), axis=0)
# cam=cam/np.max(cam)
# cam3 = np.expand_dims(cam, axis=2)
# cam3 = np.tile(cam3, [1, 1, 3])
cam = np.maximum(cam, 0)
cam = cam / np.max(cam)
cam3 = cv2.resize(cam, (299, 299))
# cam3=np.expand_dims(cam,axis=2)
# cam=np.tile(cam3,[1,1,3])
# cam = resize(cam, (299, 299,3))
return cam3
def get_gard_cam(img_path, img_class):
demo_epsilon = 2.0 / 255.0
demo_lr = 0.1
demo_steps = 100
img = PIL.Image.open(img_path).convert('RGB')
big_dim = max(img.width, img.height)
wide = img.width > img.height
new_w = 299 if not wide else int(img.width * 299 / img.height)
new_h = 299 if wide else int(img.height * 299 / img.width)
img = img.resize((new_w, new_h)).crop((0, 0, 299, 299))
img = (np.asarray(img) / 255.0).astype(np.float32)
# 展示原分类图
# 获取原图激活区域
rar_gard_cam = grad_cam(img, img_class)
# 显示被进攻后和的激活区域
""""""
# 展示攻击后的图像
# 展示攻击后的图像的激活区域
return img, rar_gard_cam
def show_img(file_name,img,rar,adv):
plt.figure()
plt.subplot(1, 3, 1)
plt.imshow(img)
plt.subplot(1, 3, 2)
img = cv2.resize(img, (299, 299))
img = img.astype(float)
img /= img.max()
rar = cv2.applyColorMap(np.uint8(255 * rar), cv2.COLORMAP_JET)
rar = cv2.cvtColor(rar, cv2.COLOR_BGR2RGB)
alpha = 0.0072
rar = img + alpha * rar
rar /= rar.max()
# Display and save
plt.imshow(rar)
plt.subplot(1, 3, 3)
adv = cv2.applyColorMap(np.uint8(255 * adv), cv2.COLORMAP_JET)
adv = cv2.cvtColor(adv, cv2.COLOR_BGR2RGB)
alpha = 0.0072
adv = img + alpha * adv
adv /= adv.max()
plt.imshow(adv)
plt.savefig(file_name)
plt.close()
sess.graph.finalize()
def get_label_name(index):
with open('imagenet_labels.txt','r',encoding='utf8')as f:
data=f.read(index+1)
return data
if __name__ == '__main__':
print(get_label_name(0))
# for r,d,f in os.walk('img_val/n01440764'):
# for file in f:
# imgs=[]
# labels_file = 'imagenet_labels.txt'
# results_file = 'result.txt'
# print('img_val/n01440764/'+file)
# img, cam3 = get_gard_cam('img_val/n01440764/'+file, 0)
# show_img(img,cam3,cam3)
|
flexible
|
{
"blob_id": "31d87b11f6a1f6304a2fef6dd1cd1c0ca292dfe8",
"index": 3491,
"step-1": "<mask token>\n\n\ndef inception(image, reuse):\n preprocessed = tf.multiply(tf.subtract(tf.expand_dims(image, 0), 0.5), 2.0)\n arg_scope = nets.inception.inception_v3_arg_scope(weight_decay=0.0)\n with slim.arg_scope(arg_scope):\n logits, end_point = nets.inception.inception_v3(preprocessed, 1001,\n is_training=False, reuse=reuse)\n logits = logits[:, 1:]\n probs = tf.nn.softmax(logits)\n return logits, probs, end_point\n\n\n<mask token>\n\n\ndef classify(img, correct_class=None, target_class=None):\n p = sess.run(probs, feed_dict={image: img})[0]\n return np.argmax(p)\n\n\n<mask token>\n\n\ndef grad_cam(x, class_num):\n output, grads_val = sess.run([conv_layer, norm_grads], feed_dict={image:\n x, pre_calss: class_num})\n output = output[0]\n grads_val = grads_val[0]\n weights = np.mean(grads_val, axis=(0, 1))\n cam = np.ones(output.shape[0:2], dtype=np.float32)\n for i, w in enumerate(weights):\n cam += w * output[:, :, i]\n \"\"\"\"\"\"\n cam = np.maximum(cam, 0)\n cam = cam / np.max(cam)\n cam3 = cv2.resize(cam, (299, 299))\n return cam3\n\n\ndef get_gard_cam(img_path, img_class):\n demo_epsilon = 2.0 / 255.0\n demo_lr = 0.1\n demo_steps = 100\n img = PIL.Image.open(img_path).convert('RGB')\n big_dim = max(img.width, img.height)\n wide = img.width > img.height\n new_w = 299 if not wide else int(img.width * 299 / img.height)\n new_h = 299 if wide else int(img.height * 299 / img.width)\n img = img.resize((new_w, new_h)).crop((0, 0, 299, 299))\n img = (np.asarray(img) / 255.0).astype(np.float32)\n rar_gard_cam = grad_cam(img, img_class)\n \"\"\"\"\"\"\n return img, rar_gard_cam\n\n\ndef show_img(file_name, img, rar, adv):\n plt.figure()\n plt.subplot(1, 3, 1)\n plt.imshow(img)\n plt.subplot(1, 3, 2)\n img = cv2.resize(img, (299, 299))\n img = img.astype(float)\n img /= img.max()\n rar = cv2.applyColorMap(np.uint8(255 * rar), cv2.COLORMAP_JET)\n rar = cv2.cvtColor(rar, cv2.COLOR_BGR2RGB)\n alpha = 0.0072\n rar = img + alpha * rar\n rar /= rar.max()\n plt.imshow(rar)\n plt.subplot(1, 3, 3)\n adv = cv2.applyColorMap(np.uint8(255 * adv), cv2.COLORMAP_JET)\n adv = cv2.cvtColor(adv, cv2.COLOR_BGR2RGB)\n alpha = 0.0072\n adv = img + alpha * adv\n adv /= adv.max()\n plt.imshow(adv)\n plt.savefig(file_name)\n plt.close()\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef inception(image, reuse):\n preprocessed = tf.multiply(tf.subtract(tf.expand_dims(image, 0), 0.5), 2.0)\n arg_scope = nets.inception.inception_v3_arg_scope(weight_decay=0.0)\n with slim.arg_scope(arg_scope):\n logits, end_point = nets.inception.inception_v3(preprocessed, 1001,\n is_training=False, reuse=reuse)\n logits = logits[:, 1:]\n probs = tf.nn.softmax(logits)\n return logits, probs, end_point\n\n\n<mask token>\n\n\ndef classify(img, correct_class=None, target_class=None):\n p = sess.run(probs, feed_dict={image: img})[0]\n return np.argmax(p)\n\n\n<mask token>\n\n\ndef grad_cam(x, class_num):\n output, grads_val = sess.run([conv_layer, norm_grads], feed_dict={image:\n x, pre_calss: class_num})\n output = output[0]\n grads_val = grads_val[0]\n weights = np.mean(grads_val, axis=(0, 1))\n cam = np.ones(output.shape[0:2], dtype=np.float32)\n for i, w in enumerate(weights):\n cam += w * output[:, :, i]\n \"\"\"\"\"\"\n cam = np.maximum(cam, 0)\n cam = cam / np.max(cam)\n cam3 = cv2.resize(cam, (299, 299))\n return cam3\n\n\ndef get_gard_cam(img_path, img_class):\n demo_epsilon = 2.0 / 255.0\n demo_lr = 0.1\n demo_steps = 100\n img = PIL.Image.open(img_path).convert('RGB')\n big_dim = max(img.width, img.height)\n wide = img.width > img.height\n new_w = 299 if not wide else int(img.width * 299 / img.height)\n new_h = 299 if wide else int(img.height * 299 / img.width)\n img = img.resize((new_w, new_h)).crop((0, 0, 299, 299))\n img = (np.asarray(img) / 255.0).astype(np.float32)\n rar_gard_cam = grad_cam(img, img_class)\n \"\"\"\"\"\"\n return img, rar_gard_cam\n\n\ndef show_img(file_name, img, rar, adv):\n plt.figure()\n plt.subplot(1, 3, 1)\n plt.imshow(img)\n plt.subplot(1, 3, 2)\n img = cv2.resize(img, (299, 299))\n img = img.astype(float)\n img /= img.max()\n rar = cv2.applyColorMap(np.uint8(255 * rar), cv2.COLORMAP_JET)\n rar = cv2.cvtColor(rar, cv2.COLOR_BGR2RGB)\n alpha = 0.0072\n rar = img + alpha * rar\n rar /= rar.max()\n plt.imshow(rar)\n plt.subplot(1, 3, 3)\n adv = cv2.applyColorMap(np.uint8(255 * adv), cv2.COLORMAP_JET)\n adv = cv2.cvtColor(adv, cv2.COLOR_BGR2RGB)\n alpha = 0.0072\n adv = img + alpha * adv\n adv /= adv.max()\n plt.imshow(adv)\n plt.savefig(file_name)\n plt.close()\n\n\n<mask token>\n\n\ndef get_label_name(index):\n with open('imagenet_labels.txt', 'r', encoding='utf8') as f:\n data = f.read(index + 1)\n return data\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef inception(image, reuse):\n preprocessed = tf.multiply(tf.subtract(tf.expand_dims(image, 0), 0.5), 2.0)\n arg_scope = nets.inception.inception_v3_arg_scope(weight_decay=0.0)\n with slim.arg_scope(arg_scope):\n logits, end_point = nets.inception.inception_v3(preprocessed, 1001,\n is_training=False, reuse=reuse)\n logits = logits[:, 1:]\n probs = tf.nn.softmax(logits)\n return logits, probs, end_point\n\n\n<mask token>\nsaver.restore(sess, 'inception_v3.ckpt')\n<mask token>\nwith open(imagenet_json) as f:\n imagenet_labels = json.load(f)\n\n\ndef classify(img, correct_class=None, target_class=None):\n p = sess.run(probs, feed_dict={image: img})[0]\n return np.argmax(p)\n\n\n<mask token>\n\n\ndef grad_cam(x, class_num):\n output, grads_val = sess.run([conv_layer, norm_grads], feed_dict={image:\n x, pre_calss: class_num})\n output = output[0]\n grads_val = grads_val[0]\n weights = np.mean(grads_val, axis=(0, 1))\n cam = np.ones(output.shape[0:2], dtype=np.float32)\n for i, w in enumerate(weights):\n cam += w * output[:, :, i]\n \"\"\"\"\"\"\n cam = np.maximum(cam, 0)\n cam = cam / np.max(cam)\n cam3 = cv2.resize(cam, (299, 299))\n return cam3\n\n\ndef get_gard_cam(img_path, img_class):\n demo_epsilon = 2.0 / 255.0\n demo_lr = 0.1\n demo_steps = 100\n img = PIL.Image.open(img_path).convert('RGB')\n big_dim = max(img.width, img.height)\n wide = img.width > img.height\n new_w = 299 if not wide else int(img.width * 299 / img.height)\n new_h = 299 if wide else int(img.height * 299 / img.width)\n img = img.resize((new_w, new_h)).crop((0, 0, 299, 299))\n img = (np.asarray(img) / 255.0).astype(np.float32)\n rar_gard_cam = grad_cam(img, img_class)\n \"\"\"\"\"\"\n return img, rar_gard_cam\n\n\ndef show_img(file_name, img, rar, adv):\n plt.figure()\n plt.subplot(1, 3, 1)\n plt.imshow(img)\n plt.subplot(1, 3, 2)\n img = cv2.resize(img, (299, 299))\n img = img.astype(float)\n img /= img.max()\n rar = cv2.applyColorMap(np.uint8(255 * rar), cv2.COLORMAP_JET)\n rar = cv2.cvtColor(rar, cv2.COLOR_BGR2RGB)\n alpha = 0.0072\n rar = img + alpha * rar\n rar /= rar.max()\n plt.imshow(rar)\n plt.subplot(1, 3, 3)\n adv = cv2.applyColorMap(np.uint8(255 * adv), cv2.COLORMAP_JET)\n adv = cv2.cvtColor(adv, cv2.COLOR_BGR2RGB)\n alpha = 0.0072\n adv = img + alpha * adv\n adv /= adv.max()\n plt.imshow(adv)\n plt.savefig(file_name)\n plt.close()\n\n\nsess.graph.finalize()\n\n\ndef get_label_name(index):\n with open('imagenet_labels.txt', 'r', encoding='utf8') as f:\n data = f.read(index + 1)\n return data\n\n\nif __name__ == '__main__':\n print(get_label_name(0))\n",
"step-4": "import os\nimport random\nimport cv2\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\nimport tensorflow.contrib.slim.nets as nets\nfrom skimage.transform import resize\nimport PIL\nimport numpy as np\nimport json\nimport matplotlib.pyplot as plt\nsess = tf.InteractiveSession()\nimage = tf.Variable(tf.zeros((299, 299, 3)))\n\n\ndef inception(image, reuse):\n preprocessed = tf.multiply(tf.subtract(tf.expand_dims(image, 0), 0.5), 2.0)\n arg_scope = nets.inception.inception_v3_arg_scope(weight_decay=0.0)\n with slim.arg_scope(arg_scope):\n logits, end_point = nets.inception.inception_v3(preprocessed, 1001,\n is_training=False, reuse=reuse)\n logits = logits[:, 1:]\n probs = tf.nn.softmax(logits)\n return logits, probs, end_point\n\n\nlogits, probs, end_point = inception(image, reuse=False)\nrestore_vars = [var for var in tf.global_variables() if var.name.startswith\n ('InceptionV3/')]\nsaver = tf.train.Saver(restore_vars)\nsaver.restore(sess, 'inception_v3.ckpt')\nimagenet_json = 'imagenet.json'\nwith open(imagenet_json) as f:\n imagenet_labels = json.load(f)\n\n\ndef classify(img, correct_class=None, target_class=None):\n p = sess.run(probs, feed_dict={image: img})[0]\n return np.argmax(p)\n\n\nlayer_name = 'Mixed_7c'\nnum_class = 1000\nconv_layer = end_point[layer_name]\npre_calss = tf.placeholder(tf.int32)\none_hot = tf.sparse_to_dense(pre_calss, [num_class], 1.0)\nsignal = tf.multiply(end_point['Logits'][:, 1:], one_hot)\nloss = tf.reduce_mean(signal)\ngrads = tf.gradients(loss, conv_layer)[0]\nnorm_grads = tf.div(grads, tf.sqrt(tf.reduce_mean(tf.square(grads))) + tf.\n constant(1e-05))\n\n\ndef grad_cam(x, class_num):\n output, grads_val = sess.run([conv_layer, norm_grads], feed_dict={image:\n x, pre_calss: class_num})\n output = output[0]\n grads_val = grads_val[0]\n weights = np.mean(grads_val, axis=(0, 1))\n cam = np.ones(output.shape[0:2], dtype=np.float32)\n for i, w in enumerate(weights):\n cam += w * output[:, :, i]\n \"\"\"\"\"\"\n cam = np.maximum(cam, 0)\n cam = cam / np.max(cam)\n cam3 = cv2.resize(cam, (299, 299))\n return cam3\n\n\ndef get_gard_cam(img_path, img_class):\n demo_epsilon = 2.0 / 255.0\n demo_lr = 0.1\n demo_steps = 100\n img = PIL.Image.open(img_path).convert('RGB')\n big_dim = max(img.width, img.height)\n wide = img.width > img.height\n new_w = 299 if not wide else int(img.width * 299 / img.height)\n new_h = 299 if wide else int(img.height * 299 / img.width)\n img = img.resize((new_w, new_h)).crop((0, 0, 299, 299))\n img = (np.asarray(img) / 255.0).astype(np.float32)\n rar_gard_cam = grad_cam(img, img_class)\n \"\"\"\"\"\"\n return img, rar_gard_cam\n\n\ndef show_img(file_name, img, rar, adv):\n plt.figure()\n plt.subplot(1, 3, 1)\n plt.imshow(img)\n plt.subplot(1, 3, 2)\n img = cv2.resize(img, (299, 299))\n img = img.astype(float)\n img /= img.max()\n rar = cv2.applyColorMap(np.uint8(255 * rar), cv2.COLORMAP_JET)\n rar = cv2.cvtColor(rar, cv2.COLOR_BGR2RGB)\n alpha = 0.0072\n rar = img + alpha * rar\n rar /= rar.max()\n plt.imshow(rar)\n plt.subplot(1, 3, 3)\n adv = cv2.applyColorMap(np.uint8(255 * adv), cv2.COLORMAP_JET)\n adv = cv2.cvtColor(adv, cv2.COLOR_BGR2RGB)\n alpha = 0.0072\n adv = img + alpha * adv\n adv /= adv.max()\n plt.imshow(adv)\n plt.savefig(file_name)\n plt.close()\n\n\nsess.graph.finalize()\n\n\ndef get_label_name(index):\n with open('imagenet_labels.txt', 'r', encoding='utf8') as f:\n data = f.read(index + 1)\n return data\n\n\nif __name__ == '__main__':\n print(get_label_name(0))\n",
"step-5": "import os\nimport random\n\nimport cv2\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\nimport tensorflow.contrib.slim.nets as nets\nfrom skimage.transform import resize\nimport PIL\nimport numpy as np\nimport json\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\nimport matplotlib.pyplot as plt\n\n# plt.switch_backend('agg')\n\n\nsess = tf.InteractiveSession()\nimage = tf.Variable(tf.zeros((299, 299, 3)))\n\n\n\n# 加载inceptionV\ndef inception(image, reuse):\n preprocessed = tf.multiply(tf.subtract(tf.expand_dims(image, 0), 0.5), 2.0)\n arg_scope = nets.inception.inception_v3_arg_scope(weight_decay=0.0)\n with slim.arg_scope(arg_scope):\n logits, end_point = nets.inception.inception_v3(preprocessed, 1001, is_training=False, reuse=reuse)\n logits = logits[:, 1:] # ignore background class\n probs = tf.nn.softmax(logits) # probabilities\n return logits, probs, end_point\n\n\nlogits, probs, end_point = inception(image, reuse=False)\n\nrestore_vars = [\n var for var in tf.global_variables()\n if var.name.startswith('InceptionV3/')\n]\nsaver = tf.train.Saver(restore_vars)\nsaver.restore(sess, \"inception_v3.ckpt\")\n\nimagenet_json = 'imagenet.json'\nwith open(imagenet_json) as f:\n imagenet_labels = json.load(f)\n\n\n# 打印进攻前的图片\ndef classify(img, correct_class=None, target_class=None):\n p = sess.run(probs, feed_dict={image: img})[0]\n return np.argmax(p)\n\n\n# TODO\n# 重要代码,获取激活分布8*8\nlayer_name='Mixed_7c'\nnum_class=1000\nconv_layer = end_point[layer_name]\npre_calss = tf.placeholder(tf.int32)\none_hot = tf.sparse_to_dense(pre_calss, [num_class], 1.0)\nsignal = tf.multiply(end_point['Logits'][:, 1:], one_hot)\nloss = tf.reduce_mean(signal)\ngrads = tf.gradients(loss, conv_layer)[0]\nnorm_grads = tf.div(grads, tf.sqrt(tf.reduce_mean(tf.square(grads))) + tf.constant(1e-5))\n\ndef grad_cam(x, class_num):\n output, grads_val = sess.run([conv_layer, norm_grads], feed_dict={image: x, pre_calss: class_num})\n output = output[0]\n grads_val = grads_val[0]\n weights = np.mean(grads_val, axis=(0, 1)) # [512]\n cam = np.ones(output.shape[0: 2], dtype=np.float32) # [7,7]\n\n # Taking a weighted average\n for i, w in enumerate(weights):\n cam += w * output[:, :, i]\n\n # Passing through ReLU\n\n \"\"\"\"\"\"\n # cam=np.exp(cam) / np.sum(np.exp(cam), axis=0)\n # cam=cam/np.max(cam)\n # cam3 = np.expand_dims(cam, axis=2)\n # cam3 = np.tile(cam3, [1, 1, 3])\n\n cam = np.maximum(cam, 0)\n cam = cam / np.max(cam)\n cam3 = cv2.resize(cam, (299, 299))\n\n # cam3=np.expand_dims(cam,axis=2)\n # cam=np.tile(cam3,[1,1,3])\n # cam = resize(cam, (299, 299,3))\n\n\n return cam3\n\n\ndef get_gard_cam(img_path, img_class):\n demo_epsilon = 2.0 / 255.0\n demo_lr = 0.1\n demo_steps = 100\n img = PIL.Image.open(img_path).convert('RGB')\n big_dim = max(img.width, img.height)\n wide = img.width > img.height\n new_w = 299 if not wide else int(img.width * 299 / img.height)\n new_h = 299 if wide else int(img.height * 299 / img.width)\n img = img.resize((new_w, new_h)).crop((0, 0, 299, 299))\n img = (np.asarray(img) / 255.0).astype(np.float32)\n\n # 展示原分类图\n\n # 获取原图激活区域\n rar_gard_cam = grad_cam(img, img_class)\n\n # 显示被进攻后和的激活区域\n\n\n\n \"\"\"\"\"\"\n # 展示攻击后的图像\n # 展示攻击后的图像的激活区域\n\n return img, rar_gard_cam\n\ndef show_img(file_name,img,rar,adv):\n plt.figure()\n plt.subplot(1, 3, 1)\n plt.imshow(img)\n plt.subplot(1, 3, 2)\n img = cv2.resize(img, (299, 299))\n img = img.astype(float)\n img /= img.max()\n rar = cv2.applyColorMap(np.uint8(255 * rar), cv2.COLORMAP_JET)\n rar = cv2.cvtColor(rar, cv2.COLOR_BGR2RGB)\n alpha = 0.0072\n rar = img + alpha * rar\n rar /= rar.max()\n # Display and save\n plt.imshow(rar)\n plt.subplot(1, 3, 3)\n adv = cv2.applyColorMap(np.uint8(255 * adv), cv2.COLORMAP_JET)\n adv = cv2.cvtColor(adv, cv2.COLOR_BGR2RGB)\n alpha = 0.0072\n adv = img + alpha * adv\n adv /= adv.max()\n plt.imshow(adv)\n plt.savefig(file_name)\n plt.close()\nsess.graph.finalize()\ndef get_label_name(index):\n with open('imagenet_labels.txt','r',encoding='utf8')as f:\n data=f.read(index+1)\n return data\nif __name__ == '__main__':\n print(get_label_name(0))\n # for r,d,f in os.walk('img_val/n01440764'):\n # for file in f:\n # imgs=[]\n # labels_file = 'imagenet_labels.txt'\n # results_file = 'result.txt'\n # print('img_val/n01440764/'+file)\n # img, cam3 = get_gard_cam('img_val/n01440764/'+file, 0)\n # show_img(img,cam3,cam3)",
"step-ids": [
5,
6,
7,
9,
10
]
}
|
[
5,
6,
7,
9,
10
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
if __name__ == '__main__':
img_path = (pathlib.Path('..') / 'images' / 'tiger.jpg').resolve()
with Image.open(str(img_path)) as img:
print('IMAGE: {}'.format(str(img_path)))
print('Image is in {} format'.format(img.format))
print('Image size: width {} pixels, height {} pixels'.format(img.
size[0], img.size[1]))
print('Image color bands: {}'.format(img.mode))
img.show()
<|reserved_special_token_1|>
import pathlib
from PIL import Image
if __name__ == '__main__':
img_path = (pathlib.Path('..') / 'images' / 'tiger.jpg').resolve()
with Image.open(str(img_path)) as img:
print('IMAGE: {}'.format(str(img_path)))
print('Image is in {} format'.format(img.format))
print('Image size: width {} pixels, height {} pixels'.format(img.
size[0], img.size[1]))
print('Image color bands: {}'.format(img.mode))
img.show()
<|reserved_special_token_1|>
# -*- coding: utf-8 -*-
# !/usr/bin/env python3
import pathlib
from PIL import Image
if __name__ == '__main__':
img_path = (pathlib.Path('..') / 'images' / 'tiger.jpg').resolve()
# image load
with Image.open(str(img_path)) as img:
# image info
print('IMAGE: {}'.format(str(img_path)))
print('Image is in {} format'.format(img.format))
print('Image size: width {} pixels, height {} pixels'.format(img.size[0], img.size[1]))
print('Image color bands: {}'.format(img.mode))
# image display
img.show()
|
flexible
|
{
"blob_id": "05edbf3662936465eee8eee0824d1a0cca0df0e5",
"index": 4855,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif __name__ == '__main__':\n img_path = (pathlib.Path('..') / 'images' / 'tiger.jpg').resolve()\n with Image.open(str(img_path)) as img:\n print('IMAGE: {}'.format(str(img_path)))\n print('Image is in {} format'.format(img.format))\n print('Image size: width {} pixels, height {} pixels'.format(img.\n size[0], img.size[1]))\n print('Image color bands: {}'.format(img.mode))\n img.show()\n",
"step-3": "import pathlib\nfrom PIL import Image\nif __name__ == '__main__':\n img_path = (pathlib.Path('..') / 'images' / 'tiger.jpg').resolve()\n with Image.open(str(img_path)) as img:\n print('IMAGE: {}'.format(str(img_path)))\n print('Image is in {} format'.format(img.format))\n print('Image size: width {} pixels, height {} pixels'.format(img.\n size[0], img.size[1]))\n print('Image color bands: {}'.format(img.mode))\n img.show()\n",
"step-4": "# -*- coding: utf-8 -*-\n# !/usr/bin/env python3\n\nimport pathlib\nfrom PIL import Image\n\n\nif __name__ == '__main__':\n\n img_path = (pathlib.Path('..') / 'images' / 'tiger.jpg').resolve()\n\n # image load\n with Image.open(str(img_path)) as img:\n # image info\n print('IMAGE: {}'.format(str(img_path)))\n print('Image is in {} format'.format(img.format))\n print('Image size: width {} pixels, height {} pixels'.format(img.size[0], img.size[1]))\n print('Image color bands: {}'.format(img.mode))\n # image display\n img.show()\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
class CustomUsuarioViewSet(AccessViewSetMixin, mixins.CreateModelMixin,
mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def perform_update(self, serializer):
serializer.save(usuario_modificacao=self.request.user)
@swagger_auto_schema(method='patch', manual_parameters=[openapi.
Parameter('token', openapi.IN_QUERY, type=openapi.TYPE_STRING,
required=True)])
@transaction.atomic
@action(detail=True, methods=['patch'], serializer_class=
CustomUsuarioMudarPasswordAposResetSerializer)
def mudar_password_apos_reset(self, request, pk=None):
usuario = self.get_object()
try:
token = request.query_params['token']
except KeyError:
return Response({'status': 'Token não informado.'}, status=
status.HTTP_400_BAD_REQUEST)
try:
token_instance = usuario.password_reset_tokens.get(token=token)
except PasswordResetToken.DoesNotExist:
return Response({'status': 'Token inválido.'}, status=status.
HTTP_400_BAD_REQUEST)
serializer_token = PasswordResetTokenSerializer(token_instance,
data={'ativo': False}, partial=True)
if serializer_token.is_valid():
serializer_token.save()
else:
return Response(serializer_token.errors, status=status.
HTTP_400_BAD_REQUEST)
serializer_usuario = self.get_serializer(usuario, data=request.data,
partial=True)
if serializer_usuario.is_valid():
serializer_usuario.save()
return Response({'status': 'A nova senha foi registrada.'},
status=status.HTTP_200_OK)
return Response(serializer_usuario.errors, status=status.
HTTP_400_BAD_REQUEST)
<|reserved_special_token_0|>
<|reserved_special_token_0|>
@action(detail=True, methods=['patch'], serializer_class=
CustomUsuarioMudarGrupoSerializer)
def mudar_grupo(self, request, pk=None):
usuario = self.get_object()
serializer = self.get_serializer(usuario, data=request.data,
partial=True)
if serializer.is_valid():
serializer.save()
return Response({'status': 'O grupo foi alterado com sucesso.'},
status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
<|reserved_special_token_0|>
<|reserved_special_token_0|>
class GroupViewSet(AccessViewSetMixin, ReadOnlyModelViewSet):
"""
Group ViewSet description:
list: Listar grupos.
retrieve: Consultar grupos.
"""
access_policy = GroupAccessPolicy
serializer_class = GroupSerializer
def get_queryset(self):
return Group.objects.all().order_by('id')
class PasswordResetTokenViewSet(AccessViewSetMixin, mixins.CreateModelMixin,
mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet):
"""
Password Reset Token ViewSet description:
create: Criar token.
retrieve: Consultar token.
list: Listar tokens.
"""
access_policy = PasswordResetTokenAccessPolicy
serializer_class = PasswordResetTokenSerializer
def get_queryset(self):
return PasswordResetToken.objects.all().order_by('id')
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response({'status':
'Token criado. E-mail enviado ao usuário para criação de nova senha.'
}, status=status.HTTP_201_CREATED, headers=headers)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class CustomUsuarioViewSet(AccessViewSetMixin, mixins.CreateModelMixin,
mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def perform_update(self, serializer):
serializer.save(usuario_modificacao=self.request.user)
@swagger_auto_schema(method='patch', manual_parameters=[openapi.
Parameter('token', openapi.IN_QUERY, type=openapi.TYPE_STRING,
required=True)])
@transaction.atomic
@action(detail=True, methods=['patch'], serializer_class=
CustomUsuarioMudarPasswordAposResetSerializer)
def mudar_password_apos_reset(self, request, pk=None):
usuario = self.get_object()
try:
token = request.query_params['token']
except KeyError:
return Response({'status': 'Token não informado.'}, status=
status.HTTP_400_BAD_REQUEST)
try:
token_instance = usuario.password_reset_tokens.get(token=token)
except PasswordResetToken.DoesNotExist:
return Response({'status': 'Token inválido.'}, status=status.
HTTP_400_BAD_REQUEST)
serializer_token = PasswordResetTokenSerializer(token_instance,
data={'ativo': False}, partial=True)
if serializer_token.is_valid():
serializer_token.save()
else:
return Response(serializer_token.errors, status=status.
HTTP_400_BAD_REQUEST)
serializer_usuario = self.get_serializer(usuario, data=request.data,
partial=True)
if serializer_usuario.is_valid():
serializer_usuario.save()
return Response({'status': 'A nova senha foi registrada.'},
status=status.HTTP_200_OK)
return Response(serializer_usuario.errors, status=status.
HTTP_400_BAD_REQUEST)
@action(detail=True, methods=['patch'], serializer_class=
CustomUsuarioMudarPasswordSerializer)
def mudar_password(self, request, pk=None):
usuario = self.get_object()
serializer = self.get_serializer(usuario, data=request.data,
partial=True)
if serializer.is_valid():
serializer.save()
return Response({'status': 'A nova senha foi registrada.'},
status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
<|reserved_special_token_0|>
@action(detail=True, methods=['patch'], serializer_class=
CustomUsuarioMudarGrupoSerializer)
def mudar_grupo(self, request, pk=None):
usuario = self.get_object()
serializer = self.get_serializer(usuario, data=request.data,
partial=True)
if serializer.is_valid():
serializer.save()
return Response({'status': 'O grupo foi alterado com sucesso.'},
status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
<|reserved_special_token_0|>
<|reserved_special_token_0|>
class GroupViewSet(AccessViewSetMixin, ReadOnlyModelViewSet):
"""
Group ViewSet description:
list: Listar grupos.
retrieve: Consultar grupos.
"""
access_policy = GroupAccessPolicy
serializer_class = GroupSerializer
def get_queryset(self):
return Group.objects.all().order_by('id')
class PasswordResetTokenViewSet(AccessViewSetMixin, mixins.CreateModelMixin,
mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet):
"""
Password Reset Token ViewSet description:
create: Criar token.
retrieve: Consultar token.
list: Listar tokens.
"""
access_policy = PasswordResetTokenAccessPolicy
serializer_class = PasswordResetTokenSerializer
def get_queryset(self):
return PasswordResetToken.objects.all().order_by('id')
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response({'status':
'Token criado. E-mail enviado ao usuário para criação de nova senha.'
}, status=status.HTTP_201_CREATED, headers=headers)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class CustomUsuarioViewSet(AccessViewSetMixin, mixins.CreateModelMixin,
mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def get_queryset(self):
return CustomUsuario.objects.all().order_by('id')
def perform_create(self, serializer):
serializer.save(usuario_modificacao=self.request.user)
def perform_update(self, serializer):
serializer.save(usuario_modificacao=self.request.user)
@swagger_auto_schema(method='patch', manual_parameters=[openapi.
Parameter('token', openapi.IN_QUERY, type=openapi.TYPE_STRING,
required=True)])
@transaction.atomic
@action(detail=True, methods=['patch'], serializer_class=
CustomUsuarioMudarPasswordAposResetSerializer)
def mudar_password_apos_reset(self, request, pk=None):
usuario = self.get_object()
try:
token = request.query_params['token']
except KeyError:
return Response({'status': 'Token não informado.'}, status=
status.HTTP_400_BAD_REQUEST)
try:
token_instance = usuario.password_reset_tokens.get(token=token)
except PasswordResetToken.DoesNotExist:
return Response({'status': 'Token inválido.'}, status=status.
HTTP_400_BAD_REQUEST)
serializer_token = PasswordResetTokenSerializer(token_instance,
data={'ativo': False}, partial=True)
if serializer_token.is_valid():
serializer_token.save()
else:
return Response(serializer_token.errors, status=status.
HTTP_400_BAD_REQUEST)
serializer_usuario = self.get_serializer(usuario, data=request.data,
partial=True)
if serializer_usuario.is_valid():
serializer_usuario.save()
return Response({'status': 'A nova senha foi registrada.'},
status=status.HTTP_200_OK)
return Response(serializer_usuario.errors, status=status.
HTTP_400_BAD_REQUEST)
@action(detail=True, methods=['patch'], serializer_class=
CustomUsuarioMudarPasswordSerializer)
def mudar_password(self, request, pk=None):
usuario = self.get_object()
serializer = self.get_serializer(usuario, data=request.data,
partial=True)
if serializer.is_valid():
serializer.save()
return Response({'status': 'A nova senha foi registrada.'},
status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@action(detail=True, methods=['patch'], serializer_class=
CustomUsuarioMudarEmailSerializer)
def mudar_email(self, request, pk=None):
usuario = self.get_object()
if 'password' not in request.data:
return Response({'status':
'Para mudar o e-mail é necessário informar a senha atual.'},
status=status.HTTP_400_BAD_REQUEST)
serializer = self.get_serializer(usuario, data=request.data,
partial=True)
if serializer.is_valid():
serializer.save()
return Response({'status': 'O e-mail foi alterado com sucesso.'
}, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@action(detail=True, methods=['patch'], serializer_class=
CustomUsuarioMudarGrupoSerializer)
def mudar_grupo(self, request, pk=None):
usuario = self.get_object()
serializer = self.get_serializer(usuario, data=request.data,
partial=True)
if serializer.is_valid():
serializer.save()
return Response({'status': 'O grupo foi alterado com sucesso.'},
status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@action(detail=True, methods=['patch'], serializer_class=
CustomUsuarioMudarAtivacaoSerializer)
def ativar(self, request, pk=None):
usuario = self.get_object()
serializer = self.get_serializer(usuario, data={'is_active': True},
partial=True)
if serializer.is_valid():
serializer.save()
try:
usuario.perfil.ativo = True
usuario.perfil.save()
except Exception:
print('Não há perfil vinculado ao usuário.')
return Response({'status': 'Usuário ativado.'}, status=status.
HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@action(detail=True, methods=['patch'], serializer_class=
CustomUsuarioMudarAtivacaoSerializer)
def desativar(self, request, pk=None):
usuario = self.get_object()
serializer = self.get_serializer(usuario, data={'is_active': False},
partial=True)
if serializer.is_valid():
serializer.save()
try:
usuario.perfil.ativo = False
usuario.perfil.save()
except Exception:
print('Não há perfil vinculado ao usuário.')
return Response({'status': 'Usuário desativado.'}, status=
status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class GroupViewSet(AccessViewSetMixin, ReadOnlyModelViewSet):
"""
Group ViewSet description:
list: Listar grupos.
retrieve: Consultar grupos.
"""
access_policy = GroupAccessPolicy
serializer_class = GroupSerializer
def get_queryset(self):
return Group.objects.all().order_by('id')
class PasswordResetTokenViewSet(AccessViewSetMixin, mixins.CreateModelMixin,
mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet):
"""
Password Reset Token ViewSet description:
create: Criar token.
retrieve: Consultar token.
list: Listar tokens.
"""
access_policy = PasswordResetTokenAccessPolicy
serializer_class = PasswordResetTokenSerializer
def get_queryset(self):
return PasswordResetToken.objects.all().order_by('id')
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response({'status':
'Token criado. E-mail enviado ao usuário para criação de nova senha.'
}, status=status.HTTP_201_CREATED, headers=headers)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class CustomUsuarioViewSet(AccessViewSetMixin, mixins.CreateModelMixin,
mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet):
"""
CustomUsuario ViewSet description:
create: Criar usuário.
retrieve: Consultar usuário.
list: Listar usuários.
ativar: Ativar usuário.
desativar: Desativar usuário.
mudar_password_apos_reset: Mudar a password do usuário após a solicitação de resetá-la. Consequentemente,
é desativado o token que permitiu a alteração.
mudar_password: Atualiza a password do usuário.
mudar_email: Atualiza o e-mail do usuário.
mudar_grupo: Atualiza o(s) grupo(s) do usuário.
"""
access_policy = CustomUsuarioAccessPolicy
serializer_class = CustomUsuarioSerializer
def get_queryset(self):
return CustomUsuario.objects.all().order_by('id')
def perform_create(self, serializer):
serializer.save(usuario_modificacao=self.request.user)
def perform_update(self, serializer):
serializer.save(usuario_modificacao=self.request.user)
@swagger_auto_schema(method='patch', manual_parameters=[openapi.
Parameter('token', openapi.IN_QUERY, type=openapi.TYPE_STRING,
required=True)])
@transaction.atomic
@action(detail=True, methods=['patch'], serializer_class=
CustomUsuarioMudarPasswordAposResetSerializer)
def mudar_password_apos_reset(self, request, pk=None):
usuario = self.get_object()
try:
token = request.query_params['token']
except KeyError:
return Response({'status': 'Token não informado.'}, status=
status.HTTP_400_BAD_REQUEST)
try:
token_instance = usuario.password_reset_tokens.get(token=token)
except PasswordResetToken.DoesNotExist:
return Response({'status': 'Token inválido.'}, status=status.
HTTP_400_BAD_REQUEST)
serializer_token = PasswordResetTokenSerializer(token_instance,
data={'ativo': False}, partial=True)
if serializer_token.is_valid():
serializer_token.save()
else:
return Response(serializer_token.errors, status=status.
HTTP_400_BAD_REQUEST)
serializer_usuario = self.get_serializer(usuario, data=request.data,
partial=True)
if serializer_usuario.is_valid():
serializer_usuario.save()
return Response({'status': 'A nova senha foi registrada.'},
status=status.HTTP_200_OK)
return Response(serializer_usuario.errors, status=status.
HTTP_400_BAD_REQUEST)
@action(detail=True, methods=['patch'], serializer_class=
CustomUsuarioMudarPasswordSerializer)
def mudar_password(self, request, pk=None):
usuario = self.get_object()
serializer = self.get_serializer(usuario, data=request.data,
partial=True)
if serializer.is_valid():
serializer.save()
return Response({'status': 'A nova senha foi registrada.'},
status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@action(detail=True, methods=['patch'], serializer_class=
CustomUsuarioMudarEmailSerializer)
def mudar_email(self, request, pk=None):
usuario = self.get_object()
if 'password' not in request.data:
return Response({'status':
'Para mudar o e-mail é necessário informar a senha atual.'},
status=status.HTTP_400_BAD_REQUEST)
serializer = self.get_serializer(usuario, data=request.data,
partial=True)
if serializer.is_valid():
serializer.save()
return Response({'status': 'O e-mail foi alterado com sucesso.'
}, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@action(detail=True, methods=['patch'], serializer_class=
CustomUsuarioMudarGrupoSerializer)
def mudar_grupo(self, request, pk=None):
usuario = self.get_object()
serializer = self.get_serializer(usuario, data=request.data,
partial=True)
if serializer.is_valid():
serializer.save()
return Response({'status': 'O grupo foi alterado com sucesso.'},
status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@action(detail=True, methods=['patch'], serializer_class=
CustomUsuarioMudarAtivacaoSerializer)
def ativar(self, request, pk=None):
usuario = self.get_object()
serializer = self.get_serializer(usuario, data={'is_active': True},
partial=True)
if serializer.is_valid():
serializer.save()
try:
usuario.perfil.ativo = True
usuario.perfil.save()
except Exception:
print('Não há perfil vinculado ao usuário.')
return Response({'status': 'Usuário ativado.'}, status=status.
HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@action(detail=True, methods=['patch'], serializer_class=
CustomUsuarioMudarAtivacaoSerializer)
def desativar(self, request, pk=None):
usuario = self.get_object()
serializer = self.get_serializer(usuario, data={'is_active': False},
partial=True)
if serializer.is_valid():
serializer.save()
try:
usuario.perfil.ativo = False
usuario.perfil.save()
except Exception:
print('Não há perfil vinculado ao usuário.')
return Response({'status': 'Usuário desativado.'}, status=
status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class GroupViewSet(AccessViewSetMixin, ReadOnlyModelViewSet):
"""
Group ViewSet description:
list: Listar grupos.
retrieve: Consultar grupos.
"""
access_policy = GroupAccessPolicy
serializer_class = GroupSerializer
def get_queryset(self):
return Group.objects.all().order_by('id')
class PasswordResetTokenViewSet(AccessViewSetMixin, mixins.CreateModelMixin,
mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet):
"""
Password Reset Token ViewSet description:
create: Criar token.
retrieve: Consultar token.
list: Listar tokens.
"""
access_policy = PasswordResetTokenAccessPolicy
serializer_class = PasswordResetTokenSerializer
def get_queryset(self):
return PasswordResetToken.objects.all().order_by('id')
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response({'status':
'Token criado. E-mail enviado ao usuário para criação de nova senha.'
}, status=status.HTTP_201_CREATED, headers=headers)
<|reserved_special_token_1|>
from django.db import transaction
from django.contrib.auth.models import Group
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from rest_framework import status, mixins
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet, GenericViewSet
from rest_access_policy import AccessViewSetMixin
from .models import CustomUsuario, PasswordResetToken
from .serializers import (
GroupSerializer,
CustomUsuarioSerializer,
CustomUsuarioMudarPasswordSerializer,
CustomUsuarioMudarPasswordAposResetSerializer,
CustomUsuarioMudarEmailSerializer,
CustomUsuarioMudarGrupoSerializer,
CustomUsuarioMudarAtivacaoSerializer,
PasswordResetTokenSerializer
)
from .views_access_policies import GroupAccessPolicy, CustomUsuarioAccessPolicy, PasswordResetTokenAccessPolicy
class CustomUsuarioViewSet(AccessViewSetMixin,
mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.ListModelMixin,
GenericViewSet):
"""
CustomUsuario ViewSet description:
create: Criar usuário.
retrieve: Consultar usuário.
list: Listar usuários.
ativar: Ativar usuário.
desativar: Desativar usuário.
mudar_password_apos_reset: Mudar a password do usuário após a solicitação de resetá-la. Consequentemente,
é desativado o token que permitiu a alteração.
mudar_password: Atualiza a password do usuário.
mudar_email: Atualiza o e-mail do usuário.
mudar_grupo: Atualiza o(s) grupo(s) do usuário.
"""
access_policy = CustomUsuarioAccessPolicy
serializer_class = CustomUsuarioSerializer
def get_queryset(self):
return CustomUsuario.objects.all().order_by('id')
def perform_create(self, serializer):
serializer.save(usuario_modificacao=self.request.user)
def perform_update(self, serializer):
serializer.save(usuario_modificacao=self.request.user)
@swagger_auto_schema(method='patch', manual_parameters=[openapi.Parameter('token',
openapi.IN_QUERY,
type=openapi.TYPE_STRING,
required=True)])
@transaction.atomic
@action(detail=True, methods=['patch'], serializer_class=CustomUsuarioMudarPasswordAposResetSerializer)
def mudar_password_apos_reset(self, request, pk=None):
usuario = self.get_object()
try:
token = request.query_params['token']
except KeyError:
return Response({'status': 'Token não informado.'},
status=status.HTTP_400_BAD_REQUEST)
try:
token_instance = usuario.password_reset_tokens.get(token=token)
except PasswordResetToken.DoesNotExist:
return Response({'status': 'Token inválido.'},
status=status.HTTP_400_BAD_REQUEST)
serializer_token = PasswordResetTokenSerializer(token_instance,
data={'ativo': False},
partial=True)
if serializer_token.is_valid():
serializer_token.save()
else:
return Response(serializer_token.errors,
status=status.HTTP_400_BAD_REQUEST)
serializer_usuario = self.get_serializer(
usuario,
data=request.data,
partial=True
)
if serializer_usuario.is_valid():
serializer_usuario.save()
return Response({'status': 'A nova senha foi registrada.'},
status=status.HTTP_200_OK)
return Response(serializer_usuario.errors,
status=status.HTTP_400_BAD_REQUEST)
@action(detail=True, methods=['patch'], serializer_class=CustomUsuarioMudarPasswordSerializer)
def mudar_password(self, request, pk=None):
usuario = self.get_object()
serializer = self.get_serializer(usuario,
data=request.data,
partial=True)
if serializer.is_valid():
serializer.save()
return Response({'status': 'A nova senha foi registrada.'},
status=status.HTTP_200_OK)
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
@action(detail=True, methods=['patch'], serializer_class=CustomUsuarioMudarEmailSerializer)
def mudar_email(self, request, pk=None):
usuario = self.get_object()
if 'password' not in request.data:
return Response({'status': 'Para mudar o e-mail é necessário '
'informar a senha atual.'},
status=status.HTTP_400_BAD_REQUEST)
serializer = self.get_serializer(usuario, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return Response({'status': 'O e-mail foi alterado com sucesso.'}, status=status.HTTP_200_OK)
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
@action(detail=True, methods=['patch'], serializer_class=CustomUsuarioMudarGrupoSerializer)
def mudar_grupo(self, request, pk=None):
usuario = self.get_object()
serializer = self.get_serializer(usuario, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return Response({'status': 'O grupo foi alterado com sucesso.'}, status=status.HTTP_200_OK)
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
@action(detail=True, methods=['patch'], serializer_class=CustomUsuarioMudarAtivacaoSerializer)
def ativar(self, request, pk=None):
usuario = self.get_object()
serializer = self.get_serializer(
usuario,
data={'is_active': True},
partial=True
)
if serializer.is_valid():
serializer.save()
try:
usuario.perfil.ativo = True
usuario.perfil.save()
except Exception:
print("Não há perfil vinculado ao usuário.")
return Response({'status': 'Usuário ativado.'},
status=status.HTTP_200_OK)
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
@action(detail=True, methods=['patch'], serializer_class=CustomUsuarioMudarAtivacaoSerializer)
def desativar(self, request, pk=None):
usuario = self.get_object()
serializer = self.get_serializer(
usuario,
data={'is_active': False},
partial=True
)
if serializer.is_valid():
serializer.save()
try:
usuario.perfil.ativo = False
usuario.perfil.save()
except Exception:
print("Não há perfil vinculado ao usuário.")
return Response({'status': 'Usuário desativado.'},
status=status.HTTP_200_OK)
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
class GroupViewSet(AccessViewSetMixin, ReadOnlyModelViewSet):
"""
Group ViewSet description:
list: Listar grupos.
retrieve: Consultar grupos.
"""
access_policy = GroupAccessPolicy
serializer_class = GroupSerializer
def get_queryset(self):
return Group.objects.all().order_by('id')
class PasswordResetTokenViewSet(AccessViewSetMixin,
mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.ListModelMixin,
GenericViewSet):
"""
Password Reset Token ViewSet description:
create: Criar token.
retrieve: Consultar token.
list: Listar tokens.
"""
access_policy = PasswordResetTokenAccessPolicy
serializer_class = PasswordResetTokenSerializer
def get_queryset(self):
return PasswordResetToken.objects.all().order_by('id')
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response({'status': 'Token criado. E-mail enviado ao '
'usuário para criação de nova senha.'},
status=status.HTTP_201_CREATED, headers=headers)
|
flexible
|
{
"blob_id": "43b5936ca9368dcae8d41b44fd9dc927fe18c9bc",
"index": 8794,
"step-1": "<mask token>\n\n\nclass CustomUsuarioViewSet(AccessViewSetMixin, mixins.CreateModelMixin,\n mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def perform_update(self, serializer):\n serializer.save(usuario_modificacao=self.request.user)\n\n @swagger_auto_schema(method='patch', manual_parameters=[openapi.\n Parameter('token', openapi.IN_QUERY, type=openapi.TYPE_STRING,\n required=True)])\n @transaction.atomic\n @action(detail=True, methods=['patch'], serializer_class=\n CustomUsuarioMudarPasswordAposResetSerializer)\n def mudar_password_apos_reset(self, request, pk=None):\n usuario = self.get_object()\n try:\n token = request.query_params['token']\n except KeyError:\n return Response({'status': 'Token não informado.'}, status=\n status.HTTP_400_BAD_REQUEST)\n try:\n token_instance = usuario.password_reset_tokens.get(token=token)\n except PasswordResetToken.DoesNotExist:\n return Response({'status': 'Token inválido.'}, status=status.\n HTTP_400_BAD_REQUEST)\n serializer_token = PasswordResetTokenSerializer(token_instance,\n data={'ativo': False}, partial=True)\n if serializer_token.is_valid():\n serializer_token.save()\n else:\n return Response(serializer_token.errors, status=status.\n HTTP_400_BAD_REQUEST)\n serializer_usuario = self.get_serializer(usuario, data=request.data,\n partial=True)\n if serializer_usuario.is_valid():\n serializer_usuario.save()\n return Response({'status': 'A nova senha foi registrada.'},\n status=status.HTTP_200_OK)\n return Response(serializer_usuario.errors, status=status.\n HTTP_400_BAD_REQUEST)\n <mask token>\n <mask token>\n\n @action(detail=True, methods=['patch'], serializer_class=\n CustomUsuarioMudarGrupoSerializer)\n def mudar_grupo(self, request, pk=None):\n usuario = self.get_object()\n serializer = self.get_serializer(usuario, data=request.data,\n partial=True)\n if serializer.is_valid():\n serializer.save()\n return Response({'status': 'O grupo foi alterado com sucesso.'},\n status=status.HTTP_200_OK)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n <mask token>\n <mask token>\n\n\nclass GroupViewSet(AccessViewSetMixin, ReadOnlyModelViewSet):\n \"\"\"\n Group ViewSet description:\n\n list: Listar grupos.\n retrieve: Consultar grupos.\n \"\"\"\n access_policy = GroupAccessPolicy\n serializer_class = GroupSerializer\n\n def get_queryset(self):\n return Group.objects.all().order_by('id')\n\n\nclass PasswordResetTokenViewSet(AccessViewSetMixin, mixins.CreateModelMixin,\n mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet):\n \"\"\"\n Password Reset Token ViewSet description:\n\n create: Criar token.\n retrieve: Consultar token.\n list: Listar tokens.\n \"\"\"\n access_policy = PasswordResetTokenAccessPolicy\n serializer_class = PasswordResetTokenSerializer\n\n def get_queryset(self):\n return PasswordResetToken.objects.all().order_by('id')\n\n def create(self, request, *args, **kwargs):\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n self.perform_create(serializer)\n headers = self.get_success_headers(serializer.data)\n return Response({'status':\n 'Token criado. E-mail enviado ao usuário para criação de nova senha.'\n }, status=status.HTTP_201_CREATED, headers=headers)\n",
"step-2": "<mask token>\n\n\nclass CustomUsuarioViewSet(AccessViewSetMixin, mixins.CreateModelMixin,\n mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def perform_update(self, serializer):\n serializer.save(usuario_modificacao=self.request.user)\n\n @swagger_auto_schema(method='patch', manual_parameters=[openapi.\n Parameter('token', openapi.IN_QUERY, type=openapi.TYPE_STRING,\n required=True)])\n @transaction.atomic\n @action(detail=True, methods=['patch'], serializer_class=\n CustomUsuarioMudarPasswordAposResetSerializer)\n def mudar_password_apos_reset(self, request, pk=None):\n usuario = self.get_object()\n try:\n token = request.query_params['token']\n except KeyError:\n return Response({'status': 'Token não informado.'}, status=\n status.HTTP_400_BAD_REQUEST)\n try:\n token_instance = usuario.password_reset_tokens.get(token=token)\n except PasswordResetToken.DoesNotExist:\n return Response({'status': 'Token inválido.'}, status=status.\n HTTP_400_BAD_REQUEST)\n serializer_token = PasswordResetTokenSerializer(token_instance,\n data={'ativo': False}, partial=True)\n if serializer_token.is_valid():\n serializer_token.save()\n else:\n return Response(serializer_token.errors, status=status.\n HTTP_400_BAD_REQUEST)\n serializer_usuario = self.get_serializer(usuario, data=request.data,\n partial=True)\n if serializer_usuario.is_valid():\n serializer_usuario.save()\n return Response({'status': 'A nova senha foi registrada.'},\n status=status.HTTP_200_OK)\n return Response(serializer_usuario.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n @action(detail=True, methods=['patch'], serializer_class=\n CustomUsuarioMudarPasswordSerializer)\n def mudar_password(self, request, pk=None):\n usuario = self.get_object()\n serializer = self.get_serializer(usuario, data=request.data,\n partial=True)\n if serializer.is_valid():\n serializer.save()\n return Response({'status': 'A nova senha foi registrada.'},\n status=status.HTTP_200_OK)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n <mask token>\n\n @action(detail=True, methods=['patch'], serializer_class=\n CustomUsuarioMudarGrupoSerializer)\n def mudar_grupo(self, request, pk=None):\n usuario = self.get_object()\n serializer = self.get_serializer(usuario, data=request.data,\n partial=True)\n if serializer.is_valid():\n serializer.save()\n return Response({'status': 'O grupo foi alterado com sucesso.'},\n status=status.HTTP_200_OK)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n <mask token>\n <mask token>\n\n\nclass GroupViewSet(AccessViewSetMixin, ReadOnlyModelViewSet):\n \"\"\"\n Group ViewSet description:\n\n list: Listar grupos.\n retrieve: Consultar grupos.\n \"\"\"\n access_policy = GroupAccessPolicy\n serializer_class = GroupSerializer\n\n def get_queryset(self):\n return Group.objects.all().order_by('id')\n\n\nclass PasswordResetTokenViewSet(AccessViewSetMixin, mixins.CreateModelMixin,\n mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet):\n \"\"\"\n Password Reset Token ViewSet description:\n\n create: Criar token.\n retrieve: Consultar token.\n list: Listar tokens.\n \"\"\"\n access_policy = PasswordResetTokenAccessPolicy\n serializer_class = PasswordResetTokenSerializer\n\n def get_queryset(self):\n return PasswordResetToken.objects.all().order_by('id')\n\n def create(self, request, *args, **kwargs):\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n self.perform_create(serializer)\n headers = self.get_success_headers(serializer.data)\n return Response({'status':\n 'Token criado. E-mail enviado ao usuário para criação de nova senha.'\n }, status=status.HTTP_201_CREATED, headers=headers)\n",
"step-3": "<mask token>\n\n\nclass CustomUsuarioViewSet(AccessViewSetMixin, mixins.CreateModelMixin,\n mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet):\n <mask token>\n <mask token>\n <mask token>\n\n def get_queryset(self):\n return CustomUsuario.objects.all().order_by('id')\n\n def perform_create(self, serializer):\n serializer.save(usuario_modificacao=self.request.user)\n\n def perform_update(self, serializer):\n serializer.save(usuario_modificacao=self.request.user)\n\n @swagger_auto_schema(method='patch', manual_parameters=[openapi.\n Parameter('token', openapi.IN_QUERY, type=openapi.TYPE_STRING,\n required=True)])\n @transaction.atomic\n @action(detail=True, methods=['patch'], serializer_class=\n CustomUsuarioMudarPasswordAposResetSerializer)\n def mudar_password_apos_reset(self, request, pk=None):\n usuario = self.get_object()\n try:\n token = request.query_params['token']\n except KeyError:\n return Response({'status': 'Token não informado.'}, status=\n status.HTTP_400_BAD_REQUEST)\n try:\n token_instance = usuario.password_reset_tokens.get(token=token)\n except PasswordResetToken.DoesNotExist:\n return Response({'status': 'Token inválido.'}, status=status.\n HTTP_400_BAD_REQUEST)\n serializer_token = PasswordResetTokenSerializer(token_instance,\n data={'ativo': False}, partial=True)\n if serializer_token.is_valid():\n serializer_token.save()\n else:\n return Response(serializer_token.errors, status=status.\n HTTP_400_BAD_REQUEST)\n serializer_usuario = self.get_serializer(usuario, data=request.data,\n partial=True)\n if serializer_usuario.is_valid():\n serializer_usuario.save()\n return Response({'status': 'A nova senha foi registrada.'},\n status=status.HTTP_200_OK)\n return Response(serializer_usuario.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n @action(detail=True, methods=['patch'], serializer_class=\n CustomUsuarioMudarPasswordSerializer)\n def mudar_password(self, request, pk=None):\n usuario = self.get_object()\n serializer = self.get_serializer(usuario, data=request.data,\n partial=True)\n if serializer.is_valid():\n serializer.save()\n return Response({'status': 'A nova senha foi registrada.'},\n status=status.HTTP_200_OK)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n @action(detail=True, methods=['patch'], serializer_class=\n CustomUsuarioMudarEmailSerializer)\n def mudar_email(self, request, pk=None):\n usuario = self.get_object()\n if 'password' not in request.data:\n return Response({'status':\n 'Para mudar o e-mail é necessário informar a senha atual.'},\n status=status.HTTP_400_BAD_REQUEST)\n serializer = self.get_serializer(usuario, data=request.data,\n partial=True)\n if serializer.is_valid():\n serializer.save()\n return Response({'status': 'O e-mail foi alterado com sucesso.'\n }, status=status.HTTP_200_OK)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n @action(detail=True, methods=['patch'], serializer_class=\n CustomUsuarioMudarGrupoSerializer)\n def mudar_grupo(self, request, pk=None):\n usuario = self.get_object()\n serializer = self.get_serializer(usuario, data=request.data,\n partial=True)\n if serializer.is_valid():\n serializer.save()\n return Response({'status': 'O grupo foi alterado com sucesso.'},\n status=status.HTTP_200_OK)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n @action(detail=True, methods=['patch'], serializer_class=\n CustomUsuarioMudarAtivacaoSerializer)\n def ativar(self, request, pk=None):\n usuario = self.get_object()\n serializer = self.get_serializer(usuario, data={'is_active': True},\n partial=True)\n if serializer.is_valid():\n serializer.save()\n try:\n usuario.perfil.ativo = True\n usuario.perfil.save()\n except Exception:\n print('Não há perfil vinculado ao usuário.')\n return Response({'status': 'Usuário ativado.'}, status=status.\n HTTP_200_OK)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n @action(detail=True, methods=['patch'], serializer_class=\n CustomUsuarioMudarAtivacaoSerializer)\n def desativar(self, request, pk=None):\n usuario = self.get_object()\n serializer = self.get_serializer(usuario, data={'is_active': False},\n partial=True)\n if serializer.is_valid():\n serializer.save()\n try:\n usuario.perfil.ativo = False\n usuario.perfil.save()\n except Exception:\n print('Não há perfil vinculado ao usuário.')\n return Response({'status': 'Usuário desativado.'}, status=\n status.HTTP_200_OK)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass GroupViewSet(AccessViewSetMixin, ReadOnlyModelViewSet):\n \"\"\"\n Group ViewSet description:\n\n list: Listar grupos.\n retrieve: Consultar grupos.\n \"\"\"\n access_policy = GroupAccessPolicy\n serializer_class = GroupSerializer\n\n def get_queryset(self):\n return Group.objects.all().order_by('id')\n\n\nclass PasswordResetTokenViewSet(AccessViewSetMixin, mixins.CreateModelMixin,\n mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet):\n \"\"\"\n Password Reset Token ViewSet description:\n\n create: Criar token.\n retrieve: Consultar token.\n list: Listar tokens.\n \"\"\"\n access_policy = PasswordResetTokenAccessPolicy\n serializer_class = PasswordResetTokenSerializer\n\n def get_queryset(self):\n return PasswordResetToken.objects.all().order_by('id')\n\n def create(self, request, *args, **kwargs):\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n self.perform_create(serializer)\n headers = self.get_success_headers(serializer.data)\n return Response({'status':\n 'Token criado. E-mail enviado ao usuário para criação de nova senha.'\n }, status=status.HTTP_201_CREATED, headers=headers)\n",
"step-4": "<mask token>\n\n\nclass CustomUsuarioViewSet(AccessViewSetMixin, mixins.CreateModelMixin,\n mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet):\n \"\"\"\n CustomUsuario ViewSet description:\n\n create: Criar usuário.\n retrieve: Consultar usuário.\n list: Listar usuários.\n ativar: Ativar usuário.\n desativar: Desativar usuário.\n mudar_password_apos_reset: Mudar a password do usuário após a solicitação de resetá-la. Consequentemente,\n é desativado o token que permitiu a alteração.\n mudar_password: Atualiza a password do usuário.\n mudar_email: Atualiza o e-mail do usuário.\n mudar_grupo: Atualiza o(s) grupo(s) do usuário.\n \"\"\"\n access_policy = CustomUsuarioAccessPolicy\n serializer_class = CustomUsuarioSerializer\n\n def get_queryset(self):\n return CustomUsuario.objects.all().order_by('id')\n\n def perform_create(self, serializer):\n serializer.save(usuario_modificacao=self.request.user)\n\n def perform_update(self, serializer):\n serializer.save(usuario_modificacao=self.request.user)\n\n @swagger_auto_schema(method='patch', manual_parameters=[openapi.\n Parameter('token', openapi.IN_QUERY, type=openapi.TYPE_STRING,\n required=True)])\n @transaction.atomic\n @action(detail=True, methods=['patch'], serializer_class=\n CustomUsuarioMudarPasswordAposResetSerializer)\n def mudar_password_apos_reset(self, request, pk=None):\n usuario = self.get_object()\n try:\n token = request.query_params['token']\n except KeyError:\n return Response({'status': 'Token não informado.'}, status=\n status.HTTP_400_BAD_REQUEST)\n try:\n token_instance = usuario.password_reset_tokens.get(token=token)\n except PasswordResetToken.DoesNotExist:\n return Response({'status': 'Token inválido.'}, status=status.\n HTTP_400_BAD_REQUEST)\n serializer_token = PasswordResetTokenSerializer(token_instance,\n data={'ativo': False}, partial=True)\n if serializer_token.is_valid():\n serializer_token.save()\n else:\n return Response(serializer_token.errors, status=status.\n HTTP_400_BAD_REQUEST)\n serializer_usuario = self.get_serializer(usuario, data=request.data,\n partial=True)\n if serializer_usuario.is_valid():\n serializer_usuario.save()\n return Response({'status': 'A nova senha foi registrada.'},\n status=status.HTTP_200_OK)\n return Response(serializer_usuario.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n @action(detail=True, methods=['patch'], serializer_class=\n CustomUsuarioMudarPasswordSerializer)\n def mudar_password(self, request, pk=None):\n usuario = self.get_object()\n serializer = self.get_serializer(usuario, data=request.data,\n partial=True)\n if serializer.is_valid():\n serializer.save()\n return Response({'status': 'A nova senha foi registrada.'},\n status=status.HTTP_200_OK)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n @action(detail=True, methods=['patch'], serializer_class=\n CustomUsuarioMudarEmailSerializer)\n def mudar_email(self, request, pk=None):\n usuario = self.get_object()\n if 'password' not in request.data:\n return Response({'status':\n 'Para mudar o e-mail é necessário informar a senha atual.'},\n status=status.HTTP_400_BAD_REQUEST)\n serializer = self.get_serializer(usuario, data=request.data,\n partial=True)\n if serializer.is_valid():\n serializer.save()\n return Response({'status': 'O e-mail foi alterado com sucesso.'\n }, status=status.HTTP_200_OK)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n @action(detail=True, methods=['patch'], serializer_class=\n CustomUsuarioMudarGrupoSerializer)\n def mudar_grupo(self, request, pk=None):\n usuario = self.get_object()\n serializer = self.get_serializer(usuario, data=request.data,\n partial=True)\n if serializer.is_valid():\n serializer.save()\n return Response({'status': 'O grupo foi alterado com sucesso.'},\n status=status.HTTP_200_OK)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n @action(detail=True, methods=['patch'], serializer_class=\n CustomUsuarioMudarAtivacaoSerializer)\n def ativar(self, request, pk=None):\n usuario = self.get_object()\n serializer = self.get_serializer(usuario, data={'is_active': True},\n partial=True)\n if serializer.is_valid():\n serializer.save()\n try:\n usuario.perfil.ativo = True\n usuario.perfil.save()\n except Exception:\n print('Não há perfil vinculado ao usuário.')\n return Response({'status': 'Usuário ativado.'}, status=status.\n HTTP_200_OK)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n @action(detail=True, methods=['patch'], serializer_class=\n CustomUsuarioMudarAtivacaoSerializer)\n def desativar(self, request, pk=None):\n usuario = self.get_object()\n serializer = self.get_serializer(usuario, data={'is_active': False},\n partial=True)\n if serializer.is_valid():\n serializer.save()\n try:\n usuario.perfil.ativo = False\n usuario.perfil.save()\n except Exception:\n print('Não há perfil vinculado ao usuário.')\n return Response({'status': 'Usuário desativado.'}, status=\n status.HTTP_200_OK)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass GroupViewSet(AccessViewSetMixin, ReadOnlyModelViewSet):\n \"\"\"\n Group ViewSet description:\n\n list: Listar grupos.\n retrieve: Consultar grupos.\n \"\"\"\n access_policy = GroupAccessPolicy\n serializer_class = GroupSerializer\n\n def get_queryset(self):\n return Group.objects.all().order_by('id')\n\n\nclass PasswordResetTokenViewSet(AccessViewSetMixin, mixins.CreateModelMixin,\n mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet):\n \"\"\"\n Password Reset Token ViewSet description:\n\n create: Criar token.\n retrieve: Consultar token.\n list: Listar tokens.\n \"\"\"\n access_policy = PasswordResetTokenAccessPolicy\n serializer_class = PasswordResetTokenSerializer\n\n def get_queryset(self):\n return PasswordResetToken.objects.all().order_by('id')\n\n def create(self, request, *args, **kwargs):\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n self.perform_create(serializer)\n headers = self.get_success_headers(serializer.data)\n return Response({'status':\n 'Token criado. E-mail enviado ao usuário para criação de nova senha.'\n }, status=status.HTTP_201_CREATED, headers=headers)\n",
"step-5": "from django.db import transaction\nfrom django.contrib.auth.models import Group\nfrom drf_yasg import openapi\nfrom drf_yasg.utils import swagger_auto_schema\n\nfrom rest_framework import status, mixins\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\nfrom rest_framework.viewsets import ReadOnlyModelViewSet, GenericViewSet\nfrom rest_access_policy import AccessViewSetMixin\n\nfrom .models import CustomUsuario, PasswordResetToken\nfrom .serializers import (\n GroupSerializer,\n CustomUsuarioSerializer,\n CustomUsuarioMudarPasswordSerializer,\n CustomUsuarioMudarPasswordAposResetSerializer,\n CustomUsuarioMudarEmailSerializer,\n CustomUsuarioMudarGrupoSerializer,\n CustomUsuarioMudarAtivacaoSerializer,\n PasswordResetTokenSerializer\n)\nfrom .views_access_policies import GroupAccessPolicy, CustomUsuarioAccessPolicy, PasswordResetTokenAccessPolicy\n\nclass CustomUsuarioViewSet(AccessViewSetMixin,\n mixins.CreateModelMixin,\n mixins.RetrieveModelMixin,\n mixins.ListModelMixin,\n GenericViewSet):\n \"\"\"\n CustomUsuario ViewSet description:\n\n create: Criar usuário.\n retrieve: Consultar usuário.\n list: Listar usuários.\n ativar: Ativar usuário.\n desativar: Desativar usuário.\n mudar_password_apos_reset: Mudar a password do usuário após a solicitação de resetá-la. Consequentemente,\n é desativado o token que permitiu a alteração.\n mudar_password: Atualiza a password do usuário.\n mudar_email: Atualiza o e-mail do usuário.\n mudar_grupo: Atualiza o(s) grupo(s) do usuário.\n \"\"\"\n access_policy = CustomUsuarioAccessPolicy\n serializer_class = CustomUsuarioSerializer\n\n def get_queryset(self):\n return CustomUsuario.objects.all().order_by('id')\n\n def perform_create(self, serializer):\n serializer.save(usuario_modificacao=self.request.user)\n\n def perform_update(self, serializer):\n serializer.save(usuario_modificacao=self.request.user)\n\n @swagger_auto_schema(method='patch', manual_parameters=[openapi.Parameter('token',\n openapi.IN_QUERY,\n type=openapi.TYPE_STRING,\n required=True)])\n @transaction.atomic\n @action(detail=True, methods=['patch'], serializer_class=CustomUsuarioMudarPasswordAposResetSerializer)\n def mudar_password_apos_reset(self, request, pk=None):\n usuario = self.get_object()\n try:\n token = request.query_params['token']\n except KeyError:\n return Response({'status': 'Token não informado.'},\n status=status.HTTP_400_BAD_REQUEST)\n try:\n token_instance = usuario.password_reset_tokens.get(token=token)\n except PasswordResetToken.DoesNotExist:\n return Response({'status': 'Token inválido.'},\n status=status.HTTP_400_BAD_REQUEST)\n\n serializer_token = PasswordResetTokenSerializer(token_instance,\n data={'ativo': False},\n partial=True)\n if serializer_token.is_valid():\n serializer_token.save()\n else:\n return Response(serializer_token.errors,\n status=status.HTTP_400_BAD_REQUEST)\n\n serializer_usuario = self.get_serializer(\n usuario,\n data=request.data,\n partial=True\n )\n\n if serializer_usuario.is_valid():\n serializer_usuario.save()\n return Response({'status': 'A nova senha foi registrada.'},\n status=status.HTTP_200_OK)\n return Response(serializer_usuario.errors,\n status=status.HTTP_400_BAD_REQUEST)\n\n @action(detail=True, methods=['patch'], serializer_class=CustomUsuarioMudarPasswordSerializer)\n def mudar_password(self, request, pk=None):\n usuario = self.get_object()\n serializer = self.get_serializer(usuario,\n data=request.data,\n partial=True)\n\n if serializer.is_valid():\n serializer.save()\n return Response({'status': 'A nova senha foi registrada.'},\n status=status.HTTP_200_OK)\n\n return Response(serializer.errors,\n status=status.HTTP_400_BAD_REQUEST)\n\n @action(detail=True, methods=['patch'], serializer_class=CustomUsuarioMudarEmailSerializer)\n def mudar_email(self, request, pk=None):\n usuario = self.get_object()\n\n if 'password' not in request.data:\n return Response({'status': 'Para mudar o e-mail é necessário '\n 'informar a senha atual.'},\n status=status.HTTP_400_BAD_REQUEST)\n\n serializer = self.get_serializer(usuario, data=request.data, partial=True)\n if serializer.is_valid():\n serializer.save()\n return Response({'status': 'O e-mail foi alterado com sucesso.'}, status=status.HTTP_200_OK)\n\n return Response(serializer.errors,\n status=status.HTTP_400_BAD_REQUEST)\n\n @action(detail=True, methods=['patch'], serializer_class=CustomUsuarioMudarGrupoSerializer)\n def mudar_grupo(self, request, pk=None):\n usuario = self.get_object()\n serializer = self.get_serializer(usuario, data=request.data, partial=True)\n if serializer.is_valid():\n serializer.save()\n return Response({'status': 'O grupo foi alterado com sucesso.'}, status=status.HTTP_200_OK)\n return Response(serializer.errors,\n status=status.HTTP_400_BAD_REQUEST)\n\n @action(detail=True, methods=['patch'], serializer_class=CustomUsuarioMudarAtivacaoSerializer)\n def ativar(self, request, pk=None):\n usuario = self.get_object()\n serializer = self.get_serializer(\n usuario,\n data={'is_active': True},\n partial=True\n )\n if serializer.is_valid():\n serializer.save()\n try:\n usuario.perfil.ativo = True\n usuario.perfil.save()\n except Exception:\n print(\"Não há perfil vinculado ao usuário.\")\n return Response({'status': 'Usuário ativado.'},\n status=status.HTTP_200_OK)\n\n return Response(serializer.errors,\n status=status.HTTP_400_BAD_REQUEST)\n\n @action(detail=True, methods=['patch'], serializer_class=CustomUsuarioMudarAtivacaoSerializer)\n def desativar(self, request, pk=None):\n usuario = self.get_object()\n serializer = self.get_serializer(\n usuario,\n data={'is_active': False},\n partial=True\n )\n if serializer.is_valid():\n serializer.save()\n try:\n usuario.perfil.ativo = False\n usuario.perfil.save()\n except Exception:\n print(\"Não há perfil vinculado ao usuário.\")\n return Response({'status': 'Usuário desativado.'},\n status=status.HTTP_200_OK)\n\n return Response(serializer.errors,\n status=status.HTTP_400_BAD_REQUEST)\n\n\nclass GroupViewSet(AccessViewSetMixin, ReadOnlyModelViewSet):\n \"\"\"\n Group ViewSet description:\n\n list: Listar grupos.\n retrieve: Consultar grupos.\n \"\"\"\n access_policy = GroupAccessPolicy\n serializer_class = GroupSerializer\n\n def get_queryset(self):\n return Group.objects.all().order_by('id')\n\n\nclass PasswordResetTokenViewSet(AccessViewSetMixin,\n mixins.CreateModelMixin,\n mixins.RetrieveModelMixin,\n mixins.ListModelMixin,\n GenericViewSet):\n \"\"\"\n Password Reset Token ViewSet description:\n\n create: Criar token.\n retrieve: Consultar token.\n list: Listar tokens.\n \"\"\"\n access_policy = PasswordResetTokenAccessPolicy\n serializer_class = PasswordResetTokenSerializer\n\n def get_queryset(self):\n return PasswordResetToken.objects.all().order_by('id')\n\n def create(self, request, *args, **kwargs):\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n self.perform_create(serializer)\n headers = self.get_success_headers(serializer.data)\n return Response({'status': 'Token criado. E-mail enviado ao '\n 'usuário para criação de nova senha.'},\n status=status.HTTP_201_CREATED, headers=headers)\n",
"step-ids": [
13,
14,
19,
21,
23
]
}
|
[
13,
14,
19,
21,
23
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
setup(name='Antennass', version=VERSION, description=
'A class project that plots far field antenna array patterns',
long_description=README, long_description_content_type='text/markdown',
url='https://github.com/MdeVillefort/Antennass', author=
'Monsieur de Villefort', author_email='ethanmross92@gmail.com',
classifiers=['Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.8'], packages=['Antennass'],
install_requires=REQUIREMENTS, entry_points={'console_scripts': [
'antennass-cli=Antennass.antennass_cli:main',
'antennass-gui=Antennass.antennass_gui:main']})
<|reserved_special_token_1|>
<|reserved_special_token_0|>
HERE = pathlib.Path(__file__).parent
README = (HERE / 'README.md').read_text()
VERSION = '1.0.1'
REQUIREMENTS = (HERE / 'requirements.txt').read_text()
REQUIREMENTS = REQUIREMENTS.split('\n')
setup(name='Antennass', version=VERSION, description=
'A class project that plots far field antenna array patterns',
long_description=README, long_description_content_type='text/markdown',
url='https://github.com/MdeVillefort/Antennass', author=
'Monsieur de Villefort', author_email='ethanmross92@gmail.com',
classifiers=['Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.8'], packages=['Antennass'],
install_requires=REQUIREMENTS, entry_points={'console_scripts': [
'antennass-cli=Antennass.antennass_cli:main',
'antennass-gui=Antennass.antennass_gui:main']})
<|reserved_special_token_1|>
import pathlib
from setuptools import setup
HERE = pathlib.Path(__file__).parent
README = (HERE / 'README.md').read_text()
VERSION = '1.0.1'
REQUIREMENTS = (HERE / 'requirements.txt').read_text()
REQUIREMENTS = REQUIREMENTS.split('\n')
setup(name='Antennass', version=VERSION, description=
'A class project that plots far field antenna array patterns',
long_description=README, long_description_content_type='text/markdown',
url='https://github.com/MdeVillefort/Antennass', author=
'Monsieur de Villefort', author_email='ethanmross92@gmail.com',
classifiers=['Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.8'], packages=['Antennass'],
install_requires=REQUIREMENTS, entry_points={'console_scripts': [
'antennass-cli=Antennass.antennass_cli:main',
'antennass-gui=Antennass.antennass_gui:main']})
<|reserved_special_token_1|>
import pathlib
from setuptools import setup
# The directory containing this file
HERE = pathlib.Path(__file__).parent
# The text of the README file
README = (HERE / "README.md").read_text()
# Version: major.minor.patch
VERSION = "1.0.1"
REQUIREMENTS = (HERE / "requirements.txt").read_text()
REQUIREMENTS = REQUIREMENTS.split('\n')
# This call to setup() does all the work
setup(
name = "Antennass",
version = VERSION,
description = "A class project that plots far field antenna array patterns",
long_description = README,
long_description_content_type = "text/markdown",
url = "https://github.com/MdeVillefort/Antennass",
author = "Monsieur de Villefort",
author_email = "ethanmross92@gmail.com",
classifiers = [
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.8"
],
packages = ["Antennass"],
install_requires = REQUIREMENTS,
entry_points = {
"console_scripts" : [
"antennass-cli=Antennass.antennass_cli:main",
"antennass-gui=Antennass.antennass_gui:main",
]
},
)
|
flexible
|
{
"blob_id": "f563bb5bb32d3653d8a4115c75eda80b676ae3c6",
"index": 5759,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nsetup(name='Antennass', version=VERSION, description=\n 'A class project that plots far field antenna array patterns',\n long_description=README, long_description_content_type='text/markdown',\n url='https://github.com/MdeVillefort/Antennass', author=\n 'Monsieur de Villefort', author_email='ethanmross92@gmail.com',\n classifiers=['Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.8'], packages=['Antennass'],\n install_requires=REQUIREMENTS, entry_points={'console_scripts': [\n 'antennass-cli=Antennass.antennass_cli:main',\n 'antennass-gui=Antennass.antennass_gui:main']})\n",
"step-3": "<mask token>\nHERE = pathlib.Path(__file__).parent\nREADME = (HERE / 'README.md').read_text()\nVERSION = '1.0.1'\nREQUIREMENTS = (HERE / 'requirements.txt').read_text()\nREQUIREMENTS = REQUIREMENTS.split('\\n')\nsetup(name='Antennass', version=VERSION, description=\n 'A class project that plots far field antenna array patterns',\n long_description=README, long_description_content_type='text/markdown',\n url='https://github.com/MdeVillefort/Antennass', author=\n 'Monsieur de Villefort', author_email='ethanmross92@gmail.com',\n classifiers=['Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.8'], packages=['Antennass'],\n install_requires=REQUIREMENTS, entry_points={'console_scripts': [\n 'antennass-cli=Antennass.antennass_cli:main',\n 'antennass-gui=Antennass.antennass_gui:main']})\n",
"step-4": "import pathlib\nfrom setuptools import setup\nHERE = pathlib.Path(__file__).parent\nREADME = (HERE / 'README.md').read_text()\nVERSION = '1.0.1'\nREQUIREMENTS = (HERE / 'requirements.txt').read_text()\nREQUIREMENTS = REQUIREMENTS.split('\\n')\nsetup(name='Antennass', version=VERSION, description=\n 'A class project that plots far field antenna array patterns',\n long_description=README, long_description_content_type='text/markdown',\n url='https://github.com/MdeVillefort/Antennass', author=\n 'Monsieur de Villefort', author_email='ethanmross92@gmail.com',\n classifiers=['Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.8'], packages=['Antennass'],\n install_requires=REQUIREMENTS, entry_points={'console_scripts': [\n 'antennass-cli=Antennass.antennass_cli:main',\n 'antennass-gui=Antennass.antennass_gui:main']})\n",
"step-5": "import pathlib\nfrom setuptools import setup\n\n# The directory containing this file\nHERE = pathlib.Path(__file__).parent\n\n# The text of the README file\nREADME = (HERE / \"README.md\").read_text()\n\n# Version: major.minor.patch\nVERSION = \"1.0.1\"\n\nREQUIREMENTS = (HERE / \"requirements.txt\").read_text()\nREQUIREMENTS = REQUIREMENTS.split('\\n')\n\n# This call to setup() does all the work\nsetup(\n name = \"Antennass\",\n version = VERSION,\n description = \"A class project that plots far field antenna array patterns\",\n long_description = README,\n long_description_content_type = \"text/markdown\",\n url = \"https://github.com/MdeVillefort/Antennass\",\n author = \"Monsieur de Villefort\",\n author_email = \"ethanmross92@gmail.com\",\n classifiers = [\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.8\"\n ],\n packages = [\"Antennass\"],\n install_requires = REQUIREMENTS,\n entry_points = {\n \"console_scripts\" : [\n \"antennass-cli=Antennass.antennass_cli:main\",\n \"antennass-gui=Antennass.antennass_gui:main\",\n ]\n },\n)\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
print(dic.get('country', 'Russia'))
<|reserved_special_token_0|>
print(dic)
<|reserved_special_token_1|>
dic = {'city': 'Moscow', 'temperature': 20}
print(dic.get('country', 'Russia'))
dic['date'] = '27.05.2019'
print(dic)
<|reserved_special_token_1|>
dic = {"city": "Moscow", "temperature": 20}
# print(dic["city"])
# dic["temperature"] -= 5
# print(dic)
print(dic.get("country", "Russia"))
dic["date"] = "27.05.2019"
print(dic)
|
flexible
|
{
"blob_id": "f145274c8caa1e725d12003874eb54a580a6e35e",
"index": 784,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(dic.get('country', 'Russia'))\n<mask token>\nprint(dic)\n",
"step-3": "dic = {'city': 'Moscow', 'temperature': 20}\nprint(dic.get('country', 'Russia'))\ndic['date'] = '27.05.2019'\nprint(dic)\n",
"step-4": "dic = {\"city\": \"Moscow\", \"temperature\": 20}\r\n# print(dic[\"city\"])\r\n# dic[\"temperature\"] -= 5\r\n# print(dic)\r\nprint(dic.get(\"country\", \"Russia\"))\r\ndic[\"date\"] = \"27.05.2019\" \r\nprint(dic)",
"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|>
plt.axis([0, 6, 0, 20])
plt.plot(x, y, 'ro')
plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))
plt.show()
<|reserved_special_token_1|>
<|reserved_special_token_0|>
x = [1, 2, 2.5, 3, 4]
y = [1, 4, 7, 9, 15]
plt.axis([0, 6, 0, 20])
plt.plot(x, y, 'ro')
plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))
plt.show()
<|reserved_special_token_1|>
import matplotlib.pyplot as plt
import numpy as np
x = [1, 2, 2.5, 3, 4]
y = [1, 4, 7, 9, 15]
plt.axis([0, 6, 0, 20])
plt.plot(x, y, 'ro')
plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))
plt.show()
<|reserved_special_token_1|>
import matplotlib.pyplot as plt
import numpy as np
x = [1, 2, 2.5, 3, 4] # x-coordinates for graph
y = [1, 4, 7, 9, 15] # y-coordinates
plt.axis([0, 6, 0, 20]) # creating my x and y axis range. 0-6 is x, 0-20 is y
plt.plot(x, y, 'ro')
# can see graph has a linear correspondence, therefore, can use linear regression that cn give us good predictions
# can create a line of best fit --> don't entirely understand syntax for line of best fit
# np.polyfit takes in x and y values, then the number of points (or connections) you want for your LBF
plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))
plt.show()
|
flexible
|
{
"blob_id": "c69c8ba218935e5bb065b3b925cc7c5f1aa2957b",
"index": 5806,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nplt.axis([0, 6, 0, 20])\nplt.plot(x, y, 'ro')\nplt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))\nplt.show()\n",
"step-3": "<mask token>\nx = [1, 2, 2.5, 3, 4]\ny = [1, 4, 7, 9, 15]\nplt.axis([0, 6, 0, 20])\nplt.plot(x, y, 'ro')\nplt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))\nplt.show()\n",
"step-4": "import matplotlib.pyplot as plt\nimport numpy as np\nx = [1, 2, 2.5, 3, 4]\ny = [1, 4, 7, 9, 15]\nplt.axis([0, 6, 0, 20])\nplt.plot(x, y, 'ro')\nplt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))\nplt.show()\n",
"step-5": "\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx = [1, 2, 2.5, 3, 4] # x-coordinates for graph\ny = [1, 4, 7, 9, 15] # y-coordinates\nplt.axis([0, 6, 0, 20]) # creating my x and y axis range. 0-6 is x, 0-20 is y\n\nplt.plot(x, y, 'ro')\n# can see graph has a linear correspondence, therefore, can use linear regression that cn give us good predictions\n# can create a line of best fit --> don't entirely understand syntax for line of best fit\n# np.polyfit takes in x and y values, then the number of points (or connections) you want for your LBF\nplt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))\nplt.show()\n\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
import sys
from PIL import Image
from pr_common import *
file_name = sys.argv[1]
saturation_color = sys.argv[2]
saturation_modifier = int(sys.argv[3])
img = getImage(file_name)
pixels = pixelValues(img)
for i in range(img.height):
for j in range(img.width):
pixel_val = pixels[i][j]
color_idx = None
if (saturation_color == "R"):
color_idx = 0
elif (saturation_color == "G"):
color_idx = 1
elif (saturation_color == "B"):
color_idx = 2
color_val = pixel_val[color_idx] + saturation_modifier
if (color_val > 255):
color_val = 255
pixel_list = list(pixel_val)
pixel_list[color_idx] = color_val
pixels[i][j] = tuple(pixel_list)
savePixelsToImage(editedFilePath(file_name, "saturated"), pixels)
|
normal
|
{
"blob_id": "96ef95d8997eeab3d85a1bb6e4f8c86c9bfbb0a2",
"index": 4732,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in range(img.height):\n for j in range(img.width):\n pixel_val = pixels[i][j]\n color_idx = None\n if saturation_color == 'R':\n color_idx = 0\n elif saturation_color == 'G':\n color_idx = 1\n elif saturation_color == 'B':\n color_idx = 2\n color_val = pixel_val[color_idx] + saturation_modifier\n if color_val > 255:\n color_val = 255\n pixel_list = list(pixel_val)\n pixel_list[color_idx] = color_val\n pixels[i][j] = tuple(pixel_list)\nsavePixelsToImage(editedFilePath(file_name, 'saturated'), pixels)\n",
"step-3": "<mask token>\nfile_name = sys.argv[1]\nsaturation_color = sys.argv[2]\nsaturation_modifier = int(sys.argv[3])\nimg = getImage(file_name)\npixels = pixelValues(img)\nfor i in range(img.height):\n for j in range(img.width):\n pixel_val = pixels[i][j]\n color_idx = None\n if saturation_color == 'R':\n color_idx = 0\n elif saturation_color == 'G':\n color_idx = 1\n elif saturation_color == 'B':\n color_idx = 2\n color_val = pixel_val[color_idx] + saturation_modifier\n if color_val > 255:\n color_val = 255\n pixel_list = list(pixel_val)\n pixel_list[color_idx] = color_val\n pixels[i][j] = tuple(pixel_list)\nsavePixelsToImage(editedFilePath(file_name, 'saturated'), pixels)\n",
"step-4": "import sys\nfrom PIL import Image\nfrom pr_common import *\nfile_name = sys.argv[1]\nsaturation_color = sys.argv[2]\nsaturation_modifier = int(sys.argv[3])\nimg = getImage(file_name)\npixels = pixelValues(img)\nfor i in range(img.height):\n for j in range(img.width):\n pixel_val = pixels[i][j]\n color_idx = None\n if saturation_color == 'R':\n color_idx = 0\n elif saturation_color == 'G':\n color_idx = 1\n elif saturation_color == 'B':\n color_idx = 2\n color_val = pixel_val[color_idx] + saturation_modifier\n if color_val > 255:\n color_val = 255\n pixel_list = list(pixel_val)\n pixel_list[color_idx] = color_val\n pixels[i][j] = tuple(pixel_list)\nsavePixelsToImage(editedFilePath(file_name, 'saturated'), pixels)\n",
"step-5": "import sys\nfrom PIL import Image\nfrom pr_common import *\n\nfile_name = sys.argv[1]\nsaturation_color = sys.argv[2]\nsaturation_modifier = int(sys.argv[3])\n\nimg = getImage(file_name)\npixels = pixelValues(img)\n\nfor i in range(img.height):\n for j in range(img.width):\n pixel_val = pixels[i][j]\n color_idx = None\n\n if (saturation_color == \"R\"):\n color_idx = 0\n elif (saturation_color == \"G\"):\n color_idx = 1\n elif (saturation_color == \"B\"):\n color_idx = 2\n\n color_val = pixel_val[color_idx] + saturation_modifier\n \n if (color_val > 255):\n color_val = 255\n \n pixel_list = list(pixel_val)\n pixel_list[color_idx] = color_val\n pixels[i][j] = tuple(pixel_list)\n\nsavePixelsToImage(editedFilePath(file_name, \"saturated\"), pixels)\n ",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
class SophiesAI(Player):
<|reserved_special_token_0|>
def ship_locations(self) ->Sequence[Tuple[int, int, int, bool]]:
return [(2, 0, 0, True)]
<|reserved_special_token_0|>
def bomb_feedback(self, x: int, y: int, result: ShotResult):
pass
def bombed_feedback(self, x: int, y: int, result: ShotResult):
pass
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class SophiesAI(Player):
<|reserved_special_token_0|>
def ship_locations(self) ->Sequence[Tuple[int, int, int, bool]]:
return [(2, 0, 0, True)]
def drop_bomb(self) ->Tuple[int, int]:
return randint(0, self.size - 1), randint(0, self.size - 1)
def bomb_feedback(self, x: int, y: int, result: ShotResult):
pass
def bombed_feedback(self, x: int, y: int, result: ShotResult):
pass
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class SophiesAI(Player):
"""Sophie Tan's Random Shot Magic."""
def ship_locations(self) ->Sequence[Tuple[int, int, int, bool]]:
return [(2, 0, 0, True)]
def drop_bomb(self) ->Tuple[int, int]:
return randint(0, self.size - 1), randint(0, self.size - 1)
def bomb_feedback(self, x: int, y: int, result: ShotResult):
pass
def bombed_feedback(self, x: int, y: int, result: ShotResult):
pass
<|reserved_special_token_1|>
<|reserved_special_token_0|>
from typing import Sequence, Tuple
from battleships import Player, ShotResult
from random import randint
class SophiesAI(Player):
"""Sophie Tan's Random Shot Magic."""
def ship_locations(self) ->Sequence[Tuple[int, int, int, bool]]:
return [(2, 0, 0, True)]
def drop_bomb(self) ->Tuple[int, int]:
return randint(0, self.size - 1), randint(0, self.size - 1)
def bomb_feedback(self, x: int, y: int, result: ShotResult):
pass
def bombed_feedback(self, x: int, y: int, result: ShotResult):
pass
<|reserved_special_token_1|>
"""Sophie Tan's special AI."""
from typing import Sequence, Tuple
from battleships import Player, ShotResult
from random import randint
class SophiesAI(Player):
"""Sophie Tan's Random Shot Magic."""
def ship_locations(self) -> Sequence[Tuple[int, int, int, bool]]:
return [(2, 0, 0, True)]
def drop_bomb(self) -> Tuple[int, int]:
return randint(0, self.size - 1), randint(0, self.size - 1)
def bomb_feedback(self, x: int, y: int, result: ShotResult):
pass
def bombed_feedback(self, x: int, y: int, result: ShotResult):
pass
|
flexible
|
{
"blob_id": "127bf47de554dd397d18c6a70616a2a4d93cae80",
"index": 3659,
"step-1": "<mask token>\n\n\nclass SophiesAI(Player):\n <mask token>\n\n def ship_locations(self) ->Sequence[Tuple[int, int, int, bool]]:\n return [(2, 0, 0, True)]\n <mask token>\n\n def bomb_feedback(self, x: int, y: int, result: ShotResult):\n pass\n\n def bombed_feedback(self, x: int, y: int, result: ShotResult):\n pass\n",
"step-2": "<mask token>\n\n\nclass SophiesAI(Player):\n <mask token>\n\n def ship_locations(self) ->Sequence[Tuple[int, int, int, bool]]:\n return [(2, 0, 0, True)]\n\n def drop_bomb(self) ->Tuple[int, int]:\n return randint(0, self.size - 1), randint(0, self.size - 1)\n\n def bomb_feedback(self, x: int, y: int, result: ShotResult):\n pass\n\n def bombed_feedback(self, x: int, y: int, result: ShotResult):\n pass\n",
"step-3": "<mask token>\n\n\nclass SophiesAI(Player):\n \"\"\"Sophie Tan's Random Shot Magic.\"\"\"\n\n def ship_locations(self) ->Sequence[Tuple[int, int, int, bool]]:\n return [(2, 0, 0, True)]\n\n def drop_bomb(self) ->Tuple[int, int]:\n return randint(0, self.size - 1), randint(0, self.size - 1)\n\n def bomb_feedback(self, x: int, y: int, result: ShotResult):\n pass\n\n def bombed_feedback(self, x: int, y: int, result: ShotResult):\n pass\n",
"step-4": "<mask token>\nfrom typing import Sequence, Tuple\nfrom battleships import Player, ShotResult\nfrom random import randint\n\n\nclass SophiesAI(Player):\n \"\"\"Sophie Tan's Random Shot Magic.\"\"\"\n\n def ship_locations(self) ->Sequence[Tuple[int, int, int, bool]]:\n return [(2, 0, 0, True)]\n\n def drop_bomb(self) ->Tuple[int, int]:\n return randint(0, self.size - 1), randint(0, self.size - 1)\n\n def bomb_feedback(self, x: int, y: int, result: ShotResult):\n pass\n\n def bombed_feedback(self, x: int, y: int, result: ShotResult):\n pass\n",
"step-5": "\"\"\"Sophie Tan's special AI.\"\"\"\nfrom typing import Sequence, Tuple\n\nfrom battleships import Player, ShotResult\nfrom random import randint\n\n\nclass SophiesAI(Player):\n \"\"\"Sophie Tan's Random Shot Magic.\"\"\"\n\n def ship_locations(self) -> Sequence[Tuple[int, int, int, bool]]:\n return [(2, 0, 0, True)]\n\n def drop_bomb(self) -> Tuple[int, int]:\n return randint(0, self.size - 1), randint(0, self.size - 1)\n\n def bomb_feedback(self, x: int, y: int, result: ShotResult):\n pass\n\n def bombed_feedback(self, x: int, y: int, result: ShotResult):\n pass\n",
"step-ids": [
4,
5,
6,
7,
8
]
}
|
[
4,
5,
6,
7,
8
] |
import sys
sys.path.append("..\\Pole_IA_Systemes_Experts")
from tkinter import *
from Knowledge_base.Facts import Fact
from Knowledge_base.Rules import Rule
from Backward.Explanation_tree import *
def ask_about_fact(fact: Fact):
"""
Asks the user about whether a fact is true or false threw an interface provided by tkinter
Args:
fact (Fact): the fact we want to know about
Returns:
bool: true if the fact is true, false otherwise
"""
window = Tk()
window.title("Question !")
Label(window, text=fact.description, font=("Arial", 18)).grid(padx="1c", pady=("0.5c", "1c"), columnspan=3)
def fact_is_true():
global boolean
boolean = True
window.quit()
window.destroy()
def fact_not_true():
global boolean
boolean = False
window.quit()
window.destroy()
Button(window, text="Vrai", fg="green", command=fact_is_true, width="15") \
.grid(column=0, row=1, padx="0.5c", pady="0.5c")
Button(window, text="Ne sais pas", fg="black", command=fact_not_true, width="15") \
.grid(column=1, row=1, padx="0.5c", pady="0.5c")
Button(window, text="Faux", fg="red", command=fact_not_true, width="15") \
.grid(column=2, row=1, padx="0.5c", pady="0.5c")
window.mainloop()
try:
return boolean
except NameError:
return False
def show_result(goal: Fact, description: str, true_fact: bool, facts: list, used_rules: list):
"""
Displays the result of the inference engine and the explanation of the facts and rules used to reach this conclusion
Args:
goal (Fact): the fact understudy
description (String): the explanation of the rules and facts used
true_fact (bool): is True if the goal is verified, False otherwise
facts (list[fact]): list of the known facts
used_rules (list[Rule]): list of the rules that have been used
"""
root = Tk()
root.title("Résultat !")
if true_fact:
Label(root, text=goal.description, font=("Arial", 18)) \
.grid(padx="1c", pady="1c")
Label(root, text="car {}".format(description), font=("Arial", 10)) \
.grid(row=1, padx="1c", pady="1c")
else:
Label(root, text="Impossible à dire", font=("Arial", 18)) \
.grid(padx="1c", pady="1c")
display_explanation_tree(facts, used_rules, root)
root.mainloop()
|
normal
|
{
"blob_id": "4dae34b7c90f52314aac5e457addb3700ffcbd28",
"index": 9156,
"step-1": "<mask token>\n\n\ndef ask_about_fact(fact: Fact):\n \"\"\"\n Asks the user about whether a fact is true or false threw an interface provided by tkinter\n Args:\n fact (Fact): the fact we want to know about\n\n Returns:\n bool: true if the fact is true, false otherwise\n \"\"\"\n window = Tk()\n window.title('Question !')\n Label(window, text=fact.description, font=('Arial', 18)).grid(padx='1c',\n pady=('0.5c', '1c'), columnspan=3)\n\n def fact_is_true():\n global boolean\n boolean = True\n window.quit()\n window.destroy()\n\n def fact_not_true():\n global boolean\n boolean = False\n window.quit()\n window.destroy()\n Button(window, text='Vrai', fg='green', command=fact_is_true, width='15'\n ).grid(column=0, row=1, padx='0.5c', pady='0.5c')\n Button(window, text='Ne sais pas', fg='black', command=fact_not_true,\n width='15').grid(column=1, row=1, padx='0.5c', pady='0.5c')\n Button(window, text='Faux', fg='red', command=fact_not_true, width='15'\n ).grid(column=2, row=1, padx='0.5c', pady='0.5c')\n window.mainloop()\n try:\n return boolean\n except NameError:\n return False\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef ask_about_fact(fact: Fact):\n \"\"\"\n Asks the user about whether a fact is true or false threw an interface provided by tkinter\n Args:\n fact (Fact): the fact we want to know about\n\n Returns:\n bool: true if the fact is true, false otherwise\n \"\"\"\n window = Tk()\n window.title('Question !')\n Label(window, text=fact.description, font=('Arial', 18)).grid(padx='1c',\n pady=('0.5c', '1c'), columnspan=3)\n\n def fact_is_true():\n global boolean\n boolean = True\n window.quit()\n window.destroy()\n\n def fact_not_true():\n global boolean\n boolean = False\n window.quit()\n window.destroy()\n Button(window, text='Vrai', fg='green', command=fact_is_true, width='15'\n ).grid(column=0, row=1, padx='0.5c', pady='0.5c')\n Button(window, text='Ne sais pas', fg='black', command=fact_not_true,\n width='15').grid(column=1, row=1, padx='0.5c', pady='0.5c')\n Button(window, text='Faux', fg='red', command=fact_not_true, width='15'\n ).grid(column=2, row=1, padx='0.5c', pady='0.5c')\n window.mainloop()\n try:\n return boolean\n except NameError:\n return False\n\n\ndef show_result(goal: Fact, description: str, true_fact: bool, facts: list,\n used_rules: list):\n \"\"\"\n Displays the result of the inference engine and the explanation of the facts and rules used to reach this conclusion\n Args:\n goal (Fact): the fact understudy\n description (String): the explanation of the rules and facts used\n true_fact (bool): is True if the goal is verified, False otherwise\n facts (list[fact]): list of the known facts\n used_rules (list[Rule]): list of the rules that have been used\n \"\"\"\n root = Tk()\n root.title('Résultat !')\n if true_fact:\n Label(root, text=goal.description, font=('Arial', 18)).grid(padx=\n '1c', pady='1c')\n Label(root, text='car {}'.format(description), font=('Arial', 10)\n ).grid(row=1, padx='1c', pady='1c')\n else:\n Label(root, text='Impossible à dire', font=('Arial', 18)).grid(padx\n ='1c', pady='1c')\n display_explanation_tree(facts, used_rules, root)\n root.mainloop()\n",
"step-3": "<mask token>\nsys.path.append('..\\\\Pole_IA_Systemes_Experts')\n<mask token>\n\n\ndef ask_about_fact(fact: Fact):\n \"\"\"\n Asks the user about whether a fact is true or false threw an interface provided by tkinter\n Args:\n fact (Fact): the fact we want to know about\n\n Returns:\n bool: true if the fact is true, false otherwise\n \"\"\"\n window = Tk()\n window.title('Question !')\n Label(window, text=fact.description, font=('Arial', 18)).grid(padx='1c',\n pady=('0.5c', '1c'), columnspan=3)\n\n def fact_is_true():\n global boolean\n boolean = True\n window.quit()\n window.destroy()\n\n def fact_not_true():\n global boolean\n boolean = False\n window.quit()\n window.destroy()\n Button(window, text='Vrai', fg='green', command=fact_is_true, width='15'\n ).grid(column=0, row=1, padx='0.5c', pady='0.5c')\n Button(window, text='Ne sais pas', fg='black', command=fact_not_true,\n width='15').grid(column=1, row=1, padx='0.5c', pady='0.5c')\n Button(window, text='Faux', fg='red', command=fact_not_true, width='15'\n ).grid(column=2, row=1, padx='0.5c', pady='0.5c')\n window.mainloop()\n try:\n return boolean\n except NameError:\n return False\n\n\ndef show_result(goal: Fact, description: str, true_fact: bool, facts: list,\n used_rules: list):\n \"\"\"\n Displays the result of the inference engine and the explanation of the facts and rules used to reach this conclusion\n Args:\n goal (Fact): the fact understudy\n description (String): the explanation of the rules and facts used\n true_fact (bool): is True if the goal is verified, False otherwise\n facts (list[fact]): list of the known facts\n used_rules (list[Rule]): list of the rules that have been used\n \"\"\"\n root = Tk()\n root.title('Résultat !')\n if true_fact:\n Label(root, text=goal.description, font=('Arial', 18)).grid(padx=\n '1c', pady='1c')\n Label(root, text='car {}'.format(description), font=('Arial', 10)\n ).grid(row=1, padx='1c', pady='1c')\n else:\n Label(root, text='Impossible à dire', font=('Arial', 18)).grid(padx\n ='1c', pady='1c')\n display_explanation_tree(facts, used_rules, root)\n root.mainloop()\n",
"step-4": "import sys\nsys.path.append('..\\\\Pole_IA_Systemes_Experts')\nfrom tkinter import *\nfrom Knowledge_base.Facts import Fact\nfrom Knowledge_base.Rules import Rule\nfrom Backward.Explanation_tree import *\n\n\ndef ask_about_fact(fact: Fact):\n \"\"\"\n Asks the user about whether a fact is true or false threw an interface provided by tkinter\n Args:\n fact (Fact): the fact we want to know about\n\n Returns:\n bool: true if the fact is true, false otherwise\n \"\"\"\n window = Tk()\n window.title('Question !')\n Label(window, text=fact.description, font=('Arial', 18)).grid(padx='1c',\n pady=('0.5c', '1c'), columnspan=3)\n\n def fact_is_true():\n global boolean\n boolean = True\n window.quit()\n window.destroy()\n\n def fact_not_true():\n global boolean\n boolean = False\n window.quit()\n window.destroy()\n Button(window, text='Vrai', fg='green', command=fact_is_true, width='15'\n ).grid(column=0, row=1, padx='0.5c', pady='0.5c')\n Button(window, text='Ne sais pas', fg='black', command=fact_not_true,\n width='15').grid(column=1, row=1, padx='0.5c', pady='0.5c')\n Button(window, text='Faux', fg='red', command=fact_not_true, width='15'\n ).grid(column=2, row=1, padx='0.5c', pady='0.5c')\n window.mainloop()\n try:\n return boolean\n except NameError:\n return False\n\n\ndef show_result(goal: Fact, description: str, true_fact: bool, facts: list,\n used_rules: list):\n \"\"\"\n Displays the result of the inference engine and the explanation of the facts and rules used to reach this conclusion\n Args:\n goal (Fact): the fact understudy\n description (String): the explanation of the rules and facts used\n true_fact (bool): is True if the goal is verified, False otherwise\n facts (list[fact]): list of the known facts\n used_rules (list[Rule]): list of the rules that have been used\n \"\"\"\n root = Tk()\n root.title('Résultat !')\n if true_fact:\n Label(root, text=goal.description, font=('Arial', 18)).grid(padx=\n '1c', pady='1c')\n Label(root, text='car {}'.format(description), font=('Arial', 10)\n ).grid(row=1, padx='1c', pady='1c')\n else:\n Label(root, text='Impossible à dire', font=('Arial', 18)).grid(padx\n ='1c', pady='1c')\n display_explanation_tree(facts, used_rules, root)\n root.mainloop()\n",
"step-5": "import sys\n\nsys.path.append(\"..\\\\Pole_IA_Systemes_Experts\")\nfrom tkinter import *\nfrom Knowledge_base.Facts import Fact\nfrom Knowledge_base.Rules import Rule\nfrom Backward.Explanation_tree import *\n\n\ndef ask_about_fact(fact: Fact):\n \"\"\"\n Asks the user about whether a fact is true or false threw an interface provided by tkinter\n Args:\n fact (Fact): the fact we want to know about\n\n Returns:\n bool: true if the fact is true, false otherwise\n \"\"\"\n \n window = Tk()\n window.title(\"Question !\")\n \n Label(window, text=fact.description, font=(\"Arial\", 18)).grid(padx=\"1c\", pady=(\"0.5c\", \"1c\"), columnspan=3)\n \n def fact_is_true():\n global boolean\n boolean = True\n window.quit()\n window.destroy()\n \n def fact_not_true():\n global boolean\n boolean = False\n window.quit()\n window.destroy()\n \n Button(window, text=\"Vrai\", fg=\"green\", command=fact_is_true, width=\"15\") \\\n .grid(column=0, row=1, padx=\"0.5c\", pady=\"0.5c\")\n \n Button(window, text=\"Ne sais pas\", fg=\"black\", command=fact_not_true, width=\"15\") \\\n .grid(column=1, row=1, padx=\"0.5c\", pady=\"0.5c\")\n \n Button(window, text=\"Faux\", fg=\"red\", command=fact_not_true, width=\"15\") \\\n .grid(column=2, row=1, padx=\"0.5c\", pady=\"0.5c\")\n \n window.mainloop()\n \n try:\n return boolean\n except NameError:\n return False\n\n\ndef show_result(goal: Fact, description: str, true_fact: bool, facts: list, used_rules: list):\n \"\"\"\n Displays the result of the inference engine and the explanation of the facts and rules used to reach this conclusion\n Args:\n goal (Fact): the fact understudy\n description (String): the explanation of the rules and facts used\n true_fact (bool): is True if the goal is verified, False otherwise\n facts (list[fact]): list of the known facts\n used_rules (list[Rule]): list of the rules that have been used\n \"\"\"\n root = Tk()\n root.title(\"Résultat !\")\n \n if true_fact:\n Label(root, text=goal.description, font=(\"Arial\", 18)) \\\n .grid(padx=\"1c\", pady=\"1c\")\n \n Label(root, text=\"car {}\".format(description), font=(\"Arial\", 10)) \\\n .grid(row=1, padx=\"1c\", pady=\"1c\")\n \n else:\n Label(root, text=\"Impossible à dire\", font=(\"Arial\", 18)) \\\n .grid(padx=\"1c\", pady=\"1c\")\n \n display_explanation_tree(facts, used_rules, root)\n \n root.mainloop()\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
a = 1
b = 2
print(a + b)
print("hello")
list = [1, 2, 3, 4, 5]
for i in list:
if i % 2 != 0:
print(i)
print("branch")
|
normal
|
{
"blob_id": "03b325094bd3e77f467e17ce54deb95bf2b5c727",
"index": 1724,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(a + b)\nprint('hello')\n<mask token>\nfor i in list:\n if i % 2 != 0:\n print(i)\nprint('branch')\n",
"step-3": "a = 1\nb = 2\nprint(a + b)\nprint('hello')\nlist = [1, 2, 3, 4, 5]\nfor i in list:\n if i % 2 != 0:\n print(i)\nprint('branch')\n",
"step-4": "a = 1\nb = 2\nprint(a + b)\nprint(\"hello\")\n\nlist = [1, 2, 3, 4, 5]\n\nfor i in list:\n if i % 2 != 0:\n print(i)\nprint(\"branch\")",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
def clicked(num):
current = ent.get()
ent.delete(0, END)
ent.insert(0, str(current) + str(num))
def click_clear():
ent.delete(0, END)
def add():
global ch
ch = '+'
clicked('+')
def subtract():
global ch
ch = '-'
clicked('-')
def multiply():
global ch
ch = '*'
clicked('*')
def divide():
global ch
ch = '/'
clicked('/')
def equals():
f_num, s_num = ent.get().split(ch)
res = c.calculate(float(f_num), float(s_num), ch)
ent.delete(0, END)
ent.insert(0, res)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
root.title('CALCULATOR')
<|reserved_special_token_0|>
ent.grid(row=0, column=0, columnspan=3, padx=10, pady=10)
<|reserved_special_token_0|>
def clicked(num):
current = ent.get()
ent.delete(0, END)
ent.insert(0, str(current) + str(num))
def click_clear():
ent.delete(0, END)
def add():
global ch
ch = '+'
clicked('+')
def subtract():
global ch
ch = '-'
clicked('-')
def multiply():
global ch
ch = '*'
clicked('*')
def divide():
global ch
ch = '/'
clicked('/')
def equals():
f_num, s_num = ent.get().split(ch)
res = c.calculate(float(f_num), float(s_num), ch)
ent.delete(0, END)
ent.insert(0, res)
<|reserved_special_token_0|>
but7.grid(row=1, column=0)
but8.grid(row=1, column=1)
but9.grid(row=1, column=2)
but4.grid(row=2, column=0)
but5.grid(row=2, column=1)
but6.grid(row=2, column=2)
but1.grid(row=3, column=0)
but2.grid(row=3, column=1)
but3.grid(row=3, column=2)
but0.grid(row=4, column=0)
but_plus.grid(row=5, column=0)
but_sub.grid(row=6, column=0)
but_mul.grid(row=6, column=1)
but_div.grid(row=6, column=2)
but_eq.grid(row=4, column=1, columnspan=2)
but_clr.grid(row=5, column=1, columnspan=2)
root.mainloop()
<|reserved_special_token_1|>
<|reserved_special_token_0|>
root = Tk()
root.title('CALCULATOR')
ent = Entry(root, width=35)
ent.grid(row=0, column=0, columnspan=3, padx=10, pady=10)
ch = ''
num = ent.get()
def clicked(num):
current = ent.get()
ent.delete(0, END)
ent.insert(0, str(current) + str(num))
def click_clear():
ent.delete(0, END)
def add():
global ch
ch = '+'
clicked('+')
def subtract():
global ch
ch = '-'
clicked('-')
def multiply():
global ch
ch = '*'
clicked('*')
def divide():
global ch
ch = '/'
clicked('/')
def equals():
f_num, s_num = ent.get().split(ch)
res = c.calculate(float(f_num), float(s_num), ch)
ent.delete(0, END)
ent.insert(0, res)
but1 = Button(root, text='1', padx=40, pady=20, command=lambda : clicked(1))
but2 = Button(root, text='2', padx=40, pady=20, command=lambda : clicked(2))
but3 = Button(root, text='3', padx=40, pady=20, command=lambda : clicked(3))
but4 = Button(root, text='4', padx=40, pady=20, command=lambda : clicked(4))
but5 = Button(root, text='5', padx=40, pady=20, command=lambda : clicked(5))
but6 = Button(root, text='6', padx=40, pady=20, command=lambda : clicked(6))
but7 = Button(root, text='7', padx=40, pady=20, command=lambda : clicked(7))
but8 = Button(root, text='8', padx=40, pady=20, command=lambda : clicked(8))
but9 = Button(root, text='9', padx=40, pady=20, command=lambda : clicked(9))
but0 = Button(root, text='0', padx=40, pady=20, command=lambda : clicked(0))
but_plus = Button(root, text='+', padx=39, pady=20, command=add)
but_sub = Button(root, text='-', padx=40, pady=20, command=subtract)
but_mul = Button(root, text='*', padx=40, pady=20, command=multiply)
but_div = Button(root, text='/', padx=40, pady=20, command=divide)
but_eq = Button(root, text='=', padx=89, pady=20, command=equals)
but_clr = Button(root, text='C', padx=89, pady=20, command=click_clear)
but7.grid(row=1, column=0)
but8.grid(row=1, column=1)
but9.grid(row=1, column=2)
but4.grid(row=2, column=0)
but5.grid(row=2, column=1)
but6.grid(row=2, column=2)
but1.grid(row=3, column=0)
but2.grid(row=3, column=1)
but3.grid(row=3, column=2)
but0.grid(row=4, column=0)
but_plus.grid(row=5, column=0)
but_sub.grid(row=6, column=0)
but_mul.grid(row=6, column=1)
but_div.grid(row=6, column=2)
but_eq.grid(row=4, column=1, columnspan=2)
but_clr.grid(row=5, column=1, columnspan=2)
root.mainloop()
<|reserved_special_token_1|>
from tkinter import *
import mathcalc as c
root = Tk()
root.title('CALCULATOR')
ent = Entry(root, width=35)
ent.grid(row=0, column=0, columnspan=3, padx=10, pady=10)
ch = ''
num = ent.get()
def clicked(num):
current = ent.get()
ent.delete(0, END)
ent.insert(0, str(current) + str(num))
def click_clear():
ent.delete(0, END)
def add():
global ch
ch = '+'
clicked('+')
def subtract():
global ch
ch = '-'
clicked('-')
def multiply():
global ch
ch = '*'
clicked('*')
def divide():
global ch
ch = '/'
clicked('/')
def equals():
f_num, s_num = ent.get().split(ch)
res = c.calculate(float(f_num), float(s_num), ch)
ent.delete(0, END)
ent.insert(0, res)
but1 = Button(root, text='1', padx=40, pady=20, command=lambda : clicked(1))
but2 = Button(root, text='2', padx=40, pady=20, command=lambda : clicked(2))
but3 = Button(root, text='3', padx=40, pady=20, command=lambda : clicked(3))
but4 = Button(root, text='4', padx=40, pady=20, command=lambda : clicked(4))
but5 = Button(root, text='5', padx=40, pady=20, command=lambda : clicked(5))
but6 = Button(root, text='6', padx=40, pady=20, command=lambda : clicked(6))
but7 = Button(root, text='7', padx=40, pady=20, command=lambda : clicked(7))
but8 = Button(root, text='8', padx=40, pady=20, command=lambda : clicked(8))
but9 = Button(root, text='9', padx=40, pady=20, command=lambda : clicked(9))
but0 = Button(root, text='0', padx=40, pady=20, command=lambda : clicked(0))
but_plus = Button(root, text='+', padx=39, pady=20, command=add)
but_sub = Button(root, text='-', padx=40, pady=20, command=subtract)
but_mul = Button(root, text='*', padx=40, pady=20, command=multiply)
but_div = Button(root, text='/', padx=40, pady=20, command=divide)
but_eq = Button(root, text='=', padx=89, pady=20, command=equals)
but_clr = Button(root, text='C', padx=89, pady=20, command=click_clear)
but7.grid(row=1, column=0)
but8.grid(row=1, column=1)
but9.grid(row=1, column=2)
but4.grid(row=2, column=0)
but5.grid(row=2, column=1)
but6.grid(row=2, column=2)
but1.grid(row=3, column=0)
but2.grid(row=3, column=1)
but3.grid(row=3, column=2)
but0.grid(row=4, column=0)
but_plus.grid(row=5, column=0)
but_sub.grid(row=6, column=0)
but_mul.grid(row=6, column=1)
but_div.grid(row=6, column=2)
but_eq.grid(row=4, column=1, columnspan=2)
but_clr.grid(row=5, column=1, columnspan=2)
root.mainloop()
<|reserved_special_token_1|>
from tkinter import *
import mathcalc as c
root= Tk()
root.title("CALCULATOR")
ent=Entry(root,width=35)
ent.grid(row=0,column=0,columnspan=3,padx=10,pady=10)
#ent.grid(row=0,column=0)
ch=''
num=ent.get()
def clicked(num):
current=ent.get()
ent.delete(0,END)
ent.insert(0,str(current)+str(num))
def click_clear():
ent.delete(0,END)
def add():
global ch
ch='+'
clicked('+')
def subtract():
global ch
ch='-'
clicked('-')
def multiply():
global ch
ch='*'
clicked('*')
def divide():
global ch
ch='/'
clicked('/')
def equals():
f_num,s_num=ent.get().split(ch)
res=c.calculate(float(f_num),float(s_num),ch)
ent.delete(0,END)
ent.insert(0,res)
#buttons
but1=Button(root,text="1",padx=40,pady=20,command=lambda: clicked(1))
but2=Button(root,text="2",padx=40,pady=20,command=lambda: clicked(2))
but3=Button(root,text="3",padx=40,pady=20,command=lambda: clicked(3))
but4=Button(root,text="4",padx=40,pady=20,command=lambda: clicked(4))
but5=Button(root,text="5",padx=40,pady=20,command=lambda: clicked(5))
but6=Button(root,text="6",padx=40,pady=20,command=lambda: clicked(6))
but7=Button(root,text="7",padx=40,pady=20,command=lambda: clicked(7))
but8=Button(root,text="8",padx=40,pady=20,command=lambda: clicked(8))
but9=Button(root,text="9",padx=40,pady=20,command=lambda: clicked(9))
but0=Button(root,text="0",padx=40,pady=20,command=lambda: clicked(0))
but_plus=Button(root,text="+",padx=39,pady=20,command=add)
but_sub=Button(root,text="-",padx=40,pady=20,command=subtract)
but_mul=Button(root,text="*",padx=40,pady=20,command=multiply)
but_div=Button(root,text="/",padx=40,pady=20,command=divide)
but_eq=Button(root,text="=",padx=89,pady=20,command=equals)
but_clr=Button(root,text="C",padx=89,pady=20,command=click_clear)
#button place
but7.grid(row=1,column=0)
but8.grid(row=1,column=1)
but9.grid(row=1,column=2)
but4.grid(row=2,column=0)
but5.grid(row=2,column=1)
but6.grid(row=2,column=2)
but1.grid(row=3,column=0)
but2.grid(row=3,column=1)
but3.grid(row=3,column=2)
but0.grid(row=4,column=0)
but_plus.grid(row=5,column=0)
but_sub.grid(row=6,column=0)
but_mul.grid(row=6,column=1)
but_div.grid(row=6,column=2)
but_eq.grid(row=4,column=1,columnspan=2)
but_clr.grid(row=5,column=1,columnspan=2)
root.mainloop()
|
flexible
|
{
"blob_id": "bdd9ebfa9a2f14d57efd527ca88032bfb0160a5e",
"index": 7504,
"step-1": "<mask token>\n\n\ndef clicked(num):\n current = ent.get()\n ent.delete(0, END)\n ent.insert(0, str(current) + str(num))\n\n\ndef click_clear():\n ent.delete(0, END)\n\n\ndef add():\n global ch\n ch = '+'\n clicked('+')\n\n\ndef subtract():\n global ch\n ch = '-'\n clicked('-')\n\n\ndef multiply():\n global ch\n ch = '*'\n clicked('*')\n\n\ndef divide():\n global ch\n ch = '/'\n clicked('/')\n\n\ndef equals():\n f_num, s_num = ent.get().split(ch)\n res = c.calculate(float(f_num), float(s_num), ch)\n ent.delete(0, END)\n ent.insert(0, res)\n\n\n<mask token>\n",
"step-2": "<mask token>\nroot.title('CALCULATOR')\n<mask token>\nent.grid(row=0, column=0, columnspan=3, padx=10, pady=10)\n<mask token>\n\n\ndef clicked(num):\n current = ent.get()\n ent.delete(0, END)\n ent.insert(0, str(current) + str(num))\n\n\ndef click_clear():\n ent.delete(0, END)\n\n\ndef add():\n global ch\n ch = '+'\n clicked('+')\n\n\ndef subtract():\n global ch\n ch = '-'\n clicked('-')\n\n\ndef multiply():\n global ch\n ch = '*'\n clicked('*')\n\n\ndef divide():\n global ch\n ch = '/'\n clicked('/')\n\n\ndef equals():\n f_num, s_num = ent.get().split(ch)\n res = c.calculate(float(f_num), float(s_num), ch)\n ent.delete(0, END)\n ent.insert(0, res)\n\n\n<mask token>\nbut7.grid(row=1, column=0)\nbut8.grid(row=1, column=1)\nbut9.grid(row=1, column=2)\nbut4.grid(row=2, column=0)\nbut5.grid(row=2, column=1)\nbut6.grid(row=2, column=2)\nbut1.grid(row=3, column=0)\nbut2.grid(row=3, column=1)\nbut3.grid(row=3, column=2)\nbut0.grid(row=4, column=0)\nbut_plus.grid(row=5, column=0)\nbut_sub.grid(row=6, column=0)\nbut_mul.grid(row=6, column=1)\nbut_div.grid(row=6, column=2)\nbut_eq.grid(row=4, column=1, columnspan=2)\nbut_clr.grid(row=5, column=1, columnspan=2)\nroot.mainloop()\n",
"step-3": "<mask token>\nroot = Tk()\nroot.title('CALCULATOR')\nent = Entry(root, width=35)\nent.grid(row=0, column=0, columnspan=3, padx=10, pady=10)\nch = ''\nnum = ent.get()\n\n\ndef clicked(num):\n current = ent.get()\n ent.delete(0, END)\n ent.insert(0, str(current) + str(num))\n\n\ndef click_clear():\n ent.delete(0, END)\n\n\ndef add():\n global ch\n ch = '+'\n clicked('+')\n\n\ndef subtract():\n global ch\n ch = '-'\n clicked('-')\n\n\ndef multiply():\n global ch\n ch = '*'\n clicked('*')\n\n\ndef divide():\n global ch\n ch = '/'\n clicked('/')\n\n\ndef equals():\n f_num, s_num = ent.get().split(ch)\n res = c.calculate(float(f_num), float(s_num), ch)\n ent.delete(0, END)\n ent.insert(0, res)\n\n\nbut1 = Button(root, text='1', padx=40, pady=20, command=lambda : clicked(1))\nbut2 = Button(root, text='2', padx=40, pady=20, command=lambda : clicked(2))\nbut3 = Button(root, text='3', padx=40, pady=20, command=lambda : clicked(3))\nbut4 = Button(root, text='4', padx=40, pady=20, command=lambda : clicked(4))\nbut5 = Button(root, text='5', padx=40, pady=20, command=lambda : clicked(5))\nbut6 = Button(root, text='6', padx=40, pady=20, command=lambda : clicked(6))\nbut7 = Button(root, text='7', padx=40, pady=20, command=lambda : clicked(7))\nbut8 = Button(root, text='8', padx=40, pady=20, command=lambda : clicked(8))\nbut9 = Button(root, text='9', padx=40, pady=20, command=lambda : clicked(9))\nbut0 = Button(root, text='0', padx=40, pady=20, command=lambda : clicked(0))\nbut_plus = Button(root, text='+', padx=39, pady=20, command=add)\nbut_sub = Button(root, text='-', padx=40, pady=20, command=subtract)\nbut_mul = Button(root, text='*', padx=40, pady=20, command=multiply)\nbut_div = Button(root, text='/', padx=40, pady=20, command=divide)\nbut_eq = Button(root, text='=', padx=89, pady=20, command=equals)\nbut_clr = Button(root, text='C', padx=89, pady=20, command=click_clear)\nbut7.grid(row=1, column=0)\nbut8.grid(row=1, column=1)\nbut9.grid(row=1, column=2)\nbut4.grid(row=2, column=0)\nbut5.grid(row=2, column=1)\nbut6.grid(row=2, column=2)\nbut1.grid(row=3, column=0)\nbut2.grid(row=3, column=1)\nbut3.grid(row=3, column=2)\nbut0.grid(row=4, column=0)\nbut_plus.grid(row=5, column=0)\nbut_sub.grid(row=6, column=0)\nbut_mul.grid(row=6, column=1)\nbut_div.grid(row=6, column=2)\nbut_eq.grid(row=4, column=1, columnspan=2)\nbut_clr.grid(row=5, column=1, columnspan=2)\nroot.mainloop()\n",
"step-4": "from tkinter import *\nimport mathcalc as c\nroot = Tk()\nroot.title('CALCULATOR')\nent = Entry(root, width=35)\nent.grid(row=0, column=0, columnspan=3, padx=10, pady=10)\nch = ''\nnum = ent.get()\n\n\ndef clicked(num):\n current = ent.get()\n ent.delete(0, END)\n ent.insert(0, str(current) + str(num))\n\n\ndef click_clear():\n ent.delete(0, END)\n\n\ndef add():\n global ch\n ch = '+'\n clicked('+')\n\n\ndef subtract():\n global ch\n ch = '-'\n clicked('-')\n\n\ndef multiply():\n global ch\n ch = '*'\n clicked('*')\n\n\ndef divide():\n global ch\n ch = '/'\n clicked('/')\n\n\ndef equals():\n f_num, s_num = ent.get().split(ch)\n res = c.calculate(float(f_num), float(s_num), ch)\n ent.delete(0, END)\n ent.insert(0, res)\n\n\nbut1 = Button(root, text='1', padx=40, pady=20, command=lambda : clicked(1))\nbut2 = Button(root, text='2', padx=40, pady=20, command=lambda : clicked(2))\nbut3 = Button(root, text='3', padx=40, pady=20, command=lambda : clicked(3))\nbut4 = Button(root, text='4', padx=40, pady=20, command=lambda : clicked(4))\nbut5 = Button(root, text='5', padx=40, pady=20, command=lambda : clicked(5))\nbut6 = Button(root, text='6', padx=40, pady=20, command=lambda : clicked(6))\nbut7 = Button(root, text='7', padx=40, pady=20, command=lambda : clicked(7))\nbut8 = Button(root, text='8', padx=40, pady=20, command=lambda : clicked(8))\nbut9 = Button(root, text='9', padx=40, pady=20, command=lambda : clicked(9))\nbut0 = Button(root, text='0', padx=40, pady=20, command=lambda : clicked(0))\nbut_plus = Button(root, text='+', padx=39, pady=20, command=add)\nbut_sub = Button(root, text='-', padx=40, pady=20, command=subtract)\nbut_mul = Button(root, text='*', padx=40, pady=20, command=multiply)\nbut_div = Button(root, text='/', padx=40, pady=20, command=divide)\nbut_eq = Button(root, text='=', padx=89, pady=20, command=equals)\nbut_clr = Button(root, text='C', padx=89, pady=20, command=click_clear)\nbut7.grid(row=1, column=0)\nbut8.grid(row=1, column=1)\nbut9.grid(row=1, column=2)\nbut4.grid(row=2, column=0)\nbut5.grid(row=2, column=1)\nbut6.grid(row=2, column=2)\nbut1.grid(row=3, column=0)\nbut2.grid(row=3, column=1)\nbut3.grid(row=3, column=2)\nbut0.grid(row=4, column=0)\nbut_plus.grid(row=5, column=0)\nbut_sub.grid(row=6, column=0)\nbut_mul.grid(row=6, column=1)\nbut_div.grid(row=6, column=2)\nbut_eq.grid(row=4, column=1, columnspan=2)\nbut_clr.grid(row=5, column=1, columnspan=2)\nroot.mainloop()\n",
"step-5": "from tkinter import *\r\nimport mathcalc as c \r\nroot= Tk()\r\nroot.title(\"CALCULATOR\")\r\nent=Entry(root,width=35)\r\nent.grid(row=0,column=0,columnspan=3,padx=10,pady=10)\r\n#ent.grid(row=0,column=0)\r\nch=''\r\nnum=ent.get()\r\ndef clicked(num):\r\n\tcurrent=ent.get()\r\n\tent.delete(0,END)\r\n\tent.insert(0,str(current)+str(num))\r\ndef click_clear():\r\n\tent.delete(0,END)\r\n\r\ndef add():\r\n\tglobal ch\r\n\tch='+' \r\n\tclicked('+')\r\n\r\ndef subtract():\r\n\tglobal ch\r\n\tch='-' \r\n\tclicked('-')\r\n\r\ndef multiply():\r\n\tglobal ch\r\n\tch='*' \r\n\tclicked('*')\r\n\r\ndef divide():\r\n\tglobal ch\r\n\tch='/' \r\n\tclicked('/')\r\ndef equals():\r\n\tf_num,s_num=ent.get().split(ch)\r\n\tres=c.calculate(float(f_num),float(s_num),ch)\r\n\tent.delete(0,END)\r\n\tent.insert(0,res)\r\n\r\n#buttons\r\nbut1=Button(root,text=\"1\",padx=40,pady=20,command=lambda: clicked(1))\r\nbut2=Button(root,text=\"2\",padx=40,pady=20,command=lambda: clicked(2))\r\nbut3=Button(root,text=\"3\",padx=40,pady=20,command=lambda: clicked(3))\r\nbut4=Button(root,text=\"4\",padx=40,pady=20,command=lambda: clicked(4))\r\nbut5=Button(root,text=\"5\",padx=40,pady=20,command=lambda: clicked(5))\r\nbut6=Button(root,text=\"6\",padx=40,pady=20,command=lambda: clicked(6))\r\nbut7=Button(root,text=\"7\",padx=40,pady=20,command=lambda: clicked(7))\r\nbut8=Button(root,text=\"8\",padx=40,pady=20,command=lambda: clicked(8))\r\nbut9=Button(root,text=\"9\",padx=40,pady=20,command=lambda: clicked(9))\r\nbut0=Button(root,text=\"0\",padx=40,pady=20,command=lambda: clicked(0))\r\n\r\nbut_plus=Button(root,text=\"+\",padx=39,pady=20,command=add)\r\nbut_sub=Button(root,text=\"-\",padx=40,pady=20,command=subtract)\r\nbut_mul=Button(root,text=\"*\",padx=40,pady=20,command=multiply)\r\nbut_div=Button(root,text=\"/\",padx=40,pady=20,command=divide)\r\nbut_eq=Button(root,text=\"=\",padx=89,pady=20,command=equals)\r\nbut_clr=Button(root,text=\"C\",padx=89,pady=20,command=click_clear)\r\n#button place\r\nbut7.grid(row=1,column=0)\r\nbut8.grid(row=1,column=1)\r\nbut9.grid(row=1,column=2)\r\n\r\nbut4.grid(row=2,column=0)\r\nbut5.grid(row=2,column=1)\r\nbut6.grid(row=2,column=2)\r\n\r\nbut1.grid(row=3,column=0)\r\nbut2.grid(row=3,column=1)\r\nbut3.grid(row=3,column=2)\r\n\r\nbut0.grid(row=4,column=0)\r\nbut_plus.grid(row=5,column=0)\r\nbut_sub.grid(row=6,column=0)\r\nbut_mul.grid(row=6,column=1)\r\nbut_div.grid(row=6,column=2)\r\nbut_eq.grid(row=4,column=1,columnspan=2)\r\nbut_clr.grid(row=5,column=1,columnspan=2)\r\nroot.mainloop()\r\n",
"step-ids": [
7,
8,
9,
10,
11
]
}
|
[
7,
8,
9,
10,
11
] |
<|reserved_special_token_0|>
class Divide(APIView):
renderer_classes = JSONPRenderer,
@staticmethod
def get(request):
try:
first_number = int(request.GET.get('a'))
second_number = int(request.GET.get('b'))
return Response({'result': first_number / second_number})
except Exception as e:
return Response({'result': 'there was an error ' + str(e)})
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Multiply(APIView):
<|reserved_special_token_0|>
@staticmethod
def get(request):
form = NameForm()
return render(request, 'name.html', {'form': form})
@staticmethod
def post(request):
form = NameForm(request.POST)
if form.is_valid():
a = form.cleaned_data['one']
b = form.cleaned_data['second']
data = multiply(a, b)
return render(request, 'name.html', {'data': data})
else:
return render(request, 'name.html', {'data': 'error'})
class Divide(APIView):
renderer_classes = JSONPRenderer,
@staticmethod
def get(request):
try:
first_number = int(request.GET.get('a'))
second_number = int(request.GET.get('b'))
return Response({'result': first_number / second_number})
except Exception as e:
return Response({'result': 'there was an error ' + str(e)})
<|reserved_special_token_1|>
<|reserved_special_token_0|>
__author__ = 'jhonjairoroa87'
<|reserved_special_token_0|>
def multiply(a, b):
return a * b
class Multiply(APIView):
renderer_classes = JSONPRenderer,
@staticmethod
def get(request):
form = NameForm()
return render(request, 'name.html', {'form': form})
@staticmethod
def post(request):
form = NameForm(request.POST)
if form.is_valid():
a = form.cleaned_data['one']
b = form.cleaned_data['second']
data = multiply(a, b)
return render(request, 'name.html', {'data': data})
else:
return render(request, 'name.html', {'data': 'error'})
class Divide(APIView):
renderer_classes = JSONPRenderer,
@staticmethod
def get(request):
try:
first_number = int(request.GET.get('a'))
second_number = int(request.GET.get('b'))
return Response({'result': first_number / second_number})
except Exception as e:
return Response({'result': 'there was an error ' + str(e)})
<|reserved_special_token_1|>
from django.http import HttpResponseRedirect
from django.shortcuts import render
__author__ = 'jhonjairoroa87'
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework_jsonp.renderers import JSONPRenderer
from django.db import models
from .form import NameForm
def multiply(a, b):
return a * b
class Multiply(APIView):
renderer_classes = JSONPRenderer,
@staticmethod
def get(request):
form = NameForm()
return render(request, 'name.html', {'form': form})
@staticmethod
def post(request):
form = NameForm(request.POST)
if form.is_valid():
a = form.cleaned_data['one']
b = form.cleaned_data['second']
data = multiply(a, b)
return render(request, 'name.html', {'data': data})
else:
return render(request, 'name.html', {'data': 'error'})
class Divide(APIView):
renderer_classes = JSONPRenderer,
@staticmethod
def get(request):
try:
first_number = int(request.GET.get('a'))
second_number = int(request.GET.get('b'))
return Response({'result': first_number / second_number})
except Exception as e:
return Response({'result': 'there was an error ' + str(e)})
<|reserved_special_token_1|>
from django.http import HttpResponseRedirect
from django.shortcuts import render
__author__ = 'jhonjairoroa87'
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework_jsonp.renderers import JSONPRenderer
from django.db import models
from .form import NameForm
def multiply(a,b):
return a*b
class Multiply(APIView):
renderer_classes = (JSONPRenderer,)
@staticmethod
def get(request):
form = NameForm()
return render(request, 'name.html', {'form': form})
@staticmethod
def post(request):
form = NameForm(request.POST)
if form.is_valid():
a = form.cleaned_data['one']
b = form.cleaned_data['second']
data = multiply(a, b)
return render(request, 'name.html', {'data': data})
else:
return render(request, 'name.html', {'data': "error"})
class Divide(APIView):
renderer_classes = (JSONPRenderer,)
@staticmethod
def get(request):
try:
first_number = int(request.GET.get('a'))
second_number = int(request.GET.get('b'))
return Response({'result': first_number / second_number})
except Exception as e:
return Response({'result': 'there was an error ' + str(e)})
|
flexible
|
{
"blob_id": "4c483636316dfa660f10b1aba900813bc3e95ebe",
"index": 9463,
"step-1": "<mask token>\n\n\nclass Divide(APIView):\n renderer_classes = JSONPRenderer,\n\n @staticmethod\n def get(request):\n try:\n first_number = int(request.GET.get('a'))\n second_number = int(request.GET.get('b'))\n return Response({'result': first_number / second_number})\n except Exception as e:\n return Response({'result': 'there was an error ' + str(e)})\n",
"step-2": "<mask token>\n\n\nclass Multiply(APIView):\n <mask token>\n\n @staticmethod\n def get(request):\n form = NameForm()\n return render(request, 'name.html', {'form': form})\n\n @staticmethod\n def post(request):\n form = NameForm(request.POST)\n if form.is_valid():\n a = form.cleaned_data['one']\n b = form.cleaned_data['second']\n data = multiply(a, b)\n return render(request, 'name.html', {'data': data})\n else:\n return render(request, 'name.html', {'data': 'error'})\n\n\nclass Divide(APIView):\n renderer_classes = JSONPRenderer,\n\n @staticmethod\n def get(request):\n try:\n first_number = int(request.GET.get('a'))\n second_number = int(request.GET.get('b'))\n return Response({'result': first_number / second_number})\n except Exception as e:\n return Response({'result': 'there was an error ' + str(e)})\n",
"step-3": "<mask token>\n__author__ = 'jhonjairoroa87'\n<mask token>\n\n\ndef multiply(a, b):\n return a * b\n\n\nclass Multiply(APIView):\n renderer_classes = JSONPRenderer,\n\n @staticmethod\n def get(request):\n form = NameForm()\n return render(request, 'name.html', {'form': form})\n\n @staticmethod\n def post(request):\n form = NameForm(request.POST)\n if form.is_valid():\n a = form.cleaned_data['one']\n b = form.cleaned_data['second']\n data = multiply(a, b)\n return render(request, 'name.html', {'data': data})\n else:\n return render(request, 'name.html', {'data': 'error'})\n\n\nclass Divide(APIView):\n renderer_classes = JSONPRenderer,\n\n @staticmethod\n def get(request):\n try:\n first_number = int(request.GET.get('a'))\n second_number = int(request.GET.get('b'))\n return Response({'result': first_number / second_number})\n except Exception as e:\n return Response({'result': 'there was an error ' + str(e)})\n",
"step-4": "from django.http import HttpResponseRedirect\nfrom django.shortcuts import render\n__author__ = 'jhonjairoroa87'\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework_jsonp.renderers import JSONPRenderer\nfrom django.db import models\nfrom .form import NameForm\n\n\ndef multiply(a, b):\n return a * b\n\n\nclass Multiply(APIView):\n renderer_classes = JSONPRenderer,\n\n @staticmethod\n def get(request):\n form = NameForm()\n return render(request, 'name.html', {'form': form})\n\n @staticmethod\n def post(request):\n form = NameForm(request.POST)\n if form.is_valid():\n a = form.cleaned_data['one']\n b = form.cleaned_data['second']\n data = multiply(a, b)\n return render(request, 'name.html', {'data': data})\n else:\n return render(request, 'name.html', {'data': 'error'})\n\n\nclass Divide(APIView):\n renderer_classes = JSONPRenderer,\n\n @staticmethod\n def get(request):\n try:\n first_number = int(request.GET.get('a'))\n second_number = int(request.GET.get('b'))\n return Response({'result': first_number / second_number})\n except Exception as e:\n return Response({'result': 'there was an error ' + str(e)})\n",
"step-5": "from django.http import HttpResponseRedirect\nfrom django.shortcuts import render\n\n__author__ = 'jhonjairoroa87'\n\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework_jsonp.renderers import JSONPRenderer\nfrom django.db import models\nfrom .form import NameForm\n\n\ndef multiply(a,b):\n return a*b\n\nclass Multiply(APIView):\n\n renderer_classes = (JSONPRenderer,)\n\n @staticmethod\n def get(request):\n form = NameForm()\n\n return render(request, 'name.html', {'form': form})\n\n @staticmethod\n def post(request):\n form = NameForm(request.POST)\n if form.is_valid():\n a = form.cleaned_data['one']\n b = form.cleaned_data['second']\n data = multiply(a, b)\n return render(request, 'name.html', {'data': data})\n else:\n return render(request, 'name.html', {'data': \"error\"})\n\n\nclass Divide(APIView):\n\n renderer_classes = (JSONPRenderer,)\n\n @staticmethod\n def get(request):\n try:\n first_number = int(request.GET.get('a'))\n second_number = int(request.GET.get('b'))\n return Response({'result': first_number / second_number})\n except Exception as e:\n return Response({'result': 'there was an error ' + str(e)})\n\n",
"step-ids": [
3,
6,
9,
10,
11
]
}
|
[
3,
6,
9,
10,
11
] |
<|reserved_special_token_0|>
class UserProfileAdmin(admin.ModelAdmin):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
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'
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class UserProfileAdmin(admin.ModelAdmin):
list_display = [i.name for i in UserProfile._meta.fields]
<|reserved_special_token_0|>
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'
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
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)
<|reserved_special_token_1|>
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)
<|reserved_special_token_1|>
#!/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)
|
flexible
|
{
"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|>
class RegistrationFormCaseInsensitive(RegistrationForm):
<|reserved_special_token_0|>
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields[User.USERNAME_FIELD].validators.append(validators.
CaseInsensitiveUnique(User, User.USERNAME_FIELD, validators.
DUPLICATE_USERNAME))
class RegistrationFormTermsOfService(RegistrationForm):
"""
Subclass of ``RegistrationForm`` which adds a required checkbox
for agreeing to a site's Terms of Service.
"""
tos = forms.BooleanField(widget=forms.CheckboxInput, label=_(
'I have read and agree to the Terms of Service'), error_messages={
'required': validators.TOS_REQUIRED})
class RegistrationFormUniqueEmail(RegistrationForm):
"""
Subclass of ``RegistrationForm`` which enforces uniqueness of
email addresses.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
email_field = User.get_email_field_name()
self.fields[email_field].validators.append(validators.
CaseInsensitiveUnique(User, email_field, validators.
DUPLICATE_EMAIL))
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class RegistrationForm(UserCreationForm):
<|reserved_special_token_0|>
class Meta(UserCreationForm.Meta):
fields = [User.USERNAME_FIELD, User.get_email_field_name(),
'password1', 'password2']
error_css_class = 'error'
required_css_class = 'required'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
email_field = User.get_email_field_name()
if hasattr(self, 'reserved_names'):
reserved_names = self.reserved_names
else:
reserved_names = validators.DEFAULT_RESERVED_NAMES
username_validators = [validators.ReservedNameValidator(
reserved_names), validators.validate_confusables]
self.fields[User.USERNAME_FIELD].validators.extend(username_validators)
self.fields[email_field].validators = [validators.
HTML5EmailValidator(), validators.validate_confusables_email]
self.fields[email_field].required = True
class RegistrationFormCaseInsensitive(RegistrationForm):
"""
Subclass of ``RegistrationForm`` enforcing case-insensitive
uniqueness of usernames.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields[User.USERNAME_FIELD].validators.append(validators.
CaseInsensitiveUnique(User, User.USERNAME_FIELD, validators.
DUPLICATE_USERNAME))
class RegistrationFormTermsOfService(RegistrationForm):
"""
Subclass of ``RegistrationForm`` which adds a required checkbox
for agreeing to a site's Terms of Service.
"""
tos = forms.BooleanField(widget=forms.CheckboxInput, label=_(
'I have read and agree to the Terms of Service'), error_messages={
'required': validators.TOS_REQUIRED})
class RegistrationFormUniqueEmail(RegistrationForm):
"""
Subclass of ``RegistrationForm`` which enforces uniqueness of
email addresses.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
email_field = User.get_email_field_name()
self.fields[email_field].validators.append(validators.
CaseInsensitiveUnique(User, email_field, validators.
DUPLICATE_EMAIL))
<|reserved_special_token_1|>
<|reserved_special_token_0|>
User = get_user_model()
class RegistrationForm(UserCreationForm):
"""
Form for registering a new user account.
Validates that the requested username is not already in use, and
requires the password to be entered twice to catch typos.
Subclasses should feel free to add any additional validation they
need, but should take care when overriding ``save()`` to respect
the ``commit=False`` argument, as several registration workflows
will make use of it to create inactive user accounts.
"""
class Meta(UserCreationForm.Meta):
fields = [User.USERNAME_FIELD, User.get_email_field_name(),
'password1', 'password2']
error_css_class = 'error'
required_css_class = 'required'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
email_field = User.get_email_field_name()
if hasattr(self, 'reserved_names'):
reserved_names = self.reserved_names
else:
reserved_names = validators.DEFAULT_RESERVED_NAMES
username_validators = [validators.ReservedNameValidator(
reserved_names), validators.validate_confusables]
self.fields[User.USERNAME_FIELD].validators.extend(username_validators)
self.fields[email_field].validators = [validators.
HTML5EmailValidator(), validators.validate_confusables_email]
self.fields[email_field].required = True
class RegistrationFormCaseInsensitive(RegistrationForm):
"""
Subclass of ``RegistrationForm`` enforcing case-insensitive
uniqueness of usernames.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields[User.USERNAME_FIELD].validators.append(validators.
CaseInsensitiveUnique(User, User.USERNAME_FIELD, validators.
DUPLICATE_USERNAME))
class RegistrationFormTermsOfService(RegistrationForm):
"""
Subclass of ``RegistrationForm`` which adds a required checkbox
for agreeing to a site's Terms of Service.
"""
tos = forms.BooleanField(widget=forms.CheckboxInput, label=_(
'I have read and agree to the Terms of Service'), error_messages={
'required': validators.TOS_REQUIRED})
class RegistrationFormUniqueEmail(RegistrationForm):
"""
Subclass of ``RegistrationForm`` which enforces uniqueness of
email addresses.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
email_field = User.get_email_field_name()
self.fields[email_field].validators.append(validators.
CaseInsensitiveUnique(User, email_field, validators.
DUPLICATE_EMAIL))
<|reserved_special_token_1|>
<|reserved_special_token_0|>
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
from django.utils.translation import gettext_lazy as _
from . import validators
User = get_user_model()
class RegistrationForm(UserCreationForm):
"""
Form for registering a new user account.
Validates that the requested username is not already in use, and
requires the password to be entered twice to catch typos.
Subclasses should feel free to add any additional validation they
need, but should take care when overriding ``save()`` to respect
the ``commit=False`` argument, as several registration workflows
will make use of it to create inactive user accounts.
"""
class Meta(UserCreationForm.Meta):
fields = [User.USERNAME_FIELD, User.get_email_field_name(),
'password1', 'password2']
error_css_class = 'error'
required_css_class = 'required'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
email_field = User.get_email_field_name()
if hasattr(self, 'reserved_names'):
reserved_names = self.reserved_names
else:
reserved_names = validators.DEFAULT_RESERVED_NAMES
username_validators = [validators.ReservedNameValidator(
reserved_names), validators.validate_confusables]
self.fields[User.USERNAME_FIELD].validators.extend(username_validators)
self.fields[email_field].validators = [validators.
HTML5EmailValidator(), validators.validate_confusables_email]
self.fields[email_field].required = True
class RegistrationFormCaseInsensitive(RegistrationForm):
"""
Subclass of ``RegistrationForm`` enforcing case-insensitive
uniqueness of usernames.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields[User.USERNAME_FIELD].validators.append(validators.
CaseInsensitiveUnique(User, User.USERNAME_FIELD, validators.
DUPLICATE_USERNAME))
class RegistrationFormTermsOfService(RegistrationForm):
"""
Subclass of ``RegistrationForm`` which adds a required checkbox
for agreeing to a site's Terms of Service.
"""
tos = forms.BooleanField(widget=forms.CheckboxInput, label=_(
'I have read and agree to the Terms of Service'), error_messages={
'required': validators.TOS_REQUIRED})
class RegistrationFormUniqueEmail(RegistrationForm):
"""
Subclass of ``RegistrationForm`` which enforces uniqueness of
email addresses.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
email_field = User.get_email_field_name()
self.fields[email_field].validators.append(validators.
CaseInsensitiveUnique(User, email_field, validators.
DUPLICATE_EMAIL))
<|reserved_special_token_1|>
"""
Forms and validation code for user registration.
Note that all of these forms assume your user model is similar in
structure to Django's default User class. If your user model is
significantly different, you may need to write your own form class;
see the documentation for notes on custom user models with
django-registration.
"""
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
from django.utils.translation import gettext_lazy as _
from . import validators
User = get_user_model()
class RegistrationForm(UserCreationForm):
"""
Form for registering a new user account.
Validates that the requested username is not already in use, and
requires the password to be entered twice to catch typos.
Subclasses should feel free to add any additional validation they
need, but should take care when overriding ``save()`` to respect
the ``commit=False`` argument, as several registration workflows
will make use of it to create inactive user accounts.
"""
# pylint: disable=too-few-public-methods
class Meta(UserCreationForm.Meta):
fields = [
User.USERNAME_FIELD,
User.get_email_field_name(),
"password1",
"password2",
]
error_css_class = "error"
required_css_class = "required"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
email_field = User.get_email_field_name()
if hasattr(self, "reserved_names"):
reserved_names = self.reserved_names
else:
reserved_names = validators.DEFAULT_RESERVED_NAMES
username_validators = [
validators.ReservedNameValidator(reserved_names),
validators.validate_confusables,
]
self.fields[User.USERNAME_FIELD].validators.extend(username_validators)
# django-registration's email validation is significantly stricter than Django's
# default email validation, which means that leaving Django's default validation
# on only causes confusion due to duplicate error messages (see GitHub issue
# #238). So we apply only the django-registration validators, not the default
# Django validator, on the email field.
self.fields[email_field].validators = [
validators.HTML5EmailValidator(),
validators.validate_confusables_email,
]
self.fields[email_field].required = True
class RegistrationFormCaseInsensitive(RegistrationForm):
"""
Subclass of ``RegistrationForm`` enforcing case-insensitive
uniqueness of usernames.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields[User.USERNAME_FIELD].validators.append(
validators.CaseInsensitiveUnique(
User, User.USERNAME_FIELD, validators.DUPLICATE_USERNAME
)
)
class RegistrationFormTermsOfService(RegistrationForm):
"""
Subclass of ``RegistrationForm`` which adds a required checkbox
for agreeing to a site's Terms of Service.
"""
tos = forms.BooleanField(
widget=forms.CheckboxInput,
label=_("I have read and agree to the Terms of Service"),
error_messages={"required": validators.TOS_REQUIRED},
)
class RegistrationFormUniqueEmail(RegistrationForm):
"""
Subclass of ``RegistrationForm`` which enforces uniqueness of
email addresses.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
email_field = User.get_email_field_name()
self.fields[email_field].validators.append(
validators.CaseInsensitiveUnique(
User, email_field, validators.DUPLICATE_EMAIL
)
)
|
flexible
|
{
"blob_id": "3b959481f7c818ec35b8af174b1982954b4c72eb",
"index": 1208,
"step-1": "<mask token>\n\n\nclass RegistrationFormCaseInsensitive(RegistrationForm):\n <mask token>\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields[User.USERNAME_FIELD].validators.append(validators.\n CaseInsensitiveUnique(User, User.USERNAME_FIELD, validators.\n DUPLICATE_USERNAME))\n\n\nclass RegistrationFormTermsOfService(RegistrationForm):\n \"\"\"\n Subclass of ``RegistrationForm`` which adds a required checkbox\n for agreeing to a site's Terms of Service.\n\n \"\"\"\n tos = forms.BooleanField(widget=forms.CheckboxInput, label=_(\n 'I have read and agree to the Terms of Service'), error_messages={\n 'required': validators.TOS_REQUIRED})\n\n\nclass RegistrationFormUniqueEmail(RegistrationForm):\n \"\"\"\n Subclass of ``RegistrationForm`` which enforces uniqueness of\n email addresses.\n\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n email_field = User.get_email_field_name()\n self.fields[email_field].validators.append(validators.\n CaseInsensitiveUnique(User, email_field, validators.\n DUPLICATE_EMAIL))\n",
"step-2": "<mask token>\n\n\nclass RegistrationForm(UserCreationForm):\n <mask token>\n\n\n class Meta(UserCreationForm.Meta):\n fields = [User.USERNAME_FIELD, User.get_email_field_name(),\n 'password1', 'password2']\n error_css_class = 'error'\n required_css_class = 'required'\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n email_field = User.get_email_field_name()\n if hasattr(self, 'reserved_names'):\n reserved_names = self.reserved_names\n else:\n reserved_names = validators.DEFAULT_RESERVED_NAMES\n username_validators = [validators.ReservedNameValidator(\n reserved_names), validators.validate_confusables]\n self.fields[User.USERNAME_FIELD].validators.extend(username_validators)\n self.fields[email_field].validators = [validators.\n HTML5EmailValidator(), validators.validate_confusables_email]\n self.fields[email_field].required = True\n\n\nclass RegistrationFormCaseInsensitive(RegistrationForm):\n \"\"\"\n Subclass of ``RegistrationForm`` enforcing case-insensitive\n uniqueness of usernames.\n\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields[User.USERNAME_FIELD].validators.append(validators.\n CaseInsensitiveUnique(User, User.USERNAME_FIELD, validators.\n DUPLICATE_USERNAME))\n\n\nclass RegistrationFormTermsOfService(RegistrationForm):\n \"\"\"\n Subclass of ``RegistrationForm`` which adds a required checkbox\n for agreeing to a site's Terms of Service.\n\n \"\"\"\n tos = forms.BooleanField(widget=forms.CheckboxInput, label=_(\n 'I have read and agree to the Terms of Service'), error_messages={\n 'required': validators.TOS_REQUIRED})\n\n\nclass RegistrationFormUniqueEmail(RegistrationForm):\n \"\"\"\n Subclass of ``RegistrationForm`` which enforces uniqueness of\n email addresses.\n\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n email_field = User.get_email_field_name()\n self.fields[email_field].validators.append(validators.\n CaseInsensitiveUnique(User, email_field, validators.\n DUPLICATE_EMAIL))\n",
"step-3": "<mask token>\nUser = get_user_model()\n\n\nclass RegistrationForm(UserCreationForm):\n \"\"\"\n Form for registering a new user account.\n\n Validates that the requested username is not already in use, and\n requires the password to be entered twice to catch typos.\n\n Subclasses should feel free to add any additional validation they\n need, but should take care when overriding ``save()`` to respect\n the ``commit=False`` argument, as several registration workflows\n will make use of it to create inactive user accounts.\n\n \"\"\"\n\n\n class Meta(UserCreationForm.Meta):\n fields = [User.USERNAME_FIELD, User.get_email_field_name(),\n 'password1', 'password2']\n error_css_class = 'error'\n required_css_class = 'required'\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n email_field = User.get_email_field_name()\n if hasattr(self, 'reserved_names'):\n reserved_names = self.reserved_names\n else:\n reserved_names = validators.DEFAULT_RESERVED_NAMES\n username_validators = [validators.ReservedNameValidator(\n reserved_names), validators.validate_confusables]\n self.fields[User.USERNAME_FIELD].validators.extend(username_validators)\n self.fields[email_field].validators = [validators.\n HTML5EmailValidator(), validators.validate_confusables_email]\n self.fields[email_field].required = True\n\n\nclass RegistrationFormCaseInsensitive(RegistrationForm):\n \"\"\"\n Subclass of ``RegistrationForm`` enforcing case-insensitive\n uniqueness of usernames.\n\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields[User.USERNAME_FIELD].validators.append(validators.\n CaseInsensitiveUnique(User, User.USERNAME_FIELD, validators.\n DUPLICATE_USERNAME))\n\n\nclass RegistrationFormTermsOfService(RegistrationForm):\n \"\"\"\n Subclass of ``RegistrationForm`` which adds a required checkbox\n for agreeing to a site's Terms of Service.\n\n \"\"\"\n tos = forms.BooleanField(widget=forms.CheckboxInput, label=_(\n 'I have read and agree to the Terms of Service'), error_messages={\n 'required': validators.TOS_REQUIRED})\n\n\nclass RegistrationFormUniqueEmail(RegistrationForm):\n \"\"\"\n Subclass of ``RegistrationForm`` which enforces uniqueness of\n email addresses.\n\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n email_field = User.get_email_field_name()\n self.fields[email_field].validators.append(validators.\n CaseInsensitiveUnique(User, email_field, validators.\n DUPLICATE_EMAIL))\n",
"step-4": "<mask token>\nfrom django import forms\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.utils.translation import gettext_lazy as _\nfrom . import validators\nUser = get_user_model()\n\n\nclass RegistrationForm(UserCreationForm):\n \"\"\"\n Form for registering a new user account.\n\n Validates that the requested username is not already in use, and\n requires the password to be entered twice to catch typos.\n\n Subclasses should feel free to add any additional validation they\n need, but should take care when overriding ``save()`` to respect\n the ``commit=False`` argument, as several registration workflows\n will make use of it to create inactive user accounts.\n\n \"\"\"\n\n\n class Meta(UserCreationForm.Meta):\n fields = [User.USERNAME_FIELD, User.get_email_field_name(),\n 'password1', 'password2']\n error_css_class = 'error'\n required_css_class = 'required'\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n email_field = User.get_email_field_name()\n if hasattr(self, 'reserved_names'):\n reserved_names = self.reserved_names\n else:\n reserved_names = validators.DEFAULT_RESERVED_NAMES\n username_validators = [validators.ReservedNameValidator(\n reserved_names), validators.validate_confusables]\n self.fields[User.USERNAME_FIELD].validators.extend(username_validators)\n self.fields[email_field].validators = [validators.\n HTML5EmailValidator(), validators.validate_confusables_email]\n self.fields[email_field].required = True\n\n\nclass RegistrationFormCaseInsensitive(RegistrationForm):\n \"\"\"\n Subclass of ``RegistrationForm`` enforcing case-insensitive\n uniqueness of usernames.\n\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields[User.USERNAME_FIELD].validators.append(validators.\n CaseInsensitiveUnique(User, User.USERNAME_FIELD, validators.\n DUPLICATE_USERNAME))\n\n\nclass RegistrationFormTermsOfService(RegistrationForm):\n \"\"\"\n Subclass of ``RegistrationForm`` which adds a required checkbox\n for agreeing to a site's Terms of Service.\n\n \"\"\"\n tos = forms.BooleanField(widget=forms.CheckboxInput, label=_(\n 'I have read and agree to the Terms of Service'), error_messages={\n 'required': validators.TOS_REQUIRED})\n\n\nclass RegistrationFormUniqueEmail(RegistrationForm):\n \"\"\"\n Subclass of ``RegistrationForm`` which enforces uniqueness of\n email addresses.\n\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n email_field = User.get_email_field_name()\n self.fields[email_field].validators.append(validators.\n CaseInsensitiveUnique(User, email_field, validators.\n DUPLICATE_EMAIL))\n",
"step-5": "\"\"\"\nForms and validation code for user registration.\n\nNote that all of these forms assume your user model is similar in\nstructure to Django's default User class. If your user model is\nsignificantly different, you may need to write your own form class;\nsee the documentation for notes on custom user models with\ndjango-registration.\n\n\"\"\"\n\nfrom django import forms\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.utils.translation import gettext_lazy as _\n\nfrom . import validators\n\nUser = get_user_model()\n\n\nclass RegistrationForm(UserCreationForm):\n \"\"\"\n Form for registering a new user account.\n\n Validates that the requested username is not already in use, and\n requires the password to be entered twice to catch typos.\n\n Subclasses should feel free to add any additional validation they\n need, but should take care when overriding ``save()`` to respect\n the ``commit=False`` argument, as several registration workflows\n will make use of it to create inactive user accounts.\n\n \"\"\"\n\n # pylint: disable=too-few-public-methods\n\n class Meta(UserCreationForm.Meta):\n fields = [\n User.USERNAME_FIELD,\n User.get_email_field_name(),\n \"password1\",\n \"password2\",\n ]\n\n error_css_class = \"error\"\n required_css_class = \"required\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n email_field = User.get_email_field_name()\n if hasattr(self, \"reserved_names\"):\n reserved_names = self.reserved_names\n else:\n reserved_names = validators.DEFAULT_RESERVED_NAMES\n username_validators = [\n validators.ReservedNameValidator(reserved_names),\n validators.validate_confusables,\n ]\n self.fields[User.USERNAME_FIELD].validators.extend(username_validators)\n # django-registration's email validation is significantly stricter than Django's\n # default email validation, which means that leaving Django's default validation\n # on only causes confusion due to duplicate error messages (see GitHub issue\n # #238). So we apply only the django-registration validators, not the default\n # Django validator, on the email field.\n self.fields[email_field].validators = [\n validators.HTML5EmailValidator(),\n validators.validate_confusables_email,\n ]\n self.fields[email_field].required = True\n\n\nclass RegistrationFormCaseInsensitive(RegistrationForm):\n \"\"\"\n Subclass of ``RegistrationForm`` enforcing case-insensitive\n uniqueness of usernames.\n\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields[User.USERNAME_FIELD].validators.append(\n validators.CaseInsensitiveUnique(\n User, User.USERNAME_FIELD, validators.DUPLICATE_USERNAME\n )\n )\n\n\nclass RegistrationFormTermsOfService(RegistrationForm):\n \"\"\"\n Subclass of ``RegistrationForm`` which adds a required checkbox\n for agreeing to a site's Terms of Service.\n\n \"\"\"\n\n tos = forms.BooleanField(\n widget=forms.CheckboxInput,\n label=_(\"I have read and agree to the Terms of Service\"),\n error_messages={\"required\": validators.TOS_REQUIRED},\n )\n\n\nclass RegistrationFormUniqueEmail(RegistrationForm):\n \"\"\"\n Subclass of ``RegistrationForm`` which enforces uniqueness of\n email addresses.\n\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n email_field = User.get_email_field_name()\n self.fields[email_field].validators.append(\n validators.CaseInsensitiveUnique(\n User, email_field, validators.DUPLICATE_EMAIL\n )\n )\n",
"step-ids": [
8,
12,
14,
15,
16
]
}
|
[
8,
12,
14,
15,
16
] |
<|reserved_special_token_0|>
def tag(name, *content, cls=None, **attrs):
""" 生成一个或多个HTML标签 """
if cls is not None:
attrs['class'] = cls
if attrs:
attrs_str = ''.join(' %s="%s"' % (attr, value) for attr, value in
attrs.items())
else:
attrs_str = ''
if content:
return '\n'.join('<%s%s>%s</%s>' % (name, attrs_str, c, name) for c in
content)
else:
return '<%s%s />' % (name, attrs_str)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def tag(name, *content, cls=None, **attrs):
""" 生成一个或多个HTML标签 """
if cls is not None:
attrs['class'] = cls
if attrs:
attrs_str = ''.join(' %s="%s"' % (attr, value) for attr, value in
attrs.items())
else:
attrs_str = ''
if content:
return '\n'.join('<%s%s>%s</%s>' % (name, attrs_str, c, name) for c in
content)
else:
return '<%s%s />' % (name, attrs_str)
print(tag.__defaults__, tag.__code__, tag.__code__.co_varnames, tag.
__code__.co_argcount, sep='\n')
print()
<|reserved_special_token_0|>
print(sig)
for name, param in sig.parameters.items():
print(param.kind, ':', name, '=', param.default)
print()
<|reserved_special_token_0|>
print(bound_args)
for name, value in bound_args.arguments.items():
print(name, '=', value)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def tag(name, *content, cls=None, **attrs):
""" 生成一个或多个HTML标签 """
if cls is not None:
attrs['class'] = cls
if attrs:
attrs_str = ''.join(' %s="%s"' % (attr, value) for attr, value in
attrs.items())
else:
attrs_str = ''
if content:
return '\n'.join('<%s%s>%s</%s>' % (name, attrs_str, c, name) for c in
content)
else:
return '<%s%s />' % (name, attrs_str)
print(tag.__defaults__, tag.__code__, tag.__code__.co_varnames, tag.
__code__.co_argcount, sep='\n')
print()
<|reserved_special_token_0|>
sig = signature(tag)
print(sig)
for name, param in sig.parameters.items():
print(param.kind, ':', name, '=', param.default)
print()
my_tag = {'name': 'img', 'title': 'Sunset', 'src': 'sunset.jpg', 'cls':
'framed'}
bound_args = sig.bind(**my_tag)
print(bound_args)
for name, value in bound_args.arguments.items():
print(name, '=', value)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def tag(name, *content, cls=None, **attrs):
""" 生成一个或多个HTML标签 """
if cls is not None:
attrs['class'] = cls
if attrs:
attrs_str = ''.join(' %s="%s"' % (attr, value) for attr, value in
attrs.items())
else:
attrs_str = ''
if content:
return '\n'.join('<%s%s>%s</%s>' % (name, attrs_str, c, name) for c in
content)
else:
return '<%s%s />' % (name, attrs_str)
print(tag.__defaults__, tag.__code__, tag.__code__.co_varnames, tag.
__code__.co_argcount, sep='\n')
print()
from inspect import signature
sig = signature(tag)
print(sig)
for name, param in sig.parameters.items():
print(param.kind, ':', name, '=', param.default)
print()
my_tag = {'name': 'img', 'title': 'Sunset', 'src': 'sunset.jpg', 'cls':
'framed'}
bound_args = sig.bind(**my_tag)
print(bound_args)
for name, value in bound_args.arguments.items():
print(name, '=', value)
<|reserved_special_token_1|>
"""
函数对象有一个__defaults__属性,是保存定位参数和关键字参数默认值的元组,
仅限关键字参数默认值在__kwdefaults__属性中,参数的名称在__code__属性中(__code__本身是对象引用,有很多属性)
使用inspect模块提取函数签名更加方便,很多框架和IDE都是以此来验证代码的
"""
def tag(name, *content, cls=None, **attrs):
""" 生成一个或多个HTML标签 """
if cls is not None:
attrs['class'] = cls
if attrs:
attrs_str = ''.join(' %s="%s"' % (attr, value) for attr, value in attrs.items())
else:
attrs_str = ''
if content:
return '\n'.join('<%s%s>%s</%s>' % (name, attrs_str, c, name) for c in content)
else:
return '<%s%s />' % (name, attrs_str)
print(
tag.__defaults__,
tag.__code__,
tag.__code__.co_varnames,
tag.__code__.co_argcount,
sep = '\n'
)
print()
from inspect import signature
sig = signature(tag)
print(sig)
for name, param in sig.parameters.items(): # name 和 param.name是一样的
print(param.kind, ':', name, '=', param.default)
print()
# signature函数返回的是inspect.Signature对象,它的parameters属性是一个有序映射,这里即sig.parameters,
# 是inspect.Parameter对象,它有name、default、kind,还有annotation属性
# inspect.Signature对象有一个bind方法,可以把任意个参数绑定到签名的形参上
my_tag = {
'name': 'img',
'title': 'Sunset',
'src': 'sunset.jpg',
'cls': 'framed'
}
bound_args = sig.bind(**my_tag)
print(bound_args)
for name, value in bound_args.arguments.items(): # 一个OrderedDict对象
print(name, '=', value)
|
flexible
|
{
"blob_id": "a9b895e4d0830320276359944ca6fdc475fd144e",
"index": 7923,
"step-1": "<mask token>\n\n\ndef tag(name, *content, cls=None, **attrs):\n \"\"\" 生成一个或多个HTML标签 \"\"\"\n if cls is not None:\n attrs['class'] = cls\n if attrs:\n attrs_str = ''.join(' %s=\"%s\"' % (attr, value) for attr, value in\n attrs.items())\n else:\n attrs_str = ''\n if content:\n return '\\n'.join('<%s%s>%s</%s>' % (name, attrs_str, c, name) for c in\n content)\n else:\n return '<%s%s />' % (name, attrs_str)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef tag(name, *content, cls=None, **attrs):\n \"\"\" 生成一个或多个HTML标签 \"\"\"\n if cls is not None:\n attrs['class'] = cls\n if attrs:\n attrs_str = ''.join(' %s=\"%s\"' % (attr, value) for attr, value in\n attrs.items())\n else:\n attrs_str = ''\n if content:\n return '\\n'.join('<%s%s>%s</%s>' % (name, attrs_str, c, name) for c in\n content)\n else:\n return '<%s%s />' % (name, attrs_str)\n\n\nprint(tag.__defaults__, tag.__code__, tag.__code__.co_varnames, tag.\n __code__.co_argcount, sep='\\n')\nprint()\n<mask token>\nprint(sig)\nfor name, param in sig.parameters.items():\n print(param.kind, ':', name, '=', param.default)\nprint()\n<mask token>\nprint(bound_args)\nfor name, value in bound_args.arguments.items():\n print(name, '=', value)\n",
"step-3": "<mask token>\n\n\ndef tag(name, *content, cls=None, **attrs):\n \"\"\" 生成一个或多个HTML标签 \"\"\"\n if cls is not None:\n attrs['class'] = cls\n if attrs:\n attrs_str = ''.join(' %s=\"%s\"' % (attr, value) for attr, value in\n attrs.items())\n else:\n attrs_str = ''\n if content:\n return '\\n'.join('<%s%s>%s</%s>' % (name, attrs_str, c, name) for c in\n content)\n else:\n return '<%s%s />' % (name, attrs_str)\n\n\nprint(tag.__defaults__, tag.__code__, tag.__code__.co_varnames, tag.\n __code__.co_argcount, sep='\\n')\nprint()\n<mask token>\nsig = signature(tag)\nprint(sig)\nfor name, param in sig.parameters.items():\n print(param.kind, ':', name, '=', param.default)\nprint()\nmy_tag = {'name': 'img', 'title': 'Sunset', 'src': 'sunset.jpg', 'cls':\n 'framed'}\nbound_args = sig.bind(**my_tag)\nprint(bound_args)\nfor name, value in bound_args.arguments.items():\n print(name, '=', value)\n",
"step-4": "<mask token>\n\n\ndef tag(name, *content, cls=None, **attrs):\n \"\"\" 生成一个或多个HTML标签 \"\"\"\n if cls is not None:\n attrs['class'] = cls\n if attrs:\n attrs_str = ''.join(' %s=\"%s\"' % (attr, value) for attr, value in\n attrs.items())\n else:\n attrs_str = ''\n if content:\n return '\\n'.join('<%s%s>%s</%s>' % (name, attrs_str, c, name) for c in\n content)\n else:\n return '<%s%s />' % (name, attrs_str)\n\n\nprint(tag.__defaults__, tag.__code__, tag.__code__.co_varnames, tag.\n __code__.co_argcount, sep='\\n')\nprint()\nfrom inspect import signature\nsig = signature(tag)\nprint(sig)\nfor name, param in sig.parameters.items():\n print(param.kind, ':', name, '=', param.default)\nprint()\nmy_tag = {'name': 'img', 'title': 'Sunset', 'src': 'sunset.jpg', 'cls':\n 'framed'}\nbound_args = sig.bind(**my_tag)\nprint(bound_args)\nfor name, value in bound_args.arguments.items():\n print(name, '=', value)\n",
"step-5": "\"\"\"\n函数对象有一个__defaults__属性,是保存定位参数和关键字参数默认值的元组,\n仅限关键字参数默认值在__kwdefaults__属性中,参数的名称在__code__属性中(__code__本身是对象引用,有很多属性)\n\n使用inspect模块提取函数签名更加方便,很多框架和IDE都是以此来验证代码的\n\"\"\"\n\n\ndef tag(name, *content, cls=None, **attrs):\n\t\"\"\" 生成一个或多个HTML标签 \"\"\"\n\tif cls is not None:\n\t\tattrs['class'] = cls\n\tif attrs:\n\t\tattrs_str = ''.join(' %s=\"%s\"' % (attr, value) for attr, value in attrs.items())\n\telse:\n\t\tattrs_str = '' \n\tif content:\n\t\treturn '\\n'.join('<%s%s>%s</%s>' % (name, attrs_str, c, name) for c in content)\n\telse:\n\t\treturn '<%s%s />' % (name, attrs_str)\n\n\nprint(\n\ttag.__defaults__,\n\ttag.__code__, \n\ttag.__code__.co_varnames, \n\ttag.__code__.co_argcount,\n\tsep = '\\n'\n\t)\nprint()\n\nfrom inspect import signature\nsig = signature(tag)\nprint(sig)\nfor name, param in sig.parameters.items(): # name 和 param.name是一样的\n\tprint(param.kind, ':', name, '=', param.default)\nprint()\n# signature函数返回的是inspect.Signature对象,它的parameters属性是一个有序映射,这里即sig.parameters,\n# 是inspect.Parameter对象,它有name、default、kind,还有annotation属性\n\n# inspect.Signature对象有一个bind方法,可以把任意个参数绑定到签名的形参上\nmy_tag = {\n\t\t'name': 'img',\n\t\t'title': 'Sunset',\n\t\t'src': 'sunset.jpg',\n\t\t'cls': 'framed'\n\t}\nbound_args = sig.bind(**my_tag)\nprint(bound_args)\nfor name, value in bound_args.arguments.items(): # 一个OrderedDict对象\n\tprint(name, '=', value)\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import phpserialize
import urllib2
from cache import cache
from config import config
def block(request, limit=None):
try:
links = cache.get_cache("sape", expire=3600).get(key="links", createfunc=load_links)
except:
links = cache.get_cache("sape", expire=300).get(key="links", createfunc=lambda: {})
if request.path in links:
if not hasattr(request, "sape_links_shown"):
request.sape_links_shown = 0
slc = links[request.path][request.sape_links_shown : request.sape_links_shown + limit if limit is not None else None]
request.sape_links_shown += len(slc)
if slc:
return {
"class" : "sape",
"links" : links["__sape_delimiter__"].join(slc),
}
return None
def load_links():
return dict(
map(
lambda path_links: (path_links[0], [link.decode("windows-1251") for link in path_links[1].values()] if isinstance(path_links[1], dict) else path_links[1]),
phpserialize.loads(
urllib2.urlopen(urllib2.Request(
"http://dispenser-01.sape.ru/code.php?user={0}&host={1}".format(config.sape_user_id, config.sape_host)
)).read()
).items()
)
)
|
normal
|
{
"blob_id": "6d5acaa4a60b646432feb59f4d8eb9c9d0dceb0f",
"index": 1151,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef block(request, limit=None):\n try:\n links = cache.get_cache('sape', expire=3600).get(key='links',\n createfunc=load_links)\n except:\n links = cache.get_cache('sape', expire=300).get(key='links',\n createfunc=lambda : {})\n if request.path in links:\n if not hasattr(request, 'sape_links_shown'):\n request.sape_links_shown = 0\n slc = links[request.path][request.sape_links_shown:request.\n sape_links_shown + limit if limit is not None else None]\n request.sape_links_shown += len(slc)\n if slc:\n return {'class': 'sape', 'links': links['__sape_delimiter__'].\n join(slc)}\n return None\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef block(request, limit=None):\n try:\n links = cache.get_cache('sape', expire=3600).get(key='links',\n createfunc=load_links)\n except:\n links = cache.get_cache('sape', expire=300).get(key='links',\n createfunc=lambda : {})\n if request.path in links:\n if not hasattr(request, 'sape_links_shown'):\n request.sape_links_shown = 0\n slc = links[request.path][request.sape_links_shown:request.\n sape_links_shown + limit if limit is not None else None]\n request.sape_links_shown += len(slc)\n if slc:\n return {'class': 'sape', 'links': links['__sape_delimiter__'].\n join(slc)}\n return None\n\n\ndef load_links():\n return dict(map(lambda path_links: (path_links[0], [link.decode(\n 'windows-1251') for link in path_links[1].values()] if isinstance(\n path_links[1], dict) else path_links[1]), phpserialize.loads(\n urllib2.urlopen(urllib2.Request(\n 'http://dispenser-01.sape.ru/code.php?user={0}&host={1}'.format(\n config.sape_user_id, config.sape_host))).read()).items()))\n",
"step-4": "import phpserialize\nimport urllib2\nfrom cache import cache\nfrom config import config\n\n\ndef block(request, limit=None):\n try:\n links = cache.get_cache('sape', expire=3600).get(key='links',\n createfunc=load_links)\n except:\n links = cache.get_cache('sape', expire=300).get(key='links',\n createfunc=lambda : {})\n if request.path in links:\n if not hasattr(request, 'sape_links_shown'):\n request.sape_links_shown = 0\n slc = links[request.path][request.sape_links_shown:request.\n sape_links_shown + limit if limit is not None else None]\n request.sape_links_shown += len(slc)\n if slc:\n return {'class': 'sape', 'links': links['__sape_delimiter__'].\n join(slc)}\n return None\n\n\ndef load_links():\n return dict(map(lambda path_links: (path_links[0], [link.decode(\n 'windows-1251') for link in path_links[1].values()] if isinstance(\n path_links[1], dict) else path_links[1]), phpserialize.loads(\n urllib2.urlopen(urllib2.Request(\n 'http://dispenser-01.sape.ru/code.php?user={0}&host={1}'.format(\n config.sape_user_id, config.sape_host))).read()).items()))\n",
"step-5": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport phpserialize\nimport urllib2\n\nfrom cache import cache\nfrom config import config\n\ndef block(request, limit=None):\n try:\n links = cache.get_cache(\"sape\", expire=3600).get(key=\"links\", createfunc=load_links)\n except:\n links = cache.get_cache(\"sape\", expire=300).get(key=\"links\", createfunc=lambda: {})\n\n if request.path in links:\n if not hasattr(request, \"sape_links_shown\"):\n request.sape_links_shown = 0\n\n slc = links[request.path][request.sape_links_shown : request.sape_links_shown + limit if limit is not None else None]\n request.sape_links_shown += len(slc)\n\n if slc:\n return {\n \"class\" : \"sape\",\n \"links\" : links[\"__sape_delimiter__\"].join(slc),\n }\n\n return None\n\ndef load_links():\n return dict(\n map(\n lambda path_links: (path_links[0], [link.decode(\"windows-1251\") for link in path_links[1].values()] if isinstance(path_links[1], dict) else path_links[1]),\n phpserialize.loads(\n urllib2.urlopen(urllib2.Request(\n \"http://dispenser-01.sape.ru/code.php?user={0}&host={1}\".format(config.sape_user_id, config.sape_host)\n )).read()\n ).items()\n )\n )\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
plt.ion()
parser.add_argument('--fish', help="flag for using fisherman's algorithm")
parser.add_argument('--heat', help='flag for using heatmap')
parser.add_argument('--object', help='flag for dumping the clusters')
<|reserved_special_token_0|>
print(args)
print(args.fish)
print(args.object)
for file in glob.glob('./examples/*.p'):
print(file)
name = file[11:-2]
recover = open('./examples/' + name + '.p', 'rb')
input_list = pickle.load(recover)
print('Loaded ...')
cancer_cells = []
T_cells = []
cyto_T_cells = []
for i, row in enumerate(input_list):
try:
row = [int(x) for x in row]
except ValueError:
continue
if row[4] > 0:
cancer_cells.append([row[0], row[1], row[2], row[3]])
if row[5] > 0:
T_cells.append([row[0], row[1], row[2], row[3]])
if row[6] > 0:
cyto_T_cells.append([row[0], row[1], row[2], row[3]])
cancer_cells = np.asarray(cancer_cells)
T_cells = np.asarray(T_cells)
cyto_T_cells = np.asarray(cyto_T_cells)
print('Separated ...')
t = 25
partitioned_cancer_cells, windows, w, h = partition.partition(cancer_cells,
tile_size=t, to_list=True)
print('Cancer cells partitioned ...')
if args.heat:
spatial_distribution = np.zeros_like(partitioned_cancer_cells)
for i in range(t):
for j in range(t):
spatial_distribution[i][j] = len(partitioned_cancer_cells[i][j]
)
with open('./inputs/spatial/' + name + '.txt', 'w', newline=''
) as dest:
dest.write(str(spatial_distribution))
if args.fish:
result = fishermans_algorithm(partitioned_cancer_cells, (t, t),
windows, w, h)
print('Result retrieved ...')
if args.object:
with open('./inputs/object/' + name + '.p', 'wb') as dest:
pickle.dump(result, dest)
dups = set()
histogram = np.zeros(21, dtype=np.uint32)
for cluster in result:
dups.add(cluster)
total_cluster_cells = 0
clusters_sum = 0
dups_length = len(dups)
for i in dups:
value = len(i.cells)
clusters_sum += value
total_cluster_cells += len(i.cells)
if value > 20:
histogram[20] += 1
else:
histogram[value - 1] += 1
print('Histogram retrieved ...')
clusters_avg = clusters_sum / dups_length
assert total_cluster_cells == len(cancer_cells)
y = np.array(histogram)
x = np.arange(21) + 1
plt.bar(x, y)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.show()
plt.close()
if args.object:
with open('./inputs/object/' + name + '.txt', 'w', newline=''
) as dest:
dest.write('Average size of cluster: ' + str(clusters_avg) +
'\n')
dest.write('Number of clusters: ' + str(len(dups)) + '\n')
dest.write('Total number of cells: ' + str(
total_cluster_cells) + '\n')
dest.write('Cluster counts: ' + '\n')
for i, x in enumerate(histogram):
dest.write(str(i) + ', ' + str(x) + '\n')
os.system('say "All pickle files done in this batch."')
<|reserved_special_token_1|>
<|reserved_special_token_0|>
parser = argparse.ArgumentParser()
plt.ion()
parser.add_argument('--fish', help="flag for using fisherman's algorithm")
parser.add_argument('--heat', help='flag for using heatmap')
parser.add_argument('--object', help='flag for dumping the clusters')
args = parser.parse_args()
print(args)
print(args.fish)
print(args.object)
for file in glob.glob('./examples/*.p'):
print(file)
name = file[11:-2]
recover = open('./examples/' + name + '.p', 'rb')
input_list = pickle.load(recover)
print('Loaded ...')
cancer_cells = []
T_cells = []
cyto_T_cells = []
for i, row in enumerate(input_list):
try:
row = [int(x) for x in row]
except ValueError:
continue
if row[4] > 0:
cancer_cells.append([row[0], row[1], row[2], row[3]])
if row[5] > 0:
T_cells.append([row[0], row[1], row[2], row[3]])
if row[6] > 0:
cyto_T_cells.append([row[0], row[1], row[2], row[3]])
cancer_cells = np.asarray(cancer_cells)
T_cells = np.asarray(T_cells)
cyto_T_cells = np.asarray(cyto_T_cells)
print('Separated ...')
t = 25
partitioned_cancer_cells, windows, w, h = partition.partition(cancer_cells,
tile_size=t, to_list=True)
print('Cancer cells partitioned ...')
if args.heat:
spatial_distribution = np.zeros_like(partitioned_cancer_cells)
for i in range(t):
for j in range(t):
spatial_distribution[i][j] = len(partitioned_cancer_cells[i][j]
)
with open('./inputs/spatial/' + name + '.txt', 'w', newline=''
) as dest:
dest.write(str(spatial_distribution))
if args.fish:
result = fishermans_algorithm(partitioned_cancer_cells, (t, t),
windows, w, h)
print('Result retrieved ...')
if args.object:
with open('./inputs/object/' + name + '.p', 'wb') as dest:
pickle.dump(result, dest)
dups = set()
histogram = np.zeros(21, dtype=np.uint32)
for cluster in result:
dups.add(cluster)
total_cluster_cells = 0
clusters_sum = 0
dups_length = len(dups)
for i in dups:
value = len(i.cells)
clusters_sum += value
total_cluster_cells += len(i.cells)
if value > 20:
histogram[20] += 1
else:
histogram[value - 1] += 1
print('Histogram retrieved ...')
clusters_avg = clusters_sum / dups_length
assert total_cluster_cells == len(cancer_cells)
y = np.array(histogram)
x = np.arange(21) + 1
plt.bar(x, y)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.show()
plt.close()
if args.object:
with open('./inputs/object/' + name + '.txt', 'w', newline=''
) as dest:
dest.write('Average size of cluster: ' + str(clusters_avg) +
'\n')
dest.write('Number of clusters: ' + str(len(dups)) + '\n')
dest.write('Total number of cells: ' + str(
total_cluster_cells) + '\n')
dest.write('Cluster counts: ' + '\n')
for i, x in enumerate(histogram):
dest.write(str(i) + ', ' + str(x) + '\n')
os.system('say "All pickle files done in this batch."')
<|reserved_special_token_1|>
import glob
import os
import partition
import pickle
import matplotlib.pyplot as plt
import numpy as np
from Cluster import fishermans_algorithm
import argparse
parser = argparse.ArgumentParser()
plt.ion()
parser.add_argument('--fish', help="flag for using fisherman's algorithm")
parser.add_argument('--heat', help='flag for using heatmap')
parser.add_argument('--object', help='flag for dumping the clusters')
args = parser.parse_args()
print(args)
print(args.fish)
print(args.object)
for file in glob.glob('./examples/*.p'):
print(file)
name = file[11:-2]
recover = open('./examples/' + name + '.p', 'rb')
input_list = pickle.load(recover)
print('Loaded ...')
cancer_cells = []
T_cells = []
cyto_T_cells = []
for i, row in enumerate(input_list):
try:
row = [int(x) for x in row]
except ValueError:
continue
if row[4] > 0:
cancer_cells.append([row[0], row[1], row[2], row[3]])
if row[5] > 0:
T_cells.append([row[0], row[1], row[2], row[3]])
if row[6] > 0:
cyto_T_cells.append([row[0], row[1], row[2], row[3]])
cancer_cells = np.asarray(cancer_cells)
T_cells = np.asarray(T_cells)
cyto_T_cells = np.asarray(cyto_T_cells)
print('Separated ...')
t = 25
partitioned_cancer_cells, windows, w, h = partition.partition(cancer_cells,
tile_size=t, to_list=True)
print('Cancer cells partitioned ...')
if args.heat:
spatial_distribution = np.zeros_like(partitioned_cancer_cells)
for i in range(t):
for j in range(t):
spatial_distribution[i][j] = len(partitioned_cancer_cells[i][j]
)
with open('./inputs/spatial/' + name + '.txt', 'w', newline=''
) as dest:
dest.write(str(spatial_distribution))
if args.fish:
result = fishermans_algorithm(partitioned_cancer_cells, (t, t),
windows, w, h)
print('Result retrieved ...')
if args.object:
with open('./inputs/object/' + name + '.p', 'wb') as dest:
pickle.dump(result, dest)
dups = set()
histogram = np.zeros(21, dtype=np.uint32)
for cluster in result:
dups.add(cluster)
total_cluster_cells = 0
clusters_sum = 0
dups_length = len(dups)
for i in dups:
value = len(i.cells)
clusters_sum += value
total_cluster_cells += len(i.cells)
if value > 20:
histogram[20] += 1
else:
histogram[value - 1] += 1
print('Histogram retrieved ...')
clusters_avg = clusters_sum / dups_length
assert total_cluster_cells == len(cancer_cells)
y = np.array(histogram)
x = np.arange(21) + 1
plt.bar(x, y)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.show()
plt.close()
if args.object:
with open('./inputs/object/' + name + '.txt', 'w', newline=''
) as dest:
dest.write('Average size of cluster: ' + str(clusters_avg) +
'\n')
dest.write('Number of clusters: ' + str(len(dups)) + '\n')
dest.write('Total number of cells: ' + str(
total_cluster_cells) + '\n')
dest.write('Cluster counts: ' + '\n')
for i, x in enumerate(histogram):
dest.write(str(i) + ', ' + str(x) + '\n')
os.system('say "All pickle files done in this batch."')
<|reserved_special_token_1|>
import glob
import os
import partition
import pickle
import matplotlib.pyplot as plt
import numpy as np
from Cluster import fishermans_algorithm
import argparse
parser = argparse.ArgumentParser()
plt.ion()
parser.add_argument("--fish", help="flag for using fisherman's algorithm")
parser.add_argument("--heat", help="flag for using heatmap")
parser.add_argument("--object", help="flag for dumping the clusters")
args = parser.parse_args()
print(args)
print(args.fish)
print(args.object)
for file in glob.glob("./examples/*.p"):
print(file)
name = file[11:-2]
recover = open("./examples/" + name + ".p", "rb")
input_list = pickle.load(recover)
print("Loaded ...")
cancer_cells = []
T_cells = []
cyto_T_cells = []
for i, row in enumerate(input_list):
try:
row = [int(x) for x in row]
except ValueError:
continue
if row[4] > 0:
cancer_cells.append([row[0], row[1], row[2], row[3]])
if row[5] > 0:
T_cells.append([row[0], row[1], row[2], row[3]])
if row[6] > 0:
cyto_T_cells.append([row[0], row[1], row[2], row[3]])
cancer_cells = np.asarray(cancer_cells)
T_cells = np.asarray(T_cells)
cyto_T_cells = np.asarray(cyto_T_cells)
print("Separated ...")
t = 25
partitioned_cancer_cells, windows, w, h = partition.partition(cancer_cells, tile_size=t, to_list=True)
print("Cancer cells partitioned ...")
if args.heat:
spatial_distribution = np.zeros_like(partitioned_cancer_cells)
for i in range(t):
for j in range(t):
spatial_distribution[i][j] = len(partitioned_cancer_cells[i][j])
with open("./inputs/spatial/" + name + ".txt", "w", newline="") as dest:
dest.write(str(spatial_distribution))
if args.fish:
result = fishermans_algorithm(partitioned_cancer_cells, (t, t), windows, w, h)
print("Result retrieved ...")
if args.object:
with open("./inputs/object/" + name + ".p", "wb") as dest:
pickle.dump(result, dest)
dups = set()
histogram = np.zeros(21, dtype=np.uint32)
for cluster in result:
dups.add(cluster)
total_cluster_cells = 0
clusters_sum = 0
dups_length = len(dups)
for i in dups:
value = len(i.cells)
clusters_sum += value
total_cluster_cells += len(i.cells)
if value > 20:
histogram[20] += 1
else:
histogram[value - 1] += 1
print("Histogram retrieved ...")
clusters_avg = clusters_sum / dups_length
assert(total_cluster_cells == len(cancer_cells))
y = np.array(histogram)
x = np.arange(21) + 1
plt.bar(x, y)
plt.xlabel("Value")
plt.ylabel("Frequency")
# plt.savefig("./inputs/" + name + ".png", bbox_inches='tight')
plt.show()
plt.close()
if args.object:
with open("./inputs/object/" + name + ".txt", "w", newline="") as dest:
dest.write("Average size of cluster: " + str(clusters_avg) + "\n")
dest.write("Number of clusters: " + str(len(dups)) + "\n")
dest.write("Total number of cells: " + str(total_cluster_cells) + "\n")
dest.write("Cluster counts: " + "\n")
for i, x in enumerate(histogram):
dest.write(str(i) + ", " + str(x) + "\n")
os.system('say "All pickle files done in this batch."')
# End of file
|
flexible
|
{
"blob_id": "805bc144a4945b46b398853e79ded17370ada380",
"index": 3940,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nplt.ion()\nparser.add_argument('--fish', help=\"flag for using fisherman's algorithm\")\nparser.add_argument('--heat', help='flag for using heatmap')\nparser.add_argument('--object', help='flag for dumping the clusters')\n<mask token>\nprint(args)\nprint(args.fish)\nprint(args.object)\nfor file in glob.glob('./examples/*.p'):\n print(file)\n name = file[11:-2]\n recover = open('./examples/' + name + '.p', 'rb')\n input_list = pickle.load(recover)\n print('Loaded ...')\n cancer_cells = []\n T_cells = []\n cyto_T_cells = []\n for i, row in enumerate(input_list):\n try:\n row = [int(x) for x in row]\n except ValueError:\n continue\n if row[4] > 0:\n cancer_cells.append([row[0], row[1], row[2], row[3]])\n if row[5] > 0:\n T_cells.append([row[0], row[1], row[2], row[3]])\n if row[6] > 0:\n cyto_T_cells.append([row[0], row[1], row[2], row[3]])\n cancer_cells = np.asarray(cancer_cells)\n T_cells = np.asarray(T_cells)\n cyto_T_cells = np.asarray(cyto_T_cells)\n print('Separated ...')\n t = 25\n partitioned_cancer_cells, windows, w, h = partition.partition(cancer_cells,\n tile_size=t, to_list=True)\n print('Cancer cells partitioned ...')\n if args.heat:\n spatial_distribution = np.zeros_like(partitioned_cancer_cells)\n for i in range(t):\n for j in range(t):\n spatial_distribution[i][j] = len(partitioned_cancer_cells[i][j]\n )\n with open('./inputs/spatial/' + name + '.txt', 'w', newline=''\n ) as dest:\n dest.write(str(spatial_distribution))\n if args.fish:\n result = fishermans_algorithm(partitioned_cancer_cells, (t, t),\n windows, w, h)\n print('Result retrieved ...')\n if args.object:\n with open('./inputs/object/' + name + '.p', 'wb') as dest:\n pickle.dump(result, dest)\n dups = set()\n histogram = np.zeros(21, dtype=np.uint32)\n for cluster in result:\n dups.add(cluster)\n total_cluster_cells = 0\n clusters_sum = 0\n dups_length = len(dups)\n for i in dups:\n value = len(i.cells)\n clusters_sum += value\n total_cluster_cells += len(i.cells)\n if value > 20:\n histogram[20] += 1\n else:\n histogram[value - 1] += 1\n print('Histogram retrieved ...')\n clusters_avg = clusters_sum / dups_length\n assert total_cluster_cells == len(cancer_cells)\n y = np.array(histogram)\n x = np.arange(21) + 1\n plt.bar(x, y)\n plt.xlabel('Value')\n plt.ylabel('Frequency')\n plt.show()\n plt.close()\n if args.object:\n with open('./inputs/object/' + name + '.txt', 'w', newline=''\n ) as dest:\n dest.write('Average size of cluster: ' + str(clusters_avg) +\n '\\n')\n dest.write('Number of clusters: ' + str(len(dups)) + '\\n')\n dest.write('Total number of cells: ' + str(\n total_cluster_cells) + '\\n')\n dest.write('Cluster counts: ' + '\\n')\n for i, x in enumerate(histogram):\n dest.write(str(i) + ', ' + str(x) + '\\n')\nos.system('say \"All pickle files done in this batch.\"')\n",
"step-3": "<mask token>\nparser = argparse.ArgumentParser()\nplt.ion()\nparser.add_argument('--fish', help=\"flag for using fisherman's algorithm\")\nparser.add_argument('--heat', help='flag for using heatmap')\nparser.add_argument('--object', help='flag for dumping the clusters')\nargs = parser.parse_args()\nprint(args)\nprint(args.fish)\nprint(args.object)\nfor file in glob.glob('./examples/*.p'):\n print(file)\n name = file[11:-2]\n recover = open('./examples/' + name + '.p', 'rb')\n input_list = pickle.load(recover)\n print('Loaded ...')\n cancer_cells = []\n T_cells = []\n cyto_T_cells = []\n for i, row in enumerate(input_list):\n try:\n row = [int(x) for x in row]\n except ValueError:\n continue\n if row[4] > 0:\n cancer_cells.append([row[0], row[1], row[2], row[3]])\n if row[5] > 0:\n T_cells.append([row[0], row[1], row[2], row[3]])\n if row[6] > 0:\n cyto_T_cells.append([row[0], row[1], row[2], row[3]])\n cancer_cells = np.asarray(cancer_cells)\n T_cells = np.asarray(T_cells)\n cyto_T_cells = np.asarray(cyto_T_cells)\n print('Separated ...')\n t = 25\n partitioned_cancer_cells, windows, w, h = partition.partition(cancer_cells,\n tile_size=t, to_list=True)\n print('Cancer cells partitioned ...')\n if args.heat:\n spatial_distribution = np.zeros_like(partitioned_cancer_cells)\n for i in range(t):\n for j in range(t):\n spatial_distribution[i][j] = len(partitioned_cancer_cells[i][j]\n )\n with open('./inputs/spatial/' + name + '.txt', 'w', newline=''\n ) as dest:\n dest.write(str(spatial_distribution))\n if args.fish:\n result = fishermans_algorithm(partitioned_cancer_cells, (t, t),\n windows, w, h)\n print('Result retrieved ...')\n if args.object:\n with open('./inputs/object/' + name + '.p', 'wb') as dest:\n pickle.dump(result, dest)\n dups = set()\n histogram = np.zeros(21, dtype=np.uint32)\n for cluster in result:\n dups.add(cluster)\n total_cluster_cells = 0\n clusters_sum = 0\n dups_length = len(dups)\n for i in dups:\n value = len(i.cells)\n clusters_sum += value\n total_cluster_cells += len(i.cells)\n if value > 20:\n histogram[20] += 1\n else:\n histogram[value - 1] += 1\n print('Histogram retrieved ...')\n clusters_avg = clusters_sum / dups_length\n assert total_cluster_cells == len(cancer_cells)\n y = np.array(histogram)\n x = np.arange(21) + 1\n plt.bar(x, y)\n plt.xlabel('Value')\n plt.ylabel('Frequency')\n plt.show()\n plt.close()\n if args.object:\n with open('./inputs/object/' + name + '.txt', 'w', newline=''\n ) as dest:\n dest.write('Average size of cluster: ' + str(clusters_avg) +\n '\\n')\n dest.write('Number of clusters: ' + str(len(dups)) + '\\n')\n dest.write('Total number of cells: ' + str(\n total_cluster_cells) + '\\n')\n dest.write('Cluster counts: ' + '\\n')\n for i, x in enumerate(histogram):\n dest.write(str(i) + ', ' + str(x) + '\\n')\nos.system('say \"All pickle files done in this batch.\"')\n",
"step-4": "import glob\nimport os\nimport partition\nimport pickle\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom Cluster import fishermans_algorithm\nimport argparse\nparser = argparse.ArgumentParser()\nplt.ion()\nparser.add_argument('--fish', help=\"flag for using fisherman's algorithm\")\nparser.add_argument('--heat', help='flag for using heatmap')\nparser.add_argument('--object', help='flag for dumping the clusters')\nargs = parser.parse_args()\nprint(args)\nprint(args.fish)\nprint(args.object)\nfor file in glob.glob('./examples/*.p'):\n print(file)\n name = file[11:-2]\n recover = open('./examples/' + name + '.p', 'rb')\n input_list = pickle.load(recover)\n print('Loaded ...')\n cancer_cells = []\n T_cells = []\n cyto_T_cells = []\n for i, row in enumerate(input_list):\n try:\n row = [int(x) for x in row]\n except ValueError:\n continue\n if row[4] > 0:\n cancer_cells.append([row[0], row[1], row[2], row[3]])\n if row[5] > 0:\n T_cells.append([row[0], row[1], row[2], row[3]])\n if row[6] > 0:\n cyto_T_cells.append([row[0], row[1], row[2], row[3]])\n cancer_cells = np.asarray(cancer_cells)\n T_cells = np.asarray(T_cells)\n cyto_T_cells = np.asarray(cyto_T_cells)\n print('Separated ...')\n t = 25\n partitioned_cancer_cells, windows, w, h = partition.partition(cancer_cells,\n tile_size=t, to_list=True)\n print('Cancer cells partitioned ...')\n if args.heat:\n spatial_distribution = np.zeros_like(partitioned_cancer_cells)\n for i in range(t):\n for j in range(t):\n spatial_distribution[i][j] = len(partitioned_cancer_cells[i][j]\n )\n with open('./inputs/spatial/' + name + '.txt', 'w', newline=''\n ) as dest:\n dest.write(str(spatial_distribution))\n if args.fish:\n result = fishermans_algorithm(partitioned_cancer_cells, (t, t),\n windows, w, h)\n print('Result retrieved ...')\n if args.object:\n with open('./inputs/object/' + name + '.p', 'wb') as dest:\n pickle.dump(result, dest)\n dups = set()\n histogram = np.zeros(21, dtype=np.uint32)\n for cluster in result:\n dups.add(cluster)\n total_cluster_cells = 0\n clusters_sum = 0\n dups_length = len(dups)\n for i in dups:\n value = len(i.cells)\n clusters_sum += value\n total_cluster_cells += len(i.cells)\n if value > 20:\n histogram[20] += 1\n else:\n histogram[value - 1] += 1\n print('Histogram retrieved ...')\n clusters_avg = clusters_sum / dups_length\n assert total_cluster_cells == len(cancer_cells)\n y = np.array(histogram)\n x = np.arange(21) + 1\n plt.bar(x, y)\n plt.xlabel('Value')\n plt.ylabel('Frequency')\n plt.show()\n plt.close()\n if args.object:\n with open('./inputs/object/' + name + '.txt', 'w', newline=''\n ) as dest:\n dest.write('Average size of cluster: ' + str(clusters_avg) +\n '\\n')\n dest.write('Number of clusters: ' + str(len(dups)) + '\\n')\n dest.write('Total number of cells: ' + str(\n total_cluster_cells) + '\\n')\n dest.write('Cluster counts: ' + '\\n')\n for i, x in enumerate(histogram):\n dest.write(str(i) + ', ' + str(x) + '\\n')\nos.system('say \"All pickle files done in this batch.\"')\n",
"step-5": "import glob\nimport os\nimport partition\nimport pickle\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom Cluster import fishermans_algorithm\nimport argparse\n\nparser = argparse.ArgumentParser()\n\nplt.ion()\n\nparser.add_argument(\"--fish\", help=\"flag for using fisherman's algorithm\")\nparser.add_argument(\"--heat\", help=\"flag for using heatmap\")\nparser.add_argument(\"--object\", help=\"flag for dumping the clusters\")\nargs = parser.parse_args()\n\nprint(args)\nprint(args.fish)\nprint(args.object)\n\nfor file in glob.glob(\"./examples/*.p\"):\n print(file)\n name = file[11:-2]\n recover = open(\"./examples/\" + name + \".p\", \"rb\")\n input_list = pickle.load(recover)\n print(\"Loaded ...\")\n\n cancer_cells = []\n T_cells = []\n cyto_T_cells = []\n\n for i, row in enumerate(input_list):\n try:\n row = [int(x) for x in row]\n except ValueError:\n continue\n\n if row[4] > 0:\n cancer_cells.append([row[0], row[1], row[2], row[3]])\n if row[5] > 0:\n T_cells.append([row[0], row[1], row[2], row[3]])\n if row[6] > 0:\n cyto_T_cells.append([row[0], row[1], row[2], row[3]])\n\n cancer_cells = np.asarray(cancer_cells)\n T_cells = np.asarray(T_cells)\n cyto_T_cells = np.asarray(cyto_T_cells)\n\n print(\"Separated ...\")\n\n t = 25\n partitioned_cancer_cells, windows, w, h = partition.partition(cancer_cells, tile_size=t, to_list=True)\n print(\"Cancer cells partitioned ...\")\n\n if args.heat:\n spatial_distribution = np.zeros_like(partitioned_cancer_cells)\n\n for i in range(t):\n for j in range(t):\n spatial_distribution[i][j] = len(partitioned_cancer_cells[i][j])\n\n with open(\"./inputs/spatial/\" + name + \".txt\", \"w\", newline=\"\") as dest:\n dest.write(str(spatial_distribution))\n\n if args.fish:\n result = fishermans_algorithm(partitioned_cancer_cells, (t, t), windows, w, h)\n print(\"Result retrieved ...\")\n\n if args.object:\n with open(\"./inputs/object/\" + name + \".p\", \"wb\") as dest:\n pickle.dump(result, dest)\n\n dups = set()\n histogram = np.zeros(21, dtype=np.uint32)\n\n for cluster in result:\n dups.add(cluster)\n\n total_cluster_cells = 0\n\n clusters_sum = 0\n dups_length = len(dups)\n\n for i in dups:\n value = len(i.cells)\n clusters_sum += value\n total_cluster_cells += len(i.cells)\n if value > 20:\n histogram[20] += 1\n else:\n histogram[value - 1] += 1\n\n print(\"Histogram retrieved ...\")\n\n clusters_avg = clusters_sum / dups_length\n\n assert(total_cluster_cells == len(cancer_cells))\n\n y = np.array(histogram)\n x = np.arange(21) + 1\n\n plt.bar(x, y)\n plt.xlabel(\"Value\")\n plt.ylabel(\"Frequency\")\n # plt.savefig(\"./inputs/\" + name + \".png\", bbox_inches='tight')\n plt.show()\n plt.close()\n\n if args.object:\n with open(\"./inputs/object/\" + name + \".txt\", \"w\", newline=\"\") as dest:\n dest.write(\"Average size of cluster: \" + str(clusters_avg) + \"\\n\")\n dest.write(\"Number of clusters: \" + str(len(dups)) + \"\\n\")\n dest.write(\"Total number of cells: \" + str(total_cluster_cells) + \"\\n\")\n dest.write(\"Cluster counts: \" + \"\\n\")\n for i, x in enumerate(histogram):\n dest.write(str(i) + \", \" + str(x) + \"\\n\")\n\nos.system('say \"All pickle files done in this batch.\"')\n\n\n\n\n\n\n\n# End of file\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
from functools import wraps
class aws_retry:
"""retries the call (required for some cases where data is not consistent yet in AWS"""
def __init__(self, fields):
self.fields = fields # field to inject
def __call__(self, function):
pass
#code from aws_inject
# from osbot_aws.AWS_Config import AWS_Config
# @wraps(function) # makes __name__ work ok
# def wrapper(*args,**kwargs): # wrapper function
# for field in self.fields.split(','): # split value provided by comma
# if field == 'region' : kwargs[field] = AWS_Config().aws_session_region_name()
# if field == 'account_id': kwargs[field] = AWS_Config().aws_session_account_id()
# return function(*args,**kwargs)
#return wrapper
|
normal
|
{
"blob_id": "493b29433f0c3646e7f80fca2f656fc4a5256003",
"index": 8884,
"step-1": "<mask token>\n\n\nclass aws_retry:\n <mask token>\n\n def __init__(self, fields):\n self.fields = fields\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass aws_retry:\n <mask token>\n\n def __init__(self, fields):\n self.fields = fields\n\n def __call__(self, function):\n pass\n",
"step-3": "<mask token>\n\n\nclass aws_retry:\n \"\"\"retries the call (required for some cases where data is not consistent yet in AWS\"\"\"\n\n def __init__(self, fields):\n self.fields = fields\n\n def __call__(self, function):\n pass\n",
"step-4": "from functools import wraps\n\n\nclass aws_retry:\n \"\"\"retries the call (required for some cases where data is not consistent yet in AWS\"\"\"\n\n def __init__(self, fields):\n self.fields = fields\n\n def __call__(self, function):\n pass\n",
"step-5": "from functools import wraps\n\n\nclass aws_retry:\n\n \"\"\"retries the call (required for some cases where data is not consistent yet in AWS\"\"\"\n def __init__(self, fields):\n self.fields = fields # field to inject\n\n def __call__(self, function):\n pass\n #code from aws_inject\n # from osbot_aws.AWS_Config import AWS_Config\n # @wraps(function) # makes __name__ work ok\n # def wrapper(*args,**kwargs): # wrapper function\n # for field in self.fields.split(','): # split value provided by comma\n # if field == 'region' : kwargs[field] = AWS_Config().aws_session_region_name()\n # if field == 'account_id': kwargs[field] = AWS_Config().aws_session_account_id()\n # return function(*args,**kwargs)\n #return wrapper",
"step-ids": [
2,
3,
4,
5,
6
]
}
|
[
2,
3,
4,
5,
6
] |
# 約分して、互いに素な(1,3) (3,1)のようなペアを作りカウントする
# 正のグループと負のグループを別々に管理
# 正のグループの相手が負のグループに存在した場合、
# どちらかのグループから好きなだけ選ぶか、どちらも選ばないかしかない
# 誰ともペアにならなかったグループの個数を全て足してP個だとして、2^P通りを掛ける
# (0,0)については、その中から1つ選ぶか、選ばないかしかない
import sys
readline = sys.stdin.readline
N = int(readline())
import math
zeropair = 0
zeroa = 0
zerob = 0
from collections import defaultdict
pluspair = defaultdict(int)
minuspair = defaultdict(int)
for i in range(N):
a,b = map(int,readline().split())
if a == 0 and b == 0:
zeropair += 1
continue
if a == 0:
zeroa += 1
continue
if b == 0:
zerob += 1
continue
absa = abs(a)
absb = abs(b)
g = math.gcd(absa,absb)
absa,absb = absa//g,absb//g
if a * b > 0:
pluspair[(absa,absb)] += 1
else:
minuspair[(absa,absb)] += 1
DIV = 1000000007
ans = 1
# zeroa,zerobから選ぶパターンは、どちらから好きなだけ選ぶか、どちらも選ばないか
ans *= (pow(2,zeroa,DIV) + pow(2,zerob,DIV) - 1) % DIV
ans %= DIV
# 誰とでもペアになれるものをカウント
allcnt = 0
# plusから選ぶパターンで、minusにある対応ペアを探す
for item in pluspair.items():
a,b = item[0]
cnt = item[1]
if (b,a) in minuspair:
ans *= (pow(2,cnt,DIV) + pow(2,minuspair[(b,a)]) - 1) % DIV
ans %= DIV
del minuspair[(b,a)]
else:
allcnt += cnt
for val in minuspair.values():
allcnt += val
ans = (ans * pow(2,allcnt,DIV)) % DIV
# zeropairから選んだ場合、今までのパターンとは独立
ans += zeropair
print((ans - 1) % DIV)
|
normal
|
{
"blob_id": "098488fd10bcf81c4efa198a44d2ff87e4f8c130",
"index": 3225,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in range(N):\n a, b = map(int, readline().split())\n if a == 0 and b == 0:\n zeropair += 1\n continue\n if a == 0:\n zeroa += 1\n continue\n if b == 0:\n zerob += 1\n continue\n absa = abs(a)\n absb = abs(b)\n g = math.gcd(absa, absb)\n absa, absb = absa // g, absb // g\n if a * b > 0:\n pluspair[absa, absb] += 1\n else:\n minuspair[absa, absb] += 1\n<mask token>\nans *= (pow(2, zeroa, DIV) + pow(2, zerob, DIV) - 1) % DIV\nans %= DIV\n<mask token>\nfor item in pluspair.items():\n a, b = item[0]\n cnt = item[1]\n if (b, a) in minuspair:\n ans *= (pow(2, cnt, DIV) + pow(2, minuspair[b, a]) - 1) % DIV\n ans %= DIV\n del minuspair[b, a]\n else:\n allcnt += cnt\nfor val in minuspair.values():\n allcnt += val\n<mask token>\nans += zeropair\nprint((ans - 1) % DIV)\n",
"step-3": "<mask token>\nreadline = sys.stdin.readline\nN = int(readline())\n<mask token>\nzeropair = 0\nzeroa = 0\nzerob = 0\n<mask token>\npluspair = defaultdict(int)\nminuspair = defaultdict(int)\nfor i in range(N):\n a, b = map(int, readline().split())\n if a == 0 and b == 0:\n zeropair += 1\n continue\n if a == 0:\n zeroa += 1\n continue\n if b == 0:\n zerob += 1\n continue\n absa = abs(a)\n absb = abs(b)\n g = math.gcd(absa, absb)\n absa, absb = absa // g, absb // g\n if a * b > 0:\n pluspair[absa, absb] += 1\n else:\n minuspair[absa, absb] += 1\nDIV = 1000000007\nans = 1\nans *= (pow(2, zeroa, DIV) + pow(2, zerob, DIV) - 1) % DIV\nans %= DIV\nallcnt = 0\nfor item in pluspair.items():\n a, b = item[0]\n cnt = item[1]\n if (b, a) in minuspair:\n ans *= (pow(2, cnt, DIV) + pow(2, minuspair[b, a]) - 1) % DIV\n ans %= DIV\n del minuspair[b, a]\n else:\n allcnt += cnt\nfor val in minuspair.values():\n allcnt += val\nans = ans * pow(2, allcnt, DIV) % DIV\nans += zeropair\nprint((ans - 1) % DIV)\n",
"step-4": "import sys\nreadline = sys.stdin.readline\nN = int(readline())\nimport math\nzeropair = 0\nzeroa = 0\nzerob = 0\nfrom collections import defaultdict\npluspair = defaultdict(int)\nminuspair = defaultdict(int)\nfor i in range(N):\n a, b = map(int, readline().split())\n if a == 0 and b == 0:\n zeropair += 1\n continue\n if a == 0:\n zeroa += 1\n continue\n if b == 0:\n zerob += 1\n continue\n absa = abs(a)\n absb = abs(b)\n g = math.gcd(absa, absb)\n absa, absb = absa // g, absb // g\n if a * b > 0:\n pluspair[absa, absb] += 1\n else:\n minuspair[absa, absb] += 1\nDIV = 1000000007\nans = 1\nans *= (pow(2, zeroa, DIV) + pow(2, zerob, DIV) - 1) % DIV\nans %= DIV\nallcnt = 0\nfor item in pluspair.items():\n a, b = item[0]\n cnt = item[1]\n if (b, a) in minuspair:\n ans *= (pow(2, cnt, DIV) + pow(2, minuspair[b, a]) - 1) % DIV\n ans %= DIV\n del minuspair[b, a]\n else:\n allcnt += cnt\nfor val in minuspair.values():\n allcnt += val\nans = ans * pow(2, allcnt, DIV) % DIV\nans += zeropair\nprint((ans - 1) % DIV)\n",
"step-5": "# 約分して、互いに素な(1,3) (3,1)のようなペアを作りカウントする\n# 正のグループと負のグループを別々に管理\n# 正のグループの相手が負のグループに存在した場合、\n# どちらかのグループから好きなだけ選ぶか、どちらも選ばないかしかない\n# 誰ともペアにならなかったグループの個数を全て足してP個だとして、2^P通りを掛ける\n# (0,0)については、その中から1つ選ぶか、選ばないかしかない\n\nimport sys\nreadline = sys.stdin.readline\n\nN = int(readline())\nimport math\n\nzeropair = 0\nzeroa = 0\nzerob = 0\nfrom collections import defaultdict\npluspair = defaultdict(int)\nminuspair = defaultdict(int)\nfor i in range(N):\n a,b = map(int,readline().split())\n if a == 0 and b == 0:\n zeropair += 1\n continue\n if a == 0:\n zeroa += 1\n continue\n if b == 0:\n zerob += 1\n continue\n absa = abs(a)\n absb = abs(b)\n g = math.gcd(absa,absb)\n absa,absb = absa//g,absb//g\n if a * b > 0:\n pluspair[(absa,absb)] += 1\n else:\n minuspair[(absa,absb)] += 1\n\nDIV = 1000000007\nans = 1\n# zeroa,zerobから選ぶパターンは、どちらから好きなだけ選ぶか、どちらも選ばないか\nans *= (pow(2,zeroa,DIV) + pow(2,zerob,DIV) - 1) % DIV\nans %= DIV\n\n# 誰とでもペアになれるものをカウント\nallcnt = 0\n\n# plusから選ぶパターンで、minusにある対応ペアを探す\nfor item in pluspair.items():\n a,b = item[0]\n cnt = item[1]\n if (b,a) in minuspair:\n ans *= (pow(2,cnt,DIV) + pow(2,minuspair[(b,a)]) - 1) % DIV\n ans %= DIV\n del minuspair[(b,a)]\n else:\n allcnt += cnt\n\nfor val in minuspair.values():\n allcnt += val\n\nans = (ans * pow(2,allcnt,DIV)) % DIV\n# zeropairから選んだ場合、今までのパターンとは独立\nans += zeropair\nprint((ans - 1) % DIV)\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
from src.MultiValueDictApp import MultiValueDictApp
def main():
app = MultiValueDictApp()
print("Welcome to Multivalue Dictionary App")
print("COMMANDS and format:")
print("KEYS")
print("MEMBERS key")
print("ADD key value")
print("REMOVE key value")
print("REMOVEALL key")
print("CLEAR")
print("KEYEXISTS key")
print("VALUEEXISTS key value")
print("ALLMEMBERS")
print("ITEMS")
print("EXIT")
print("Enter COMMAND key value below")
print("---------------------------------------")
print("")
while True:
command, *args = input().split(' ')
app.run(command, args)
if __name__ == "__main__":
main()
|
normal
|
{
"blob_id": "21e83369c4100c41885e9ee8a8d7310556bfe51d",
"index": 7271,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef main():\n app = MultiValueDictApp()\n print('Welcome to Multivalue Dictionary App')\n print('COMMANDS and format:')\n print('KEYS')\n print('MEMBERS key')\n print('ADD key value')\n print('REMOVE key value')\n print('REMOVEALL key')\n print('CLEAR')\n print('KEYEXISTS key')\n print('VALUEEXISTS key value')\n print('ALLMEMBERS')\n print('ITEMS')\n print('EXIT')\n print('Enter COMMAND key value below')\n print('---------------------------------------')\n print('')\n while True:\n command, *args = input().split(' ')\n app.run(command, args)\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef main():\n app = MultiValueDictApp()\n print('Welcome to Multivalue Dictionary App')\n print('COMMANDS and format:')\n print('KEYS')\n print('MEMBERS key')\n print('ADD key value')\n print('REMOVE key value')\n print('REMOVEALL key')\n print('CLEAR')\n print('KEYEXISTS key')\n print('VALUEEXISTS key value')\n print('ALLMEMBERS')\n print('ITEMS')\n print('EXIT')\n print('Enter COMMAND key value below')\n print('---------------------------------------')\n print('')\n while True:\n command, *args = input().split(' ')\n app.run(command, args)\n\n\nif __name__ == '__main__':\n main()\n",
"step-4": "from src.MultiValueDictApp import MultiValueDictApp\n\n\ndef main():\n app = MultiValueDictApp()\n print('Welcome to Multivalue Dictionary App')\n print('COMMANDS and format:')\n print('KEYS')\n print('MEMBERS key')\n print('ADD key value')\n print('REMOVE key value')\n print('REMOVEALL key')\n print('CLEAR')\n print('KEYEXISTS key')\n print('VALUEEXISTS key value')\n print('ALLMEMBERS')\n print('ITEMS')\n print('EXIT')\n print('Enter COMMAND key value below')\n print('---------------------------------------')\n print('')\n while True:\n command, *args = input().split(' ')\n app.run(command, args)\n\n\nif __name__ == '__main__':\n main()\n",
"step-5": "from src.MultiValueDictApp import MultiValueDictApp\n\ndef main():\n app = MultiValueDictApp()\n print(\"Welcome to Multivalue Dictionary App\")\n print(\"COMMANDS and format:\")\n print(\"KEYS\")\n print(\"MEMBERS key\")\n print(\"ADD key value\")\n print(\"REMOVE key value\")\n print(\"REMOVEALL key\")\n print(\"CLEAR\")\n print(\"KEYEXISTS key\")\n print(\"VALUEEXISTS key value\")\n print(\"ALLMEMBERS\")\n print(\"ITEMS\")\n print(\"EXIT\")\n print(\"Enter COMMAND key value below\")\n print(\"---------------------------------------\")\n print(\"\")\n\n while True:\n command, *args = input().split(' ')\n app.run(command, args)\n\nif __name__ == \"__main__\":\n main()",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
class Results_flat(models.Model):
<|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|>
<|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|>
<|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|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
class Meta:
managed = False
db_table = 'NavigantAnalyzer_results_flat'
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Results_flat(models.Model):
<|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|>
<|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|>
<|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|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
class Meta:
managed = False
db_table = 'NavigantAnalyzer_results_flat'
def get_fields(self):
result = dict()
datetime_fields = ['race_begin', 'result_start_time']
for field in Results_flat._meta.fields:
value = field.value_to_string(self)
if value.isdigit():
value = int(value)
if field.name in datetime_fields:
value = convert_datetime_string(value)
result[field.name] = value
return json.dumps(result)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Results_flat(models.Model):
race_id = models.IntegerField()
race_name = models.CharField(max_length=127)
race_serie = models.CharField(max_length=127, blank=True)
race_begin = models.DateTimeField(blank=True, null=True)
result_start_time = models.DateTimeField(blank=True, null=True)
runner_last_name = models.CharField(max_length=63, blank=True)
runner_first_name = models.CharField(max_length=63, blank=True)
result_emit = models.CharField(max_length=12, blank=True)
course_name = models.CharField(max_length=63)
course_length = models.IntegerField(blank=True, null=True)
course_num_participants = models.IntegerField(blank=True, null=True)
course_min_time = models.IntegerField(blank=True, null=True)
course_mean_time = models.IntegerField(blank=True, null=True)
course_min_puistotime = models.IntegerField(blank=True, null=True)
course_mean_puistotime = models.IntegerField(blank=True, null=True)
visit_min_time = models.IntegerField(blank=True, null=True)
visit_mean_time = models.IntegerField(blank=True, null=True)
visit_min_puistotime = models.IntegerField(blank=True, null=True)
visit_mean_puistotime = models.IntegerField(blank=True, null=True)
visit_puistoman_time = models.IntegerField(blank=True, null=True)
leg_min_time = models.IntegerField(blank=True, null=True)
leg_mean_time = models.IntegerField(blank=True, null=True)
leg_min_puistotime = models.IntegerField(blank=True, null=True)
leg_mean_puistotime = models.IntegerField(blank=True, null=True)
visit_order = models.IntegerField()
visit_code = models.IntegerField()
visit_time = models.IntegerField()
visit_position = models.IntegerField(blank=True)
visit_puistoposition = models.IntegerField(blank=True)
leg_time = models.IntegerField(blank=True)
leg_position = models.IntegerField(blank=True)
leg_puistoposition = models.IntegerField(blank=True)
visit_puistodiff_time_l = models.IntegerField(blank=True, null=True)
visit_puistodiff_time_pm = models.IntegerField(blank=True, null=True)
leg_puistodiff_time_l = models.IntegerField(blank=True, null=True)
leg_puistodiff_time_pm = models.IntegerField(blank=True, null=True)
leg_puistoperc_time_l = models.FloatField(null=True)
leg_puistoperc_time_pm = models.FloatField(null=True)
leg_puistoperc_time_l = models.FloatField(null=True)
leg_puisto_success = models.FloatField(null=True)
result_puistoperc_time_l = models.FloatField(null=True)
result_puistoperc_time_pm = models.FloatField(null=True)
result_puisto_max_level = models.FloatField(null=True)
result_puisto_success = models.FloatField(null=True)
result_puisto_optimum = models.IntegerField(null=True)
result_puisto_mistakes = models.IntegerField(null=True)
class Meta:
managed = False
db_table = 'NavigantAnalyzer_results_flat'
def get_fields(self):
result = dict()
datetime_fields = ['race_begin', 'result_start_time']
for field in Results_flat._meta.fields:
value = field.value_to_string(self)
if value.isdigit():
value = int(value)
if field.name in datetime_fields:
value = convert_datetime_string(value)
result[field.name] = value
return json.dumps(result)
<|reserved_special_token_1|>
from django.db import models
from NavigantAnalyzer.common import convert_datetime_string
import json
class Results_flat(models.Model):
race_id = models.IntegerField()
race_name = models.CharField(max_length=127)
race_serie = models.CharField(max_length=127, blank=True)
race_begin = models.DateTimeField(blank=True, null=True)
result_start_time = models.DateTimeField(blank=True, null=True)
runner_last_name = models.CharField(max_length=63, blank=True)
runner_first_name = models.CharField(max_length=63, blank=True)
result_emit = models.CharField(max_length=12, blank=True)
course_name = models.CharField(max_length=63)
course_length = models.IntegerField(blank=True, null=True)
course_num_participants = models.IntegerField(blank=True, null=True)
course_min_time = models.IntegerField(blank=True, null=True)
course_mean_time = models.IntegerField(blank=True, null=True)
course_min_puistotime = models.IntegerField(blank=True, null=True)
course_mean_puistotime = models.IntegerField(blank=True, null=True)
visit_min_time = models.IntegerField(blank=True, null=True)
visit_mean_time = models.IntegerField(blank=True, null=True)
visit_min_puistotime = models.IntegerField(blank=True, null=True)
visit_mean_puistotime = models.IntegerField(blank=True, null=True)
visit_puistoman_time = models.IntegerField(blank=True, null=True)
leg_min_time = models.IntegerField(blank=True, null=True)
leg_mean_time = models.IntegerField(blank=True, null=True)
leg_min_puistotime = models.IntegerField(blank=True, null=True)
leg_mean_puistotime = models.IntegerField(blank=True, null=True)
visit_order = models.IntegerField()
visit_code = models.IntegerField()
visit_time = models.IntegerField()
visit_position = models.IntegerField(blank=True)
visit_puistoposition = models.IntegerField(blank=True)
leg_time = models.IntegerField(blank=True)
leg_position = models.IntegerField(blank=True)
leg_puistoposition = models.IntegerField(blank=True)
visit_puistodiff_time_l = models.IntegerField(blank=True, null=True)
visit_puistodiff_time_pm = models.IntegerField(blank=True, null=True)
leg_puistodiff_time_l = models.IntegerField(blank=True, null=True)
leg_puistodiff_time_pm = models.IntegerField(blank=True, null=True)
leg_puistoperc_time_l = models.FloatField(null=True)
leg_puistoperc_time_pm = models.FloatField(null=True)
leg_puistoperc_time_l = models.FloatField(null=True)
leg_puisto_success = models.FloatField(null=True)
result_puistoperc_time_l = models.FloatField(null=True)
result_puistoperc_time_pm = models.FloatField(null=True)
result_puisto_max_level = models.FloatField(null=True)
result_puisto_success = models.FloatField(null=True)
result_puisto_optimum = models.IntegerField(null=True)
result_puisto_mistakes = models.IntegerField(null=True)
class Meta:
managed = False
db_table = 'NavigantAnalyzer_results_flat'
def get_fields(self):
result = dict()
datetime_fields = ['race_begin', 'result_start_time']
for field in Results_flat._meta.fields:
value = field.value_to_string(self)
if value.isdigit():
value = int(value)
if field.name in datetime_fields:
value = convert_datetime_string(value)
result[field.name] = value
return json.dumps(result)
<|reserved_special_token_1|>
from django.db import models
from NavigantAnalyzer.common import convert_datetime_string
import json
# A custom view-based model for flat outputs - RÖ - 2018-10-24
# Don't add, change or delete fields without editing the view in the Db
class Results_flat(models.Model):
race_id = models.IntegerField()
race_name = models.CharField(max_length=127)
race_serie = models.CharField(max_length=127, blank=True)
race_begin = models.DateTimeField(blank=True, null=True)
result_start_time = models.DateTimeField(blank=True, null=True)
runner_last_name = models.CharField(max_length=63, blank=True)
runner_first_name = models.CharField(max_length=63, blank=True)
result_emit = models.CharField(max_length=12, blank=True)
course_name = models.CharField(max_length=63)
course_length = models.IntegerField(blank=True, null=True)
course_num_participants = models.IntegerField(blank=True, null=True)
course_min_time = models.IntegerField(blank=True, null=True)
course_mean_time = models.IntegerField(blank=True, null=True)
course_min_puistotime = models.IntegerField(blank=True, null=True)
course_mean_puistotime = models.IntegerField(blank=True, null=True)
visit_min_time = models.IntegerField(blank=True, null=True)
visit_mean_time = models.IntegerField(blank=True, null=True)
visit_min_puistotime = models.IntegerField(blank=True, null=True)
visit_mean_puistotime = models.IntegerField(blank=True, null=True)
visit_puistoman_time = models.IntegerField(blank=True, null=True) # Since 2019-12-08
leg_min_time = models.IntegerField(blank=True, null=True)
leg_mean_time = models.IntegerField(blank=True, null=True)
leg_min_puistotime = models.IntegerField(blank=True, null=True)
leg_mean_puistotime = models.IntegerField(blank=True, null=True)
visit_order = models.IntegerField()
visit_code = models.IntegerField()
visit_time = models.IntegerField()
visit_position = models.IntegerField(blank=True)
visit_puistoposition = models.IntegerField(blank=True)
leg_time = models.IntegerField(blank=True)
leg_position = models.IntegerField(blank=True)
leg_puistoposition = models.IntegerField(blank=True)
visit_puistodiff_time_l = models.IntegerField(blank=True, null=True) # Since 2019-12-08
visit_puistodiff_time_pm = models.IntegerField(blank=True, null=True) # Since 2019-12-08
leg_puistodiff_time_l = models.IntegerField(blank=True, null=True) # Since 2019-12-08
leg_puistodiff_time_pm = models.IntegerField(blank=True, null=True) # Since 2019-12-08
leg_puistoperc_time_l = models.FloatField(null=True) # Since 2019-12-08
leg_puistoperc_time_pm = models.FloatField(null=True) # Since 2019-12-08
leg_puistoperc_time_l = models.FloatField(null=True) # Since 2019-12-08
leg_puisto_success = models.FloatField(null=True) # Since 2019-12-08
result_puistoperc_time_l = models.FloatField(null=True) # Since 2019-12-08
result_puistoperc_time_pm = models.FloatField(null=True) # Since 2019-12-08
result_puisto_max_level = models.FloatField(null=True) # Since 2019-12-08
result_puisto_success = models.FloatField(null=True) # Since 2019-12-08
result_puisto_optimum = models.IntegerField(null=True) # Since 2019-12-08
result_puisto_mistakes = models.IntegerField(null=True) # Since 2019-12-08
class Meta:
managed = False
db_table = 'NavigantAnalyzer_results_flat'
def get_fields(self):
result = dict()
datetime_fields = ['race_begin', 'result_start_time']
for field in Results_flat._meta.fields:
value = field.value_to_string(self)
if value.isdigit():
value = int(value)
if field.name in datetime_fields:
value = convert_datetime_string(value)
result[field.name] = value
return json.dumps(result)
|
flexible
|
{
"blob_id": "802eb0502c5eddcabd41b2d438bf53a5d6fb2c82",
"index": 8368,
"step-1": "<mask token>\n\n\nclass Results_flat(models.Model):\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 <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 <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 <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\n class Meta:\n managed = False\n db_table = 'NavigantAnalyzer_results_flat'\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass Results_flat(models.Model):\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 <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 <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 <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\n class Meta:\n managed = False\n db_table = 'NavigantAnalyzer_results_flat'\n\n def get_fields(self):\n result = dict()\n datetime_fields = ['race_begin', 'result_start_time']\n for field in Results_flat._meta.fields:\n value = field.value_to_string(self)\n if value.isdigit():\n value = int(value)\n if field.name in datetime_fields:\n value = convert_datetime_string(value)\n result[field.name] = value\n return json.dumps(result)\n",
"step-3": "<mask token>\n\n\nclass Results_flat(models.Model):\n race_id = models.IntegerField()\n race_name = models.CharField(max_length=127)\n race_serie = models.CharField(max_length=127, blank=True)\n race_begin = models.DateTimeField(blank=True, null=True)\n result_start_time = models.DateTimeField(blank=True, null=True)\n runner_last_name = models.CharField(max_length=63, blank=True)\n runner_first_name = models.CharField(max_length=63, blank=True)\n result_emit = models.CharField(max_length=12, blank=True)\n course_name = models.CharField(max_length=63)\n course_length = models.IntegerField(blank=True, null=True)\n course_num_participants = models.IntegerField(blank=True, null=True)\n course_min_time = models.IntegerField(blank=True, null=True)\n course_mean_time = models.IntegerField(blank=True, null=True)\n course_min_puistotime = models.IntegerField(blank=True, null=True)\n course_mean_puistotime = models.IntegerField(blank=True, null=True)\n visit_min_time = models.IntegerField(blank=True, null=True)\n visit_mean_time = models.IntegerField(blank=True, null=True)\n visit_min_puistotime = models.IntegerField(blank=True, null=True)\n visit_mean_puistotime = models.IntegerField(blank=True, null=True)\n visit_puistoman_time = models.IntegerField(blank=True, null=True)\n leg_min_time = models.IntegerField(blank=True, null=True)\n leg_mean_time = models.IntegerField(blank=True, null=True)\n leg_min_puistotime = models.IntegerField(blank=True, null=True)\n leg_mean_puistotime = models.IntegerField(blank=True, null=True)\n visit_order = models.IntegerField()\n visit_code = models.IntegerField()\n visit_time = models.IntegerField()\n visit_position = models.IntegerField(blank=True)\n visit_puistoposition = models.IntegerField(blank=True)\n leg_time = models.IntegerField(blank=True)\n leg_position = models.IntegerField(blank=True)\n leg_puistoposition = models.IntegerField(blank=True)\n visit_puistodiff_time_l = models.IntegerField(blank=True, null=True)\n visit_puistodiff_time_pm = models.IntegerField(blank=True, null=True)\n leg_puistodiff_time_l = models.IntegerField(blank=True, null=True)\n leg_puistodiff_time_pm = models.IntegerField(blank=True, null=True)\n leg_puistoperc_time_l = models.FloatField(null=True)\n leg_puistoperc_time_pm = models.FloatField(null=True)\n leg_puistoperc_time_l = models.FloatField(null=True)\n leg_puisto_success = models.FloatField(null=True)\n result_puistoperc_time_l = models.FloatField(null=True)\n result_puistoperc_time_pm = models.FloatField(null=True)\n result_puisto_max_level = models.FloatField(null=True)\n result_puisto_success = models.FloatField(null=True)\n result_puisto_optimum = models.IntegerField(null=True)\n result_puisto_mistakes = models.IntegerField(null=True)\n\n\n class Meta:\n managed = False\n db_table = 'NavigantAnalyzer_results_flat'\n\n def get_fields(self):\n result = dict()\n datetime_fields = ['race_begin', 'result_start_time']\n for field in Results_flat._meta.fields:\n value = field.value_to_string(self)\n if value.isdigit():\n value = int(value)\n if field.name in datetime_fields:\n value = convert_datetime_string(value)\n result[field.name] = value\n return json.dumps(result)\n",
"step-4": "from django.db import models\nfrom NavigantAnalyzer.common import convert_datetime_string\nimport json\n\n\nclass Results_flat(models.Model):\n race_id = models.IntegerField()\n race_name = models.CharField(max_length=127)\n race_serie = models.CharField(max_length=127, blank=True)\n race_begin = models.DateTimeField(blank=True, null=True)\n result_start_time = models.DateTimeField(blank=True, null=True)\n runner_last_name = models.CharField(max_length=63, blank=True)\n runner_first_name = models.CharField(max_length=63, blank=True)\n result_emit = models.CharField(max_length=12, blank=True)\n course_name = models.CharField(max_length=63)\n course_length = models.IntegerField(blank=True, null=True)\n course_num_participants = models.IntegerField(blank=True, null=True)\n course_min_time = models.IntegerField(blank=True, null=True)\n course_mean_time = models.IntegerField(blank=True, null=True)\n course_min_puistotime = models.IntegerField(blank=True, null=True)\n course_mean_puistotime = models.IntegerField(blank=True, null=True)\n visit_min_time = models.IntegerField(blank=True, null=True)\n visit_mean_time = models.IntegerField(blank=True, null=True)\n visit_min_puistotime = models.IntegerField(blank=True, null=True)\n visit_mean_puistotime = models.IntegerField(blank=True, null=True)\n visit_puistoman_time = models.IntegerField(blank=True, null=True)\n leg_min_time = models.IntegerField(blank=True, null=True)\n leg_mean_time = models.IntegerField(blank=True, null=True)\n leg_min_puistotime = models.IntegerField(blank=True, null=True)\n leg_mean_puistotime = models.IntegerField(blank=True, null=True)\n visit_order = models.IntegerField()\n visit_code = models.IntegerField()\n visit_time = models.IntegerField()\n visit_position = models.IntegerField(blank=True)\n visit_puistoposition = models.IntegerField(blank=True)\n leg_time = models.IntegerField(blank=True)\n leg_position = models.IntegerField(blank=True)\n leg_puistoposition = models.IntegerField(blank=True)\n visit_puistodiff_time_l = models.IntegerField(blank=True, null=True)\n visit_puistodiff_time_pm = models.IntegerField(blank=True, null=True)\n leg_puistodiff_time_l = models.IntegerField(blank=True, null=True)\n leg_puistodiff_time_pm = models.IntegerField(blank=True, null=True)\n leg_puistoperc_time_l = models.FloatField(null=True)\n leg_puistoperc_time_pm = models.FloatField(null=True)\n leg_puistoperc_time_l = models.FloatField(null=True)\n leg_puisto_success = models.FloatField(null=True)\n result_puistoperc_time_l = models.FloatField(null=True)\n result_puistoperc_time_pm = models.FloatField(null=True)\n result_puisto_max_level = models.FloatField(null=True)\n result_puisto_success = models.FloatField(null=True)\n result_puisto_optimum = models.IntegerField(null=True)\n result_puisto_mistakes = models.IntegerField(null=True)\n\n\n class Meta:\n managed = False\n db_table = 'NavigantAnalyzer_results_flat'\n\n def get_fields(self):\n result = dict()\n datetime_fields = ['race_begin', 'result_start_time']\n for field in Results_flat._meta.fields:\n value = field.value_to_string(self)\n if value.isdigit():\n value = int(value)\n if field.name in datetime_fields:\n value = convert_datetime_string(value)\n result[field.name] = value\n return json.dumps(result)\n",
"step-5": "from django.db import models\nfrom NavigantAnalyzer.common import convert_datetime_string\nimport json\n\n# A custom view-based model for flat outputs - RÖ - 2018-10-24\n# Don't add, change or delete fields without editing the view in the Db\nclass Results_flat(models.Model):\n race_id = models.IntegerField()\n race_name = models.CharField(max_length=127)\n race_serie = models.CharField(max_length=127, blank=True)\n race_begin = models.DateTimeField(blank=True, null=True)\n result_start_time = models.DateTimeField(blank=True, null=True)\n runner_last_name = models.CharField(max_length=63, blank=True)\n runner_first_name = models.CharField(max_length=63, blank=True)\n result_emit = models.CharField(max_length=12, blank=True)\n course_name = models.CharField(max_length=63)\n course_length = models.IntegerField(blank=True, null=True)\n course_num_participants = models.IntegerField(blank=True, null=True)\n course_min_time = models.IntegerField(blank=True, null=True)\n course_mean_time = models.IntegerField(blank=True, null=True)\n course_min_puistotime = models.IntegerField(blank=True, null=True)\n course_mean_puistotime = models.IntegerField(blank=True, null=True)\n visit_min_time = models.IntegerField(blank=True, null=True)\n visit_mean_time = models.IntegerField(blank=True, null=True)\n visit_min_puistotime = models.IntegerField(blank=True, null=True)\n visit_mean_puistotime = models.IntegerField(blank=True, null=True)\n visit_puistoman_time = models.IntegerField(blank=True, null=True) # Since 2019-12-08\n leg_min_time = models.IntegerField(blank=True, null=True)\n leg_mean_time = models.IntegerField(blank=True, null=True)\n leg_min_puistotime = models.IntegerField(blank=True, null=True)\n leg_mean_puistotime = models.IntegerField(blank=True, null=True)\n visit_order = models.IntegerField()\n visit_code = models.IntegerField()\n visit_time = models.IntegerField()\n visit_position = models.IntegerField(blank=True)\n visit_puistoposition = models.IntegerField(blank=True)\n leg_time = models.IntegerField(blank=True)\n leg_position = models.IntegerField(blank=True)\n leg_puistoposition = models.IntegerField(blank=True)\n visit_puistodiff_time_l = models.IntegerField(blank=True, null=True) # Since 2019-12-08\n visit_puistodiff_time_pm = models.IntegerField(blank=True, null=True) # Since 2019-12-08\n leg_puistodiff_time_l = models.IntegerField(blank=True, null=True) # Since 2019-12-08\n leg_puistodiff_time_pm = models.IntegerField(blank=True, null=True) # Since 2019-12-08\n leg_puistoperc_time_l = models.FloatField(null=True) # Since 2019-12-08\n leg_puistoperc_time_pm = models.FloatField(null=True) # Since 2019-12-08\n leg_puistoperc_time_l = models.FloatField(null=True) # Since 2019-12-08\n leg_puisto_success = models.FloatField(null=True) # Since 2019-12-08\n result_puistoperc_time_l = models.FloatField(null=True) # Since 2019-12-08\n result_puistoperc_time_pm = models.FloatField(null=True) # Since 2019-12-08\n result_puisto_max_level = models.FloatField(null=True) # Since 2019-12-08\n result_puisto_success = models.FloatField(null=True) # Since 2019-12-08\n result_puisto_optimum = models.IntegerField(null=True) # Since 2019-12-08\n result_puisto_mistakes = models.IntegerField(null=True) # Since 2019-12-08\n\n class Meta:\n managed = False\n db_table = 'NavigantAnalyzer_results_flat'\n\n def get_fields(self):\n result = dict()\n datetime_fields = ['race_begin', 'result_start_time']\n for field in Results_flat._meta.fields:\n value = field.value_to_string(self)\n if value.isdigit():\n value = int(value)\n if field.name in datetime_fields:\n value = convert_datetime_string(value)\n result[field.name] = value\n return json.dumps(result)\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
#!/usr/bin/env python
# coding: utf-8
# MIT Licensed
# http://opensource.org/licenses/MIT
led_dir = "/sys/class/gpio/gpio40/"
led_pin = led_dir + "value"
led_mode = led_dir + "direction"
with open(led_mode, "wb") as f:
f.write("out")
with open(led_pin, "wb") as f:
f.write(__import__("sys").argv[1])
"""
Contributors!
Danilo J. S. Bellini
Estevão U. P. Vieira
Lucas S. Simões
Thiago M. Sanches
Paulo R. O. Castro
AEEEW!!!! =D
"""
|
normal
|
{
"blob_id": "1a9cad6e49e5ed2bb7781f9fec930d48ec048b3b",
"index": 5061,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwith open(led_mode, 'wb') as f:\n f.write('out')\nwith open(led_pin, 'wb') as f:\n f.write(__import__('sys').argv[1])\n<mask token>\n",
"step-3": "led_dir = '/sys/class/gpio/gpio40/'\nled_pin = led_dir + 'value'\nled_mode = led_dir + 'direction'\nwith open(led_mode, 'wb') as f:\n f.write('out')\nwith open(led_pin, 'wb') as f:\n f.write(__import__('sys').argv[1])\n<mask token>\n",
"step-4": "#!/usr/bin/env python\n# coding: utf-8\n\n# MIT Licensed\n# http://opensource.org/licenses/MIT\n\nled_dir = \"/sys/class/gpio/gpio40/\"\nled_pin = led_dir + \"value\"\nled_mode = led_dir + \"direction\"\n\nwith open(led_mode, \"wb\") as f:\n f.write(\"out\")\n\nwith open(led_pin, \"wb\") as f:\n f.write(__import__(\"sys\").argv[1])\n\n\"\"\"\nContributors!\n\nDanilo J. S. Bellini\nEstevão U. P. Vieira\nLucas S. Simões\nThiago M. Sanches\nPaulo R. O. Castro\n\nAEEEW!!!! =D\n\"\"\"\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
class Recipe:
<|reserved_special_token_0|>
def __init__(self, labor_amount: float, required_goods: BagOfGoods,
planet_variation: Distribution, person_variation: Distribution,
labor_variation: Distribution, output_good: GoodKind):
self.labor_amount = labor_amount
self.required_goods = required_goods
self.planet_variation = planet_variation
self.person_variation = person_variation
self.labor_variation = labor_variation
self.output_good = output_good
<|reserved_special_token_0|>
def draw_person_variation(self):
return max(0, self.person_variation.draw())
<|reserved_special_token_0|>
def determine_required_goods(self, output_amount: int):
"""
Determines the amount of goods and labor required for a given amount of
output. Basically does a multiplication
"""
required_goods = self.required_goods.several(output_amount)
required_labor = self.labor_amount * output_amount
return required_goods, required_labor
<|reserved_special_token_0|>
<|reserved_special_token_0|>
class FactoryKind:
def __init__(self, recipe: Recipe, rate: float, name: str=''):
self.name = name
self.rate = rate
self.recipe = recipe
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Recipe:
<|reserved_special_token_0|>
def __init__(self, labor_amount: float, required_goods: BagOfGoods,
planet_variation: Distribution, person_variation: Distribution,
labor_variation: Distribution, output_good: GoodKind):
self.labor_amount = labor_amount
self.required_goods = required_goods
self.planet_variation = planet_variation
self.person_variation = person_variation
self.labor_variation = labor_variation
self.output_good = output_good
def draw_planet_variation(self):
return max(0, self.planet_variation.draw())
def draw_person_variation(self):
return max(0, self.person_variation.draw())
def draw_labor_variation(self):
return max(0, self.labor_variation.draw())
def determine_required_goods(self, output_amount: int):
"""
Determines the amount of goods and labor required for a given amount of
output. Basically does a multiplication
"""
required_goods = self.required_goods.several(output_amount)
required_labor = self.labor_amount * output_amount
return required_goods, required_labor
def __hash__(self):
return hash(repr(self))
<|reserved_special_token_0|>
class FactoryKind:
def __init__(self, recipe: Recipe, rate: float, name: str=''):
self.name = name
self.rate = rate
self.recipe = recipe
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class GoodKind:
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
class BagOfGoods(Counter):
def several(self, times: int):
"""
Returns a new bag of goods containing a set of goods that is a
multiple (times) of the callee.
"""
return BagOfGoods({g: (self[g] * times) for g in self.keys()})
def divide(self, other: BagOfGoods):
"""
Divides one bag of goods by another. Returns the quotient as an
integer. (Whole number quotients, only. "Natural" division, no
negatives, floats, etc.)
"""
if not any(other.elements()):
raise ZeroDivisionError()
return min(self[g] // other[g] for g in other.keys())
def divide_with_remainder(self, other: BagOfGoods):
"""
Like divide(), but returns the quotent and a new bag of goods representing the remainder
after division.
"""
quotient = self.divide(other)
remainder = BagOfGoods({g: (self[g] - other[g] * quotient) for g in
self.keys()})
return quotient, remainder
def equals(self, other: BagOfGoods):
if self.keys() != other.keys():
return False
for good in (self | other):
if self[good] != other[good]:
return False
return True
class Recipe:
"""
An accounting of the goods and labor needed to produce something. An
invocation of a recipe produces one output
"""
def __init__(self, labor_amount: float, required_goods: BagOfGoods,
planet_variation: Distribution, person_variation: Distribution,
labor_variation: Distribution, output_good: GoodKind):
self.labor_amount = labor_amount
self.required_goods = required_goods
self.planet_variation = planet_variation
self.person_variation = person_variation
self.labor_variation = labor_variation
self.output_good = output_good
def draw_planet_variation(self):
return max(0, self.planet_variation.draw())
def draw_person_variation(self):
return max(0, self.person_variation.draw())
def draw_labor_variation(self):
return max(0, self.labor_variation.draw())
def determine_required_goods(self, output_amount: int):
"""
Determines the amount of goods and labor required for a given amount of
output. Basically does a multiplication
"""
required_goods = self.required_goods.several(output_amount)
required_labor = self.labor_amount * output_amount
return required_goods, required_labor
def __hash__(self):
return hash(repr(self))
def __str__(self):
return f"Recipe(for '{self.output_good}')"
class FactoryKind:
def __init__(self, recipe: Recipe, rate: float, name: str=''):
self.name = name
self.rate = rate
self.recipe = recipe
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class GoodKind:
"""
The definition of a kind of good. "Vegtable" is a kind of good, as is
"Iron Ore", "Rocket Fuel", and "Electic Motor"
"""
def __init__(self, name: str):
assert len(name) > 0
self.name = name
def __hash__(self):
return hash(repr(self))
def __repr__(self):
return f"GoodKind('{self.name}')"
class BagOfGoods(Counter):
def several(self, times: int):
"""
Returns a new bag of goods containing a set of goods that is a
multiple (times) of the callee.
"""
return BagOfGoods({g: (self[g] * times) for g in self.keys()})
def divide(self, other: BagOfGoods):
"""
Divides one bag of goods by another. Returns the quotient as an
integer. (Whole number quotients, only. "Natural" division, no
negatives, floats, etc.)
"""
if not any(other.elements()):
raise ZeroDivisionError()
return min(self[g] // other[g] for g in other.keys())
def divide_with_remainder(self, other: BagOfGoods):
"""
Like divide(), but returns the quotent and a new bag of goods representing the remainder
after division.
"""
quotient = self.divide(other)
remainder = BagOfGoods({g: (self[g] - other[g] * quotient) for g in
self.keys()})
return quotient, remainder
def equals(self, other: BagOfGoods):
if self.keys() != other.keys():
return False
for good in (self | other):
if self[good] != other[good]:
return False
return True
class Recipe:
"""
An accounting of the goods and labor needed to produce something. An
invocation of a recipe produces one output
"""
def __init__(self, labor_amount: float, required_goods: BagOfGoods,
planet_variation: Distribution, person_variation: Distribution,
labor_variation: Distribution, output_good: GoodKind):
self.labor_amount = labor_amount
self.required_goods = required_goods
self.planet_variation = planet_variation
self.person_variation = person_variation
self.labor_variation = labor_variation
self.output_good = output_good
def draw_planet_variation(self):
return max(0, self.planet_variation.draw())
def draw_person_variation(self):
return max(0, self.person_variation.draw())
def draw_labor_variation(self):
return max(0, self.labor_variation.draw())
def determine_required_goods(self, output_amount: int):
"""
Determines the amount of goods and labor required for a given amount of
output. Basically does a multiplication
"""
required_goods = self.required_goods.several(output_amount)
required_labor = self.labor_amount * output_amount
return required_goods, required_labor
def __hash__(self):
return hash(repr(self))
def __str__(self):
return f"Recipe(for '{self.output_good}')"
class FactoryKind:
def __init__(self, recipe: Recipe, rate: float, name: str=''):
self.name = name
self.rate = rate
self.recipe = recipe
<|reserved_special_token_0|>
def generate_good(good_name: str):
good = GoodKind(good_name)
good_index[good_name] = good
return good
<|reserved_special_token_0|>
def generate_basic_recipe(labor: int, good: GoodKind, planet_variation:
Distribution, person_variation: Distribution, labor_variation:
Distribution, required_goods=BagOfGoods()):
recipe = Recipe(labor, required_goods, planet_variation,
person_variation, labor_variation, good)
basic_recipe_index[good.name] = recipe
return recipe
<|reserved_special_token_0|>
<|reserved_special_token_1|>
from __future__ import annotations
from collections import Counter
from distribution import Distribution, Normal
class GoodKind:
"""
The definition of a kind of good. "Vegtable" is a kind of good, as is
"Iron Ore", "Rocket Fuel", and "Electic Motor"
"""
def __init__(self, name: str):
assert len(name) > 0
self.name = name
def __hash__(self):
# Implimenting hash so I can use this in dictionaries
# TODO, look again at Dataclasses
return hash(repr(self))
def __repr__(self):
return f"GoodKind('{self.name}')"
class BagOfGoods(Counter):
def several(self, times: int):
"""
Returns a new bag of goods containing a set of goods that is a
multiple (times) of the callee.
"""
return BagOfGoods({g: self[g] * times for g in self.keys()})
def divide(self, other: BagOfGoods):
"""
Divides one bag of goods by another. Returns the quotient as an
integer. (Whole number quotients, only. "Natural" division, no
negatives, floats, etc.)
"""
if not any(other.elements()):
raise ZeroDivisionError()
return min((self[g] // other[g] for g in other.keys()))
def divide_with_remainder(self, other: BagOfGoods):
"""
Like divide(), but returns the quotent and a new bag of goods representing the remainder
after division.
"""
quotient = self.divide(other)
remainder = BagOfGoods({g: self[g] - other[g] * quotient for g in self.keys()})
return quotient, remainder
def equals(self, other: BagOfGoods):
if self.keys() != other.keys():
return False
for good in self | other:
if self[good] != other[good]:
return False
return True
class Recipe:
"""
An accounting of the goods and labor needed to produce something. An
invocation of a recipe produces one output
"""
def __init__(
self,
labor_amount: float,
required_goods: BagOfGoods,
planet_variation: Distribution,
person_variation: Distribution,
labor_variation: Distribution,
output_good: GoodKind,
):
self.labor_amount = labor_amount
self.required_goods = required_goods
self.planet_variation = planet_variation
self.person_variation = person_variation
self.labor_variation = labor_variation
self.output_good = output_good
def draw_planet_variation(self):
return max(0, self.planet_variation.draw())
def draw_person_variation(self):
return max(0, self.person_variation.draw())
def draw_labor_variation(self):
return max(0, self.labor_variation.draw())
def determine_required_goods(self, output_amount: int):
"""
Determines the amount of goods and labor required for a given amount of
output. Basically does a multiplication
"""
required_goods = self.required_goods.several(output_amount)
required_labor = self.labor_amount * output_amount
return required_goods, required_labor
def __hash__(self):
# Implimenting hash so I can use this in dictionaries
# TODO, look again at Dataclasses1G
return hash(repr(self))
def __str__(self):
return f"Recipe(for '{self.output_good}')"
class FactoryKind:
def __init__(self, recipe: Recipe, rate: float, name: str = ""):
self.name = name
self.rate = rate
self.recipe = recipe
good_index = {}
def generate_good(good_name: str):
good = GoodKind(good_name)
good_index[good_name] = good
return good
food = generate_good("Food")
wood = generate_good("Wood")
basic_recipe_index = {}
def generate_basic_recipe(
labor: int,
good: GoodKind,
planet_variation: Distribution,
person_variation: Distribution,
labor_variation: Distribution,
required_goods=BagOfGoods(),
):
recipe = Recipe(
labor, required_goods, planet_variation, person_variation, labor_variation, good
)
basic_recipe_index[good.name] = recipe
return recipe
basic_food_recipe = generate_basic_recipe(
1, food, Normal(0.75, 0.5), Normal(1, 0.3), Normal(1, 0.05)
)
basic_wood_recipe = generate_basic_recipe(
1, wood, Normal(1, 0.5), Normal(1, 0.2), Normal(1, 0.05)
)
|
flexible
|
{
"blob_id": "286801b69546046853d123c5708f24eaaa2e8cec",
"index": 6044,
"step-1": "<mask token>\n\n\nclass Recipe:\n <mask token>\n\n def __init__(self, labor_amount: float, required_goods: BagOfGoods,\n planet_variation: Distribution, person_variation: Distribution,\n labor_variation: Distribution, output_good: GoodKind):\n self.labor_amount = labor_amount\n self.required_goods = required_goods\n self.planet_variation = planet_variation\n self.person_variation = person_variation\n self.labor_variation = labor_variation\n self.output_good = output_good\n <mask token>\n\n def draw_person_variation(self):\n return max(0, self.person_variation.draw())\n <mask token>\n\n def determine_required_goods(self, output_amount: int):\n \"\"\"\n Determines the amount of goods and labor required for a given amount of\n output. Basically does a multiplication\n \"\"\"\n required_goods = self.required_goods.several(output_amount)\n required_labor = self.labor_amount * output_amount\n return required_goods, required_labor\n <mask token>\n <mask token>\n\n\nclass FactoryKind:\n\n def __init__(self, recipe: Recipe, rate: float, name: str=''):\n self.name = name\n self.rate = rate\n self.recipe = recipe\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass Recipe:\n <mask token>\n\n def __init__(self, labor_amount: float, required_goods: BagOfGoods,\n planet_variation: Distribution, person_variation: Distribution,\n labor_variation: Distribution, output_good: GoodKind):\n self.labor_amount = labor_amount\n self.required_goods = required_goods\n self.planet_variation = planet_variation\n self.person_variation = person_variation\n self.labor_variation = labor_variation\n self.output_good = output_good\n\n def draw_planet_variation(self):\n return max(0, self.planet_variation.draw())\n\n def draw_person_variation(self):\n return max(0, self.person_variation.draw())\n\n def draw_labor_variation(self):\n return max(0, self.labor_variation.draw())\n\n def determine_required_goods(self, output_amount: int):\n \"\"\"\n Determines the amount of goods and labor required for a given amount of\n output. Basically does a multiplication\n \"\"\"\n required_goods = self.required_goods.several(output_amount)\n required_labor = self.labor_amount * output_amount\n return required_goods, required_labor\n\n def __hash__(self):\n return hash(repr(self))\n <mask token>\n\n\nclass FactoryKind:\n\n def __init__(self, recipe: Recipe, rate: float, name: str=''):\n self.name = name\n self.rate = rate\n self.recipe = recipe\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass GoodKind:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass BagOfGoods(Counter):\n\n def several(self, times: int):\n \"\"\"\n Returns a new bag of goods containing a set of goods that is a\n multiple (times) of the callee.\n \"\"\"\n return BagOfGoods({g: (self[g] * times) for g in self.keys()})\n\n def divide(self, other: BagOfGoods):\n \"\"\"\n Divides one bag of goods by another. Returns the quotient as an\n integer. (Whole number quotients, only. \"Natural\" division, no\n negatives, floats, etc.)\n \"\"\"\n if not any(other.elements()):\n raise ZeroDivisionError()\n return min(self[g] // other[g] for g in other.keys())\n\n def divide_with_remainder(self, other: BagOfGoods):\n \"\"\"\n Like divide(), but returns the quotent and a new bag of goods representing the remainder\n after division.\n \"\"\"\n quotient = self.divide(other)\n remainder = BagOfGoods({g: (self[g] - other[g] * quotient) for g in\n self.keys()})\n return quotient, remainder\n\n def equals(self, other: BagOfGoods):\n if self.keys() != other.keys():\n return False\n for good in (self | other):\n if self[good] != other[good]:\n return False\n return True\n\n\nclass Recipe:\n \"\"\"\n An accounting of the goods and labor needed to produce something. An\n invocation of a recipe produces one output\n \"\"\"\n\n def __init__(self, labor_amount: float, required_goods: BagOfGoods,\n planet_variation: Distribution, person_variation: Distribution,\n labor_variation: Distribution, output_good: GoodKind):\n self.labor_amount = labor_amount\n self.required_goods = required_goods\n self.planet_variation = planet_variation\n self.person_variation = person_variation\n self.labor_variation = labor_variation\n self.output_good = output_good\n\n def draw_planet_variation(self):\n return max(0, self.planet_variation.draw())\n\n def draw_person_variation(self):\n return max(0, self.person_variation.draw())\n\n def draw_labor_variation(self):\n return max(0, self.labor_variation.draw())\n\n def determine_required_goods(self, output_amount: int):\n \"\"\"\n Determines the amount of goods and labor required for a given amount of\n output. Basically does a multiplication\n \"\"\"\n required_goods = self.required_goods.several(output_amount)\n required_labor = self.labor_amount * output_amount\n return required_goods, required_labor\n\n def __hash__(self):\n return hash(repr(self))\n\n def __str__(self):\n return f\"Recipe(for '{self.output_good}')\"\n\n\nclass FactoryKind:\n\n def __init__(self, recipe: Recipe, rate: float, name: str=''):\n self.name = name\n self.rate = rate\n self.recipe = recipe\n\n\n<mask token>\n",
"step-4": "<mask token>\n\n\nclass GoodKind:\n \"\"\"\n The definition of a kind of good. \"Vegtable\" is a kind of good, as is \n \"Iron Ore\", \"Rocket Fuel\", and \"Electic Motor\"\n \"\"\"\n\n def __init__(self, name: str):\n assert len(name) > 0\n self.name = name\n\n def __hash__(self):\n return hash(repr(self))\n\n def __repr__(self):\n return f\"GoodKind('{self.name}')\"\n\n\nclass BagOfGoods(Counter):\n\n def several(self, times: int):\n \"\"\"\n Returns a new bag of goods containing a set of goods that is a\n multiple (times) of the callee.\n \"\"\"\n return BagOfGoods({g: (self[g] * times) for g in self.keys()})\n\n def divide(self, other: BagOfGoods):\n \"\"\"\n Divides one bag of goods by another. Returns the quotient as an\n integer. (Whole number quotients, only. \"Natural\" division, no\n negatives, floats, etc.)\n \"\"\"\n if not any(other.elements()):\n raise ZeroDivisionError()\n return min(self[g] // other[g] for g in other.keys())\n\n def divide_with_remainder(self, other: BagOfGoods):\n \"\"\"\n Like divide(), but returns the quotent and a new bag of goods representing the remainder\n after division.\n \"\"\"\n quotient = self.divide(other)\n remainder = BagOfGoods({g: (self[g] - other[g] * quotient) for g in\n self.keys()})\n return quotient, remainder\n\n def equals(self, other: BagOfGoods):\n if self.keys() != other.keys():\n return False\n for good in (self | other):\n if self[good] != other[good]:\n return False\n return True\n\n\nclass Recipe:\n \"\"\"\n An accounting of the goods and labor needed to produce something. An\n invocation of a recipe produces one output\n \"\"\"\n\n def __init__(self, labor_amount: float, required_goods: BagOfGoods,\n planet_variation: Distribution, person_variation: Distribution,\n labor_variation: Distribution, output_good: GoodKind):\n self.labor_amount = labor_amount\n self.required_goods = required_goods\n self.planet_variation = planet_variation\n self.person_variation = person_variation\n self.labor_variation = labor_variation\n self.output_good = output_good\n\n def draw_planet_variation(self):\n return max(0, self.planet_variation.draw())\n\n def draw_person_variation(self):\n return max(0, self.person_variation.draw())\n\n def draw_labor_variation(self):\n return max(0, self.labor_variation.draw())\n\n def determine_required_goods(self, output_amount: int):\n \"\"\"\n Determines the amount of goods and labor required for a given amount of\n output. Basically does a multiplication\n \"\"\"\n required_goods = self.required_goods.several(output_amount)\n required_labor = self.labor_amount * output_amount\n return required_goods, required_labor\n\n def __hash__(self):\n return hash(repr(self))\n\n def __str__(self):\n return f\"Recipe(for '{self.output_good}')\"\n\n\nclass FactoryKind:\n\n def __init__(self, recipe: Recipe, rate: float, name: str=''):\n self.name = name\n self.rate = rate\n self.recipe = recipe\n\n\n<mask token>\n\n\ndef generate_good(good_name: str):\n good = GoodKind(good_name)\n good_index[good_name] = good\n return good\n\n\n<mask token>\n\n\ndef generate_basic_recipe(labor: int, good: GoodKind, planet_variation:\n Distribution, person_variation: Distribution, labor_variation:\n Distribution, required_goods=BagOfGoods()):\n recipe = Recipe(labor, required_goods, planet_variation,\n person_variation, labor_variation, good)\n basic_recipe_index[good.name] = recipe\n return recipe\n\n\n<mask token>\n",
"step-5": "from __future__ import annotations\nfrom collections import Counter\nfrom distribution import Distribution, Normal\n\n\nclass GoodKind:\n \"\"\"\n The definition of a kind of good. \"Vegtable\" is a kind of good, as is \n \"Iron Ore\", \"Rocket Fuel\", and \"Electic Motor\"\n \"\"\"\n\n def __init__(self, name: str):\n assert len(name) > 0\n\n self.name = name\n\n def __hash__(self):\n # Implimenting hash so I can use this in dictionaries\n # TODO, look again at Dataclasses\n return hash(repr(self))\n\n def __repr__(self):\n return f\"GoodKind('{self.name}')\"\n\n\nclass BagOfGoods(Counter):\n def several(self, times: int):\n \"\"\"\n Returns a new bag of goods containing a set of goods that is a\n multiple (times) of the callee.\n \"\"\"\n return BagOfGoods({g: self[g] * times for g in self.keys()})\n\n def divide(self, other: BagOfGoods):\n \"\"\"\n Divides one bag of goods by another. Returns the quotient as an\n integer. (Whole number quotients, only. \"Natural\" division, no\n negatives, floats, etc.)\n \"\"\"\n if not any(other.elements()):\n raise ZeroDivisionError()\n return min((self[g] // other[g] for g in other.keys()))\n\n def divide_with_remainder(self, other: BagOfGoods):\n \"\"\"\n Like divide(), but returns the quotent and a new bag of goods representing the remainder\n after division.\n \"\"\"\n quotient = self.divide(other)\n remainder = BagOfGoods({g: self[g] - other[g] * quotient for g in self.keys()})\n\n return quotient, remainder\n\n def equals(self, other: BagOfGoods):\n if self.keys() != other.keys():\n return False\n\n for good in self | other:\n if self[good] != other[good]:\n return False\n\n return True\n\n\nclass Recipe:\n \"\"\"\n An accounting of the goods and labor needed to produce something. An\n invocation of a recipe produces one output\n \"\"\"\n\n def __init__(\n self,\n labor_amount: float,\n required_goods: BagOfGoods,\n planet_variation: Distribution,\n person_variation: Distribution,\n labor_variation: Distribution,\n output_good: GoodKind,\n ):\n self.labor_amount = labor_amount\n self.required_goods = required_goods\n self.planet_variation = planet_variation\n self.person_variation = person_variation\n self.labor_variation = labor_variation\n self.output_good = output_good\n\n def draw_planet_variation(self):\n return max(0, self.planet_variation.draw())\n\n def draw_person_variation(self):\n return max(0, self.person_variation.draw())\n\n def draw_labor_variation(self):\n return max(0, self.labor_variation.draw())\n\n def determine_required_goods(self, output_amount: int):\n \"\"\"\n Determines the amount of goods and labor required for a given amount of\n output. Basically does a multiplication\n \"\"\"\n required_goods = self.required_goods.several(output_amount)\n required_labor = self.labor_amount * output_amount\n return required_goods, required_labor\n\n def __hash__(self):\n # Implimenting hash so I can use this in dictionaries\n # TODO, look again at Dataclasses1G\n return hash(repr(self))\n\n def __str__(self):\n return f\"Recipe(for '{self.output_good}')\"\n\n\nclass FactoryKind:\n def __init__(self, recipe: Recipe, rate: float, name: str = \"\"):\n self.name = name\n self.rate = rate\n self.recipe = recipe\n\n\ngood_index = {}\n\n\ndef generate_good(good_name: str):\n good = GoodKind(good_name)\n good_index[good_name] = good\n return good\n\n\nfood = generate_good(\"Food\")\nwood = generate_good(\"Wood\")\n\nbasic_recipe_index = {}\n\n\ndef generate_basic_recipe(\n labor: int,\n good: GoodKind,\n planet_variation: Distribution,\n person_variation: Distribution,\n labor_variation: Distribution,\n required_goods=BagOfGoods(),\n):\n recipe = Recipe(\n labor, required_goods, planet_variation, person_variation, labor_variation, good\n )\n basic_recipe_index[good.name] = recipe\n return recipe\n\n\nbasic_food_recipe = generate_basic_recipe(\n 1, food, Normal(0.75, 0.5), Normal(1, 0.3), Normal(1, 0.05)\n)\nbasic_wood_recipe = generate_basic_recipe(\n 1, wood, Normal(1, 0.5), Normal(1, 0.2), Normal(1, 0.05)\n)\n",
"step-ids": [
6,
9,
17,
23,
26
]
}
|
[
6,
9,
17,
23,
26
] |
<|reserved_special_token_0|>
def make_Folders(names):
for n in names:
if not os.path.exists(n):
os.makedirs(n)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def make_Folders(names):
for n in names:
if not os.path.exists(n):
os.makedirs(n)
make_Folders(timeslices)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
timeslices = [('0_' + str(x) + '_' + str(y)) for x in range(30, 100) for y in
range(0, 6)]
def make_Folders(names):
for n in names:
if not os.path.exists(n):
os.makedirs(n)
make_Folders(timeslices)
<|reserved_special_token_1|>
import os
timeslices = [('0_' + str(x) + '_' + str(y)) for x in range(30, 100) for y in
range(0, 6)]
def make_Folders(names):
for n in names:
if not os.path.exists(n):
os.makedirs(n)
make_Folders(timeslices)
<|reserved_special_token_1|>
import os
timeslices = ['0_' + str(x) + '_' + str(y) for x in range(30,100) for y in range(0,6)]
#print timeslices
def make_Folders(names):
for n in names:
if not os.path.exists(n):
os.makedirs(n)
make_Folders(timeslices)
|
flexible
|
{
"blob_id": "426396c981fe56230e39b81e156e7c6877e39055",
"index": 2213,
"step-1": "<mask token>\n\n\ndef make_Folders(names):\n for n in names:\n if not os.path.exists(n):\n os.makedirs(n)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef make_Folders(names):\n for n in names:\n if not os.path.exists(n):\n os.makedirs(n)\n\n\nmake_Folders(timeslices)\n",
"step-3": "<mask token>\ntimeslices = [('0_' + str(x) + '_' + str(y)) for x in range(30, 100) for y in\n range(0, 6)]\n\n\ndef make_Folders(names):\n for n in names:\n if not os.path.exists(n):\n os.makedirs(n)\n\n\nmake_Folders(timeslices)\n",
"step-4": "import os\ntimeslices = [('0_' + str(x) + '_' + str(y)) for x in range(30, 100) for y in\n range(0, 6)]\n\n\ndef make_Folders(names):\n for n in names:\n if not os.path.exists(n):\n os.makedirs(n)\n\n\nmake_Folders(timeslices)\n",
"step-5": "import os\n\n\ntimeslices = ['0_' + str(x) + '_' + str(y) for x in range(30,100) for y in range(0,6)]\n\n#print timeslices\n\n\ndef make_Folders(names):\n for n in names:\n if not os.path.exists(n):\n os.makedirs(n)\n\nmake_Folders(timeslices)\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
<|reserved_special_token_0|>
class User(db.Model):
<|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|>
<|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|>
@classmethod
def all_data(cls):
all_data = db.GqlQuery('SELECT *FROM User')
return list(all_data)
@classmethod
def set_email(cls, id, email):
user = User.get_by_key_name(id)
penn_id = email.split('@')[0]
user.email = email
user.penn_id = penn_id
user.put()
@classmethod
def is_email_verified(cls, email):
data = User.all_data()
if data is not None:
all_emails = {user.email: user.email_verified for user in data}
logging.info('all email information ' + str(all_emails))
return all_emails.get(email, False)
@classmethod
def is_pennid_verified(cls, email):
penn_id = email.split('@')[0]
all_data = User.all_data()
if all_data is not None:
all_penn_ids = {user.penn_id: user.email_verified for user in
all_data}
logging.info('all penn id information' + str(all_penn_ids))
return all_penn_ids.get(penn_id, False)
class Answer(db.Model):
answer = db.TextProperty(required=True)
answered_by = db.StringProperty(required=True)
answerer_name = db.StringProperty(required=True)
upvoted_by = db.ListProperty(str)
def get_votes(self):
return len(self.upvoted_by)
def get_upvote_link(self):
return '/q/question/upvote/%s' % self.key().id()
<|reserved_special_token_0|>
class Question(db.Model):
question = db.TextProperty(required=True)
created = db.DateTimeProperty(auto_now_add=True)
last_modified = db.DateTimeProperty(auto_now=True)
answers = db.ListProperty(item_type=db.Key, required=True)
asked_by = db.StringProperty(required=True)
asker_name = db.StringProperty(required=True)
def render(self):
self._render_text = self.question.replace('\n', '<br>')
return render_str('question.html', q=self)
def as_dict(self):
time_fmt = '%c'
d = {'question': self.question, 'created': self.created.strftime(
time_fmt), 'last_modified': self.last_modified.strftime(time_fmt)}
return d
def link(self):
qid = self.key().id()
href_link = '/q/question/%s' % str(qid)
return href_link
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class User(db.Model):
id = db.StringProperty(required=True)
created = db.DateTimeProperty(auto_now_add=True)
updated = db.DateTimeProperty(auto_now=True)
name = db.StringProperty(required=True)
profile_url = db.StringProperty(required=True)
access_token = db.StringProperty(required=True)
email = db.StringProperty(required=False)
penn_id = db.StringProperty(required=False)
email_verified = db.BooleanProperty(required=True)
verification_code = db.StringProperty(required=True)
chair = db.StringProperty(required=False)
vicechair = db.StringProperty(required=False)
treasurer = db.StringProperty(required=False)
socialchair = db.StringProperty(required=False)
operationschair = db.StringProperty(required=False)
gapsaliason = db.StringProperty(required=False)
communicationschair = db.StringProperty(required=False)
webadmin = db.StringProperty(required=False)
marketingchair = db.StringProperty(required=False)
chair_count = db.IntegerProperty(required=False, default=0)
vicechair_count = db.IntegerProperty(required=False, default=0)
treasurer_count = db.IntegerProperty(required=False, default=0)
socialchair_count = db.IntegerProperty(required=False, default=0)
operationschair_count = db.IntegerProperty(required=False, default=0)
gapsaliason_count = db.IntegerProperty(required=False, default=0)
communicationschair_count = db.IntegerProperty(required=False, default=0)
webadmin_count = db.IntegerProperty(required=False, default=0)
marketingchair_count = db.IntegerProperty(required=False, default=0)
@classmethod
def all_data(cls):
all_data = db.GqlQuery('SELECT *FROM User')
return list(all_data)
@classmethod
def set_email(cls, id, email):
user = User.get_by_key_name(id)
penn_id = email.split('@')[0]
user.email = email
user.penn_id = penn_id
user.put()
@classmethod
def is_email_verified(cls, email):
data = User.all_data()
if data is not None:
all_emails = {user.email: user.email_verified for user in data}
logging.info('all email information ' + str(all_emails))
return all_emails.get(email, False)
@classmethod
def is_pennid_verified(cls, email):
penn_id = email.split('@')[0]
all_data = User.all_data()
if all_data is not None:
all_penn_ids = {user.penn_id: user.email_verified for user in
all_data}
logging.info('all penn id information' + str(all_penn_ids))
return all_penn_ids.get(penn_id, False)
class Answer(db.Model):
answer = db.TextProperty(required=True)
answered_by = db.StringProperty(required=True)
answerer_name = db.StringProperty(required=True)
upvoted_by = db.ListProperty(str)
def get_votes(self):
return len(self.upvoted_by)
def get_upvote_link(self):
return '/q/question/upvote/%s' % self.key().id()
<|reserved_special_token_0|>
class Question(db.Model):
question = db.TextProperty(required=True)
created = db.DateTimeProperty(auto_now_add=True)
last_modified = db.DateTimeProperty(auto_now=True)
answers = db.ListProperty(item_type=db.Key, required=True)
asked_by = db.StringProperty(required=True)
asker_name = db.StringProperty(required=True)
def render(self):
self._render_text = self.question.replace('\n', '<br>')
return render_str('question.html', q=self)
def as_dict(self):
time_fmt = '%c'
d = {'question': self.question, 'created': self.created.strftime(
time_fmt), 'last_modified': self.last_modified.strftime(time_fmt)}
return d
def link(self):
qid = self.key().id()
href_link = '/q/question/%s' % str(qid)
return href_link
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class User(db.Model):
id = db.StringProperty(required=True)
created = db.DateTimeProperty(auto_now_add=True)
updated = db.DateTimeProperty(auto_now=True)
name = db.StringProperty(required=True)
profile_url = db.StringProperty(required=True)
access_token = db.StringProperty(required=True)
email = db.StringProperty(required=False)
penn_id = db.StringProperty(required=False)
email_verified = db.BooleanProperty(required=True)
verification_code = db.StringProperty(required=True)
chair = db.StringProperty(required=False)
vicechair = db.StringProperty(required=False)
treasurer = db.StringProperty(required=False)
socialchair = db.StringProperty(required=False)
operationschair = db.StringProperty(required=False)
gapsaliason = db.StringProperty(required=False)
communicationschair = db.StringProperty(required=False)
webadmin = db.StringProperty(required=False)
marketingchair = db.StringProperty(required=False)
chair_count = db.IntegerProperty(required=False, default=0)
vicechair_count = db.IntegerProperty(required=False, default=0)
treasurer_count = db.IntegerProperty(required=False, default=0)
socialchair_count = db.IntegerProperty(required=False, default=0)
operationschair_count = db.IntegerProperty(required=False, default=0)
gapsaliason_count = db.IntegerProperty(required=False, default=0)
communicationschair_count = db.IntegerProperty(required=False, default=0)
webadmin_count = db.IntegerProperty(required=False, default=0)
marketingchair_count = db.IntegerProperty(required=False, default=0)
@classmethod
def all_data(cls):
all_data = db.GqlQuery('SELECT *FROM User')
return list(all_data)
@classmethod
def set_email(cls, id, email):
user = User.get_by_key_name(id)
penn_id = email.split('@')[0]
user.email = email
user.penn_id = penn_id
user.put()
@classmethod
def is_email_verified(cls, email):
data = User.all_data()
if data is not None:
all_emails = {user.email: user.email_verified for user in data}
logging.info('all email information ' + str(all_emails))
return all_emails.get(email, False)
@classmethod
def is_pennid_verified(cls, email):
penn_id = email.split('@')[0]
all_data = User.all_data()
if all_data is not None:
all_penn_ids = {user.penn_id: user.email_verified for user in
all_data}
logging.info('all penn id information' + str(all_penn_ids))
return all_penn_ids.get(penn_id, False)
class Answer(db.Model):
answer = db.TextProperty(required=True)
answered_by = db.StringProperty(required=True)
answerer_name = db.StringProperty(required=True)
upvoted_by = db.ListProperty(str)
def get_votes(self):
return len(self.upvoted_by)
def get_upvote_link(self):
return '/q/question/upvote/%s' % self.key().id()
def render_str(template, **params):
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(
template_dir), autoescape=True)
t = jinja_environment.get_template(template)
return t.render(params)
class Question(db.Model):
question = db.TextProperty(required=True)
created = db.DateTimeProperty(auto_now_add=True)
last_modified = db.DateTimeProperty(auto_now=True)
answers = db.ListProperty(item_type=db.Key, required=True)
asked_by = db.StringProperty(required=True)
asker_name = db.StringProperty(required=True)
def render(self):
self._render_text = self.question.replace('\n', '<br>')
return render_str('question.html', q=self)
def as_dict(self):
time_fmt = '%c'
d = {'question': self.question, 'created': self.created.strftime(
time_fmt), 'last_modified': self.last_modified.strftime(time_fmt)}
return d
def link(self):
qid = self.key().id()
href_link = '/q/question/%s' % str(qid)
return href_link
<|reserved_special_token_1|>
__author__ = 'Chitrang'
<|reserved_special_token_0|>
class User(db.Model):
id = db.StringProperty(required=True)
created = db.DateTimeProperty(auto_now_add=True)
updated = db.DateTimeProperty(auto_now=True)
name = db.StringProperty(required=True)
profile_url = db.StringProperty(required=True)
access_token = db.StringProperty(required=True)
email = db.StringProperty(required=False)
penn_id = db.StringProperty(required=False)
email_verified = db.BooleanProperty(required=True)
verification_code = db.StringProperty(required=True)
chair = db.StringProperty(required=False)
vicechair = db.StringProperty(required=False)
treasurer = db.StringProperty(required=False)
socialchair = db.StringProperty(required=False)
operationschair = db.StringProperty(required=False)
gapsaliason = db.StringProperty(required=False)
communicationschair = db.StringProperty(required=False)
webadmin = db.StringProperty(required=False)
marketingchair = db.StringProperty(required=False)
chair_count = db.IntegerProperty(required=False, default=0)
vicechair_count = db.IntegerProperty(required=False, default=0)
treasurer_count = db.IntegerProperty(required=False, default=0)
socialchair_count = db.IntegerProperty(required=False, default=0)
operationschair_count = db.IntegerProperty(required=False, default=0)
gapsaliason_count = db.IntegerProperty(required=False, default=0)
communicationschair_count = db.IntegerProperty(required=False, default=0)
webadmin_count = db.IntegerProperty(required=False, default=0)
marketingchair_count = db.IntegerProperty(required=False, default=0)
@classmethod
def all_data(cls):
all_data = db.GqlQuery('SELECT *FROM User')
return list(all_data)
@classmethod
def set_email(cls, id, email):
user = User.get_by_key_name(id)
penn_id = email.split('@')[0]
user.email = email
user.penn_id = penn_id
user.put()
@classmethod
def is_email_verified(cls, email):
data = User.all_data()
if data is not None:
all_emails = {user.email: user.email_verified for user in data}
logging.info('all email information ' + str(all_emails))
return all_emails.get(email, False)
@classmethod
def is_pennid_verified(cls, email):
penn_id = email.split('@')[0]
all_data = User.all_data()
if all_data is not None:
all_penn_ids = {user.penn_id: user.email_verified for user in
all_data}
logging.info('all penn id information' + str(all_penn_ids))
return all_penn_ids.get(penn_id, False)
class Answer(db.Model):
answer = db.TextProperty(required=True)
answered_by = db.StringProperty(required=True)
answerer_name = db.StringProperty(required=True)
upvoted_by = db.ListProperty(str)
def get_votes(self):
return len(self.upvoted_by)
def get_upvote_link(self):
return '/q/question/upvote/%s' % self.key().id()
def render_str(template, **params):
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(
template_dir), autoescape=True)
t = jinja_environment.get_template(template)
return t.render(params)
class Question(db.Model):
question = db.TextProperty(required=True)
created = db.DateTimeProperty(auto_now_add=True)
last_modified = db.DateTimeProperty(auto_now=True)
answers = db.ListProperty(item_type=db.Key, required=True)
asked_by = db.StringProperty(required=True)
asker_name = db.StringProperty(required=True)
def render(self):
self._render_text = self.question.replace('\n', '<br>')
return render_str('question.html', q=self)
def as_dict(self):
time_fmt = '%c'
d = {'question': self.question, 'created': self.created.strftime(
time_fmt), 'last_modified': self.last_modified.strftime(time_fmt)}
return d
def link(self):
qid = self.key().id()
href_link = '/q/question/%s' % str(qid)
return href_link
<|reserved_special_token_1|>
__author__ = 'Chitrang'
from google.appengine.api import memcache
from google.appengine.ext import db
import logging
import os
import jinja2
class User(db.Model):
id = db.StringProperty(required=True)
created = db.DateTimeProperty(auto_now_add=True)
updated = db.DateTimeProperty(auto_now=True)
name = db.StringProperty(required=True)
profile_url = db.StringProperty(required=True)
access_token = db.StringProperty(required=True)
email = db.StringProperty(required=False)
penn_id = db.StringProperty(required=False)
email_verified = db.BooleanProperty(required=True)
verification_code = db.StringProperty(required=True)
#posts
chair = db.StringProperty(required=False)
vicechair = db.StringProperty(required=False)
treasurer = db.StringProperty(required=False)
socialchair = db.StringProperty(required=False)
operationschair = db.StringProperty(required=False)
gapsaliason = db.StringProperty(required=False)
communicationschair = db.StringProperty(required=False)
webadmin = db.StringProperty(required=False)
marketingchair = db.StringProperty(required=False)
#counts
chair_count = db.IntegerProperty(required=False, default=0)
vicechair_count = db.IntegerProperty(required=False, default=0)
treasurer_count = db.IntegerProperty(required=False, default=0)
socialchair_count = db.IntegerProperty(required=False, default=0)
operationschair_count = db.IntegerProperty(required=False, default=0)
gapsaliason_count = db.IntegerProperty(required=False, default=0)
communicationschair_count = db.IntegerProperty(required=False, default=0)
webadmin_count = db.IntegerProperty(required=False, default=0)
marketingchair_count = db.IntegerProperty(required=False, default=0)
@classmethod
def all_data(cls):
all_data = db.GqlQuery("SELECT *"
"FROM User")
return list(all_data)
#logging.info("updating cache")
#memcache.set('users', list(all_data))
@classmethod
def set_email(cls, id, email):
user = User.get_by_key_name(id)
penn_id = email.split("@")[0]
user.email = email
user.penn_id = penn_id
user.put()
#User.update_cache()
@classmethod
def is_email_verified(cls, email):
data = User.all_data()
if data is not None:
all_emails = {user.email : user.email_verified for user in data}
logging.info("all email information "+ str(all_emails))
return all_emails.get(email, False)
@classmethod
def is_pennid_verified(cls, email):
penn_id = email.split("@")[0]
all_data = User.all_data()
if all_data is not None:
all_penn_ids = {user.penn_id: user.email_verified for user in all_data}
logging.info("all penn id information" + str(all_penn_ids))
return all_penn_ids.get(penn_id, False)
class Answer(db.Model):
answer = db.TextProperty(required=True)
answered_by = db.StringProperty(required=True)
answerer_name = db.StringProperty(required=True)
upvoted_by = db.ListProperty(str)
def get_votes(self):
return len(self.upvoted_by)
def get_upvote_link(self):
return "/q/question/upvote/%s"%self.key().id()
def render_str(template, **params):
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_environment = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),
autoescape = True)
t = jinja_environment.get_template(template)
return t.render(params)
class Question(db.Model):
question = db.TextProperty(required = True)
created = db.DateTimeProperty(auto_now_add = True)
last_modified = db.DateTimeProperty(auto_now = True)
answers = db.ListProperty(item_type=db.Key,required=True)
asked_by = db.StringProperty(required=True)
asker_name = db.StringProperty(required=True)
def render(self):
self._render_text = self.question.replace('\n', '<br>')
return render_str("question.html", q = self)
def as_dict(self):
time_fmt = '%c'
d = {'question': self.question,
'created': self.created.strftime(time_fmt),
'last_modified': self.last_modified.strftime(time_fmt)}
return d
def link(self):
qid = self.key().id()
href_link = "/q/question/%s"%str(qid)
return href_link
|
flexible
|
{
"blob_id": "0b2bc19aea9393562f79df026bc17513e25c6604",
"index": 8535,
"step-1": "<mask token>\n\n\nclass User(db.Model):\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 <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 @classmethod\n def all_data(cls):\n all_data = db.GqlQuery('SELECT *FROM User')\n return list(all_data)\n\n @classmethod\n def set_email(cls, id, email):\n user = User.get_by_key_name(id)\n penn_id = email.split('@')[0]\n user.email = email\n user.penn_id = penn_id\n user.put()\n\n @classmethod\n def is_email_verified(cls, email):\n data = User.all_data()\n if data is not None:\n all_emails = {user.email: user.email_verified for user in data}\n logging.info('all email information ' + str(all_emails))\n return all_emails.get(email, False)\n\n @classmethod\n def is_pennid_verified(cls, email):\n penn_id = email.split('@')[0]\n all_data = User.all_data()\n if all_data is not None:\n all_penn_ids = {user.penn_id: user.email_verified for user in\n all_data}\n logging.info('all penn id information' + str(all_penn_ids))\n return all_penn_ids.get(penn_id, False)\n\n\nclass Answer(db.Model):\n answer = db.TextProperty(required=True)\n answered_by = db.StringProperty(required=True)\n answerer_name = db.StringProperty(required=True)\n upvoted_by = db.ListProperty(str)\n\n def get_votes(self):\n return len(self.upvoted_by)\n\n def get_upvote_link(self):\n return '/q/question/upvote/%s' % self.key().id()\n\n\n<mask token>\n\n\nclass Question(db.Model):\n question = db.TextProperty(required=True)\n created = db.DateTimeProperty(auto_now_add=True)\n last_modified = db.DateTimeProperty(auto_now=True)\n answers = db.ListProperty(item_type=db.Key, required=True)\n asked_by = db.StringProperty(required=True)\n asker_name = db.StringProperty(required=True)\n\n def render(self):\n self._render_text = self.question.replace('\\n', '<br>')\n return render_str('question.html', q=self)\n\n def as_dict(self):\n time_fmt = '%c'\n d = {'question': self.question, 'created': self.created.strftime(\n time_fmt), 'last_modified': self.last_modified.strftime(time_fmt)}\n return d\n\n def link(self):\n qid = self.key().id()\n href_link = '/q/question/%s' % str(qid)\n return href_link\n",
"step-2": "<mask token>\n\n\nclass User(db.Model):\n id = db.StringProperty(required=True)\n created = db.DateTimeProperty(auto_now_add=True)\n updated = db.DateTimeProperty(auto_now=True)\n name = db.StringProperty(required=True)\n profile_url = db.StringProperty(required=True)\n access_token = db.StringProperty(required=True)\n email = db.StringProperty(required=False)\n penn_id = db.StringProperty(required=False)\n email_verified = db.BooleanProperty(required=True)\n verification_code = db.StringProperty(required=True)\n chair = db.StringProperty(required=False)\n vicechair = db.StringProperty(required=False)\n treasurer = db.StringProperty(required=False)\n socialchair = db.StringProperty(required=False)\n operationschair = db.StringProperty(required=False)\n gapsaliason = db.StringProperty(required=False)\n communicationschair = db.StringProperty(required=False)\n webadmin = db.StringProperty(required=False)\n marketingchair = db.StringProperty(required=False)\n chair_count = db.IntegerProperty(required=False, default=0)\n vicechair_count = db.IntegerProperty(required=False, default=0)\n treasurer_count = db.IntegerProperty(required=False, default=0)\n socialchair_count = db.IntegerProperty(required=False, default=0)\n operationschair_count = db.IntegerProperty(required=False, default=0)\n gapsaliason_count = db.IntegerProperty(required=False, default=0)\n communicationschair_count = db.IntegerProperty(required=False, default=0)\n webadmin_count = db.IntegerProperty(required=False, default=0)\n marketingchair_count = db.IntegerProperty(required=False, default=0)\n\n @classmethod\n def all_data(cls):\n all_data = db.GqlQuery('SELECT *FROM User')\n return list(all_data)\n\n @classmethod\n def set_email(cls, id, email):\n user = User.get_by_key_name(id)\n penn_id = email.split('@')[0]\n user.email = email\n user.penn_id = penn_id\n user.put()\n\n @classmethod\n def is_email_verified(cls, email):\n data = User.all_data()\n if data is not None:\n all_emails = {user.email: user.email_verified for user in data}\n logging.info('all email information ' + str(all_emails))\n return all_emails.get(email, False)\n\n @classmethod\n def is_pennid_verified(cls, email):\n penn_id = email.split('@')[0]\n all_data = User.all_data()\n if all_data is not None:\n all_penn_ids = {user.penn_id: user.email_verified for user in\n all_data}\n logging.info('all penn id information' + str(all_penn_ids))\n return all_penn_ids.get(penn_id, False)\n\n\nclass Answer(db.Model):\n answer = db.TextProperty(required=True)\n answered_by = db.StringProperty(required=True)\n answerer_name = db.StringProperty(required=True)\n upvoted_by = db.ListProperty(str)\n\n def get_votes(self):\n return len(self.upvoted_by)\n\n def get_upvote_link(self):\n return '/q/question/upvote/%s' % self.key().id()\n\n\n<mask token>\n\n\nclass Question(db.Model):\n question = db.TextProperty(required=True)\n created = db.DateTimeProperty(auto_now_add=True)\n last_modified = db.DateTimeProperty(auto_now=True)\n answers = db.ListProperty(item_type=db.Key, required=True)\n asked_by = db.StringProperty(required=True)\n asker_name = db.StringProperty(required=True)\n\n def render(self):\n self._render_text = self.question.replace('\\n', '<br>')\n return render_str('question.html', q=self)\n\n def as_dict(self):\n time_fmt = '%c'\n d = {'question': self.question, 'created': self.created.strftime(\n time_fmt), 'last_modified': self.last_modified.strftime(time_fmt)}\n return d\n\n def link(self):\n qid = self.key().id()\n href_link = '/q/question/%s' % str(qid)\n return href_link\n",
"step-3": "<mask token>\n\n\nclass User(db.Model):\n id = db.StringProperty(required=True)\n created = db.DateTimeProperty(auto_now_add=True)\n updated = db.DateTimeProperty(auto_now=True)\n name = db.StringProperty(required=True)\n profile_url = db.StringProperty(required=True)\n access_token = db.StringProperty(required=True)\n email = db.StringProperty(required=False)\n penn_id = db.StringProperty(required=False)\n email_verified = db.BooleanProperty(required=True)\n verification_code = db.StringProperty(required=True)\n chair = db.StringProperty(required=False)\n vicechair = db.StringProperty(required=False)\n treasurer = db.StringProperty(required=False)\n socialchair = db.StringProperty(required=False)\n operationschair = db.StringProperty(required=False)\n gapsaliason = db.StringProperty(required=False)\n communicationschair = db.StringProperty(required=False)\n webadmin = db.StringProperty(required=False)\n marketingchair = db.StringProperty(required=False)\n chair_count = db.IntegerProperty(required=False, default=0)\n vicechair_count = db.IntegerProperty(required=False, default=0)\n treasurer_count = db.IntegerProperty(required=False, default=0)\n socialchair_count = db.IntegerProperty(required=False, default=0)\n operationschair_count = db.IntegerProperty(required=False, default=0)\n gapsaliason_count = db.IntegerProperty(required=False, default=0)\n communicationschair_count = db.IntegerProperty(required=False, default=0)\n webadmin_count = db.IntegerProperty(required=False, default=0)\n marketingchair_count = db.IntegerProperty(required=False, default=0)\n\n @classmethod\n def all_data(cls):\n all_data = db.GqlQuery('SELECT *FROM User')\n return list(all_data)\n\n @classmethod\n def set_email(cls, id, email):\n user = User.get_by_key_name(id)\n penn_id = email.split('@')[0]\n user.email = email\n user.penn_id = penn_id\n user.put()\n\n @classmethod\n def is_email_verified(cls, email):\n data = User.all_data()\n if data is not None:\n all_emails = {user.email: user.email_verified for user in data}\n logging.info('all email information ' + str(all_emails))\n return all_emails.get(email, False)\n\n @classmethod\n def is_pennid_verified(cls, email):\n penn_id = email.split('@')[0]\n all_data = User.all_data()\n if all_data is not None:\n all_penn_ids = {user.penn_id: user.email_verified for user in\n all_data}\n logging.info('all penn id information' + str(all_penn_ids))\n return all_penn_ids.get(penn_id, False)\n\n\nclass Answer(db.Model):\n answer = db.TextProperty(required=True)\n answered_by = db.StringProperty(required=True)\n answerer_name = db.StringProperty(required=True)\n upvoted_by = db.ListProperty(str)\n\n def get_votes(self):\n return len(self.upvoted_by)\n\n def get_upvote_link(self):\n return '/q/question/upvote/%s' % self.key().id()\n\n\ndef render_str(template, **params):\n template_dir = os.path.join(os.path.dirname(__file__), 'templates')\n jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(\n template_dir), autoescape=True)\n t = jinja_environment.get_template(template)\n return t.render(params)\n\n\nclass Question(db.Model):\n question = db.TextProperty(required=True)\n created = db.DateTimeProperty(auto_now_add=True)\n last_modified = db.DateTimeProperty(auto_now=True)\n answers = db.ListProperty(item_type=db.Key, required=True)\n asked_by = db.StringProperty(required=True)\n asker_name = db.StringProperty(required=True)\n\n def render(self):\n self._render_text = self.question.replace('\\n', '<br>')\n return render_str('question.html', q=self)\n\n def as_dict(self):\n time_fmt = '%c'\n d = {'question': self.question, 'created': self.created.strftime(\n time_fmt), 'last_modified': self.last_modified.strftime(time_fmt)}\n return d\n\n def link(self):\n qid = self.key().id()\n href_link = '/q/question/%s' % str(qid)\n return href_link\n",
"step-4": "__author__ = 'Chitrang'\n<mask token>\n\n\nclass User(db.Model):\n id = db.StringProperty(required=True)\n created = db.DateTimeProperty(auto_now_add=True)\n updated = db.DateTimeProperty(auto_now=True)\n name = db.StringProperty(required=True)\n profile_url = db.StringProperty(required=True)\n access_token = db.StringProperty(required=True)\n email = db.StringProperty(required=False)\n penn_id = db.StringProperty(required=False)\n email_verified = db.BooleanProperty(required=True)\n verification_code = db.StringProperty(required=True)\n chair = db.StringProperty(required=False)\n vicechair = db.StringProperty(required=False)\n treasurer = db.StringProperty(required=False)\n socialchair = db.StringProperty(required=False)\n operationschair = db.StringProperty(required=False)\n gapsaliason = db.StringProperty(required=False)\n communicationschair = db.StringProperty(required=False)\n webadmin = db.StringProperty(required=False)\n marketingchair = db.StringProperty(required=False)\n chair_count = db.IntegerProperty(required=False, default=0)\n vicechair_count = db.IntegerProperty(required=False, default=0)\n treasurer_count = db.IntegerProperty(required=False, default=0)\n socialchair_count = db.IntegerProperty(required=False, default=0)\n operationschair_count = db.IntegerProperty(required=False, default=0)\n gapsaliason_count = db.IntegerProperty(required=False, default=0)\n communicationschair_count = db.IntegerProperty(required=False, default=0)\n webadmin_count = db.IntegerProperty(required=False, default=0)\n marketingchair_count = db.IntegerProperty(required=False, default=0)\n\n @classmethod\n def all_data(cls):\n all_data = db.GqlQuery('SELECT *FROM User')\n return list(all_data)\n\n @classmethod\n def set_email(cls, id, email):\n user = User.get_by_key_name(id)\n penn_id = email.split('@')[0]\n user.email = email\n user.penn_id = penn_id\n user.put()\n\n @classmethod\n def is_email_verified(cls, email):\n data = User.all_data()\n if data is not None:\n all_emails = {user.email: user.email_verified for user in data}\n logging.info('all email information ' + str(all_emails))\n return all_emails.get(email, False)\n\n @classmethod\n def is_pennid_verified(cls, email):\n penn_id = email.split('@')[0]\n all_data = User.all_data()\n if all_data is not None:\n all_penn_ids = {user.penn_id: user.email_verified for user in\n all_data}\n logging.info('all penn id information' + str(all_penn_ids))\n return all_penn_ids.get(penn_id, False)\n\n\nclass Answer(db.Model):\n answer = db.TextProperty(required=True)\n answered_by = db.StringProperty(required=True)\n answerer_name = db.StringProperty(required=True)\n upvoted_by = db.ListProperty(str)\n\n def get_votes(self):\n return len(self.upvoted_by)\n\n def get_upvote_link(self):\n return '/q/question/upvote/%s' % self.key().id()\n\n\ndef render_str(template, **params):\n template_dir = os.path.join(os.path.dirname(__file__), 'templates')\n jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(\n template_dir), autoescape=True)\n t = jinja_environment.get_template(template)\n return t.render(params)\n\n\nclass Question(db.Model):\n question = db.TextProperty(required=True)\n created = db.DateTimeProperty(auto_now_add=True)\n last_modified = db.DateTimeProperty(auto_now=True)\n answers = db.ListProperty(item_type=db.Key, required=True)\n asked_by = db.StringProperty(required=True)\n asker_name = db.StringProperty(required=True)\n\n def render(self):\n self._render_text = self.question.replace('\\n', '<br>')\n return render_str('question.html', q=self)\n\n def as_dict(self):\n time_fmt = '%c'\n d = {'question': self.question, 'created': self.created.strftime(\n time_fmt), 'last_modified': self.last_modified.strftime(time_fmt)}\n return d\n\n def link(self):\n qid = self.key().id()\n href_link = '/q/question/%s' % str(qid)\n return href_link\n",
"step-5": "__author__ = 'Chitrang'\n\nfrom google.appengine.api import memcache\nfrom google.appengine.ext import db\nimport logging\nimport os\nimport jinja2\n\nclass User(db.Model):\n\n id = db.StringProperty(required=True)\n created = db.DateTimeProperty(auto_now_add=True)\n updated = db.DateTimeProperty(auto_now=True)\n name = db.StringProperty(required=True)\n profile_url = db.StringProperty(required=True)\n access_token = db.StringProperty(required=True)\n email = db.StringProperty(required=False)\n penn_id = db.StringProperty(required=False)\n email_verified = db.BooleanProperty(required=True)\n verification_code = db.StringProperty(required=True)\n\n #posts\n chair = db.StringProperty(required=False)\n vicechair = db.StringProperty(required=False)\n treasurer = db.StringProperty(required=False)\n socialchair = db.StringProperty(required=False)\n operationschair = db.StringProperty(required=False)\n gapsaliason = db.StringProperty(required=False)\n communicationschair = db.StringProperty(required=False)\n webadmin = db.StringProperty(required=False)\n marketingchair = db.StringProperty(required=False)\n\n #counts\n chair_count = db.IntegerProperty(required=False, default=0)\n vicechair_count = db.IntegerProperty(required=False, default=0)\n treasurer_count = db.IntegerProperty(required=False, default=0)\n socialchair_count = db.IntegerProperty(required=False, default=0)\n operationschair_count = db.IntegerProperty(required=False, default=0)\n gapsaliason_count = db.IntegerProperty(required=False, default=0)\n communicationschair_count = db.IntegerProperty(required=False, default=0)\n webadmin_count = db.IntegerProperty(required=False, default=0)\n marketingchair_count = db.IntegerProperty(required=False, default=0)\n\n @classmethod\n def all_data(cls):\n all_data = db.GqlQuery(\"SELECT *\"\n \"FROM User\")\n return list(all_data)\n #logging.info(\"updating cache\")\n #memcache.set('users', list(all_data))\n\n @classmethod\n def set_email(cls, id, email):\n user = User.get_by_key_name(id)\n penn_id = email.split(\"@\")[0]\n user.email = email\n user.penn_id = penn_id\n user.put()\n #User.update_cache()\n\n @classmethod\n def is_email_verified(cls, email):\n data = User.all_data()\n if data is not None:\n all_emails = {user.email : user.email_verified for user in data}\n logging.info(\"all email information \"+ str(all_emails))\n return all_emails.get(email, False)\n\n @classmethod\n def is_pennid_verified(cls, email):\n penn_id = email.split(\"@\")[0]\n all_data = User.all_data()\n if all_data is not None:\n all_penn_ids = {user.penn_id: user.email_verified for user in all_data}\n logging.info(\"all penn id information\" + str(all_penn_ids))\n return all_penn_ids.get(penn_id, False)\n\n\n\nclass Answer(db.Model):\n answer = db.TextProperty(required=True)\n answered_by = db.StringProperty(required=True)\n answerer_name = db.StringProperty(required=True)\n upvoted_by = db.ListProperty(str)\n\n def get_votes(self):\n return len(self.upvoted_by)\n\n def get_upvote_link(self):\n return \"/q/question/upvote/%s\"%self.key().id()\n\ndef render_str(template, **params):\n template_dir = os.path.join(os.path.dirname(__file__), 'templates')\n jinja_environment = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),\n autoescape = True)\n t = jinja_environment.get_template(template)\n return t.render(params)\n\n\nclass Question(db.Model):\n question = db.TextProperty(required = True)\n created = db.DateTimeProperty(auto_now_add = True)\n last_modified = db.DateTimeProperty(auto_now = True)\n answers = db.ListProperty(item_type=db.Key,required=True)\n asked_by = db.StringProperty(required=True)\n asker_name = db.StringProperty(required=True)\n\n\n def render(self):\n self._render_text = self.question.replace('\\n', '<br>')\n return render_str(\"question.html\", q = self)\n\n def as_dict(self):\n time_fmt = '%c'\n d = {'question': self.question,\n 'created': self.created.strftime(time_fmt),\n 'last_modified': self.last_modified.strftime(time_fmt)}\n return d\n\n def link(self):\n qid = self.key().id()\n href_link = \"/q/question/%s\"%str(qid)\n return href_link\n\n",
"step-ids": [
14,
15,
16,
17,
19
]
}
|
[
14,
15,
16,
17,
19
] |
from otree.api import Currency as c, currency_range
from . import models
from ._builtin import Page, WaitPage
from .models import Constants
class Introduction(Page):
timeout_seconds = 60
class Welcome(Page):
timeout_seconds = 60
class Priming(Page):
form_model = models.Player
form_fields = ['text']
class Eye1(Page):
form_model = models.Player
form_fields = ['option_1']
timeout_seconds = 10
class Eye2(Page):
form_model = models.Player
form_fields = ['option_2']
timeout_seconds = 10
class Eye3(Page):
form_model = models.Player
form_fields = ['option_3']
timeout_seconds = 10
class Eye4(Page):
form_model = models.Player
form_fields = ['option_4']
timeout_seconds = 10
class Eye5(Page):
form_model = models.Player
form_fields = ['option_5']
timeout_seconds = 10
class Eye6(Page):
form_model = models.Player
form_fields = ['option_6']
timeout_seconds = 10
class Eye7(Page):
form_model = models.Player
form_fields = ['option_7']
timeout_seconds = 10
class Eye8(Page):
form_model = models.Player
form_fields = ['option_8']
timeout_seconds = 10
class Eye9(Page):
form_model = models.Player
form_fields = ['option_9']
timeout_seconds = 10
class Eye10(Page):
form_model = models.Player
form_fields = ['option_10']
timeout_seconds = 10
class Eye11(Page):
form_model = models.Player
form_fields = ['option_11']
timeout_seconds = 10
class Eye12(Page):
form_model = models.Player
form_fields = ['option_12']
timeout_seconds = 10
class Eye13(Page):
form_model = models.Player
form_fields = ['option_13']
timeout_seconds = 10
class Eye14(Page):
form_model = models.Player
form_fields = ['option_14']
timeout_seconds = 10
class Eye15(Page):
form_model = models.Player
form_fields = ['option_15']
timeout_seconds = 10
class Eye16(Page):
form_model = models.Player
form_fields = ['option_16']
timeout_seconds = 10
class Eye17(Page):
form_model = models.Player
form_fields = ['option_17']
timeout_seconds = 10
class Eye18(Page):
form_model = models.Player
form_fields = ['option_18']
timeout_seconds = 10
class Eye19(Page):
form_model = models.Player
form_fields = ['option_19']
timeout_seconds = 10
class Eye20(Page):
form_model = models.Player
form_fields = ['option_20']
timeout_seconds = 10
class Eye21(Page):
form_model = models.Player
form_fields = ['option_21']
timeout_seconds = 10
class Eye22(Page):
form_model = models.Player
form_fields = ['option_22']
timeout_seconds = 10
class Eye23(Page):
form_model = models.Player
form_fields = ['option_23']
timeout_seconds = 10
class Eye24(Page):
form_model = models.Player
form_fields = ['option_24']
timeout_seconds = 10
class Eye25(Page):
form_model = models.Player
form_fields = ['option_25']
timeout_seconds = 10
class Eye26(Page):
form_model = models.Player
form_fields = ['option_26']
timeout_seconds = 10
class Eye27(Page):
form_model = models.Player
form_fields = ['option_27']
timeout_seconds = 10
class Eye28(Page):
form_model = models.Player
form_fields = ['option_28']
timeout_seconds = 10
class Eye29(Page):
form_model = models.Player
form_fields = ['option_29']
timeout_seconds = 10
class Eye30(Page):
form_model = models.Player
form_fields = ['option_30']
timeout_seconds = 10
class Eye31(Page):
form_model = models.Player
form_fields = ['option_31']
timeout_seconds = 10
class Eye32(Page):
form_model = models.Player
form_fields = ['option_32']
timeout_seconds = 10
class Eye33(Page):
form_model = models.Player
form_fields = ['option_33']
timeout_seconds = 10
class Eye34(Page):
form_model = models.Player
form_fields = ['option_34']
timeout_seconds = 10
class Eye35(Page):
form_model = models.Player
form_fields = ['option_35']
timeout_seconds = 10
class Eye36(Page):
form_model = models.Player
form_fields = ['option_36']
timeout_seconds = 10
class ResultsWaitPage(WaitPage):
def after_all_players_arrive(self):
self.group.set_payoffs()
def is_displayed(self):
return self.player.treatment != 4
class MyWaitPage(WaitPage):
group_by_arrival_time = True
players_per_group = 2
def after_all_players_arrive(self):
self.group.get_treatment()
class Player1(Page):
form_model = models.Player
form_fields = ['Message_12']
def is_displayed(self):
return self.player.id_in_group == 1 and self.player.treatment != 4
timeout_seconds = 120
timeout_submission = {'Message_12': 'Message 1'}
class Player2(Page):
form_model = models.Player
form_fields = ['option_AB']
def is_displayed(self):
return self.player.id_in_group == 2 and self.player.treatment != 4
timeout_seconds = 120
timeout_submission = {'option_AB': 'Option A'}
class treatment_4(Page):
form_model = models.Player
form_fields = ['option4_1', 'option4_2']
def before_next_page(self):
self.player.payoff = 0.10
self.player.total = 0.30
def is_displayed(self):
return self.player.treatment == 4
class Result_123(Page):
def vars_for_template(self):
return {'task2': self.player.payoff - 0.20}
class Demographic(Page):
form_model = models.Player
form_fields = ['gender', 'age', 'religion', 'service'] #'getcode_1', 'getcode_2']
class WaitforP1(WaitPage):
def is_displayed(self):
return self.player.treatment != 4
class Task3(Page):
def is_displayed(self):
return self.player.id_in_group == 2 and self.player.treatment != 4
page_sequence = [
MyWaitPage,
Welcome,
Priming,
Introduction,
Eye1,
Eye2,
Eye3,
Eye4,
Eye5,
Eye6,
Eye7,
Eye8,
Eye9,
Eye10,
Eye11,
Eye12,
Eye13,
Eye14,
Eye15,
Eye16,
Eye17,
Eye18,
Eye19,
Eye20,
Eye21,
Eye22,
Eye23,
Eye24,
Eye25,
Eye26,
Eye27,
Eye28,
Eye29,
Eye30,
Eye31,
Eye32,
Eye33,
Eye34,
Eye35,
Eye36,
Player1,
Task3,
WaitforP1,
Player2,
treatment_4,
Demographic,
ResultsWaitPage,
Result_123
]
|
normal
|
{
"blob_id": "8fecfdf4b3772e5304f0b146317f94cdbd7fbd53",
"index": 5791,
"step-1": "<mask token>\n\n\nclass Eye11(Page):\n form_model = models.Player\n form_fields = ['option_11']\n timeout_seconds = 10\n\n\nclass Eye12(Page):\n form_model = models.Player\n form_fields = ['option_12']\n timeout_seconds = 10\n\n\nclass Eye13(Page):\n form_model = models.Player\n form_fields = ['option_13']\n timeout_seconds = 10\n\n\nclass Eye14(Page):\n form_model = models.Player\n form_fields = ['option_14']\n timeout_seconds = 10\n\n\nclass Eye15(Page):\n form_model = models.Player\n form_fields = ['option_15']\n timeout_seconds = 10\n\n\nclass Eye16(Page):\n form_model = models.Player\n form_fields = ['option_16']\n timeout_seconds = 10\n\n\nclass Eye17(Page):\n form_model = models.Player\n form_fields = ['option_17']\n timeout_seconds = 10\n\n\nclass Eye18(Page):\n form_model = models.Player\n form_fields = ['option_18']\n timeout_seconds = 10\n\n\nclass Eye19(Page):\n form_model = models.Player\n form_fields = ['option_19']\n timeout_seconds = 10\n\n\nclass Eye20(Page):\n form_model = models.Player\n form_fields = ['option_20']\n timeout_seconds = 10\n\n\nclass Eye21(Page):\n form_model = models.Player\n form_fields = ['option_21']\n timeout_seconds = 10\n\n\nclass Eye22(Page):\n form_model = models.Player\n form_fields = ['option_22']\n timeout_seconds = 10\n\n\nclass Eye23(Page):\n form_model = models.Player\n form_fields = ['option_23']\n timeout_seconds = 10\n\n\nclass Eye24(Page):\n form_model = models.Player\n form_fields = ['option_24']\n timeout_seconds = 10\n\n\nclass Eye25(Page):\n form_model = models.Player\n form_fields = ['option_25']\n timeout_seconds = 10\n\n\nclass Eye26(Page):\n form_model = models.Player\n form_fields = ['option_26']\n timeout_seconds = 10\n\n\nclass Eye27(Page):\n form_model = models.Player\n form_fields = ['option_27']\n timeout_seconds = 10\n\n\nclass Eye28(Page):\n form_model = models.Player\n form_fields = ['option_28']\n timeout_seconds = 10\n\n\nclass Eye29(Page):\n form_model = models.Player\n form_fields = ['option_29']\n timeout_seconds = 10\n\n\nclass Eye30(Page):\n form_model = models.Player\n form_fields = ['option_30']\n timeout_seconds = 10\n\n\nclass Eye31(Page):\n form_model = models.Player\n form_fields = ['option_31']\n timeout_seconds = 10\n\n\nclass Eye32(Page):\n form_model = models.Player\n form_fields = ['option_32']\n timeout_seconds = 10\n\n\nclass Eye33(Page):\n form_model = models.Player\n form_fields = ['option_33']\n timeout_seconds = 10\n\n\nclass Eye34(Page):\n form_model = models.Player\n form_fields = ['option_34']\n timeout_seconds = 10\n\n\nclass Eye35(Page):\n form_model = models.Player\n form_fields = ['option_35']\n timeout_seconds = 10\n\n\nclass Eye36(Page):\n form_model = models.Player\n form_fields = ['option_36']\n timeout_seconds = 10\n\n\nclass ResultsWaitPage(WaitPage):\n\n def after_all_players_arrive(self):\n self.group.set_payoffs()\n\n def is_displayed(self):\n return self.player.treatment != 4\n\n\nclass MyWaitPage(WaitPage):\n group_by_arrival_time = True\n players_per_group = 2\n\n def after_all_players_arrive(self):\n self.group.get_treatment()\n\n\nclass Player1(Page):\n form_model = models.Player\n form_fields = ['Message_12']\n\n def is_displayed(self):\n return self.player.id_in_group == 1 and self.player.treatment != 4\n timeout_seconds = 120\n timeout_submission = {'Message_12': 'Message 1'}\n\n\nclass Player2(Page):\n form_model = models.Player\n form_fields = ['option_AB']\n\n def is_displayed(self):\n return self.player.id_in_group == 2 and self.player.treatment != 4\n timeout_seconds = 120\n timeout_submission = {'option_AB': 'Option A'}\n\n\nclass treatment_4(Page):\n form_model = models.Player\n form_fields = ['option4_1', 'option4_2']\n\n def before_next_page(self):\n self.player.payoff = 0.1\n self.player.total = 0.3\n\n def is_displayed(self):\n return self.player.treatment == 4\n\n\nclass Result_123(Page):\n\n def vars_for_template(self):\n return {'task2': self.player.payoff - 0.2}\n\n\nclass Demographic(Page):\n form_model = models.Player\n form_fields = ['gender', 'age', 'religion', 'service']\n\n\nclass WaitforP1(WaitPage):\n\n def is_displayed(self):\n return self.player.treatment != 4\n\n\nclass Task3(Page):\n\n def is_displayed(self):\n return self.player.id_in_group == 2 and self.player.treatment != 4\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass Eye8(Page):\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Eye9(Page):\n form_model = models.Player\n form_fields = ['option_9']\n timeout_seconds = 10\n\n\nclass Eye10(Page):\n form_model = models.Player\n form_fields = ['option_10']\n timeout_seconds = 10\n\n\nclass Eye11(Page):\n form_model = models.Player\n form_fields = ['option_11']\n timeout_seconds = 10\n\n\nclass Eye12(Page):\n form_model = models.Player\n form_fields = ['option_12']\n timeout_seconds = 10\n\n\nclass Eye13(Page):\n form_model = models.Player\n form_fields = ['option_13']\n timeout_seconds = 10\n\n\nclass Eye14(Page):\n form_model = models.Player\n form_fields = ['option_14']\n timeout_seconds = 10\n\n\nclass Eye15(Page):\n form_model = models.Player\n form_fields = ['option_15']\n timeout_seconds = 10\n\n\nclass Eye16(Page):\n form_model = models.Player\n form_fields = ['option_16']\n timeout_seconds = 10\n\n\nclass Eye17(Page):\n form_model = models.Player\n form_fields = ['option_17']\n timeout_seconds = 10\n\n\nclass Eye18(Page):\n form_model = models.Player\n form_fields = ['option_18']\n timeout_seconds = 10\n\n\nclass Eye19(Page):\n form_model = models.Player\n form_fields = ['option_19']\n timeout_seconds = 10\n\n\nclass Eye20(Page):\n form_model = models.Player\n form_fields = ['option_20']\n timeout_seconds = 10\n\n\nclass Eye21(Page):\n form_model = models.Player\n form_fields = ['option_21']\n timeout_seconds = 10\n\n\nclass Eye22(Page):\n form_model = models.Player\n form_fields = ['option_22']\n timeout_seconds = 10\n\n\nclass Eye23(Page):\n form_model = models.Player\n form_fields = ['option_23']\n timeout_seconds = 10\n\n\nclass Eye24(Page):\n form_model = models.Player\n form_fields = ['option_24']\n timeout_seconds = 10\n\n\nclass Eye25(Page):\n form_model = models.Player\n form_fields = ['option_25']\n timeout_seconds = 10\n\n\nclass Eye26(Page):\n form_model = models.Player\n form_fields = ['option_26']\n timeout_seconds = 10\n\n\nclass Eye27(Page):\n form_model = models.Player\n form_fields = ['option_27']\n timeout_seconds = 10\n\n\nclass Eye28(Page):\n form_model = models.Player\n form_fields = ['option_28']\n timeout_seconds = 10\n\n\nclass Eye29(Page):\n form_model = models.Player\n form_fields = ['option_29']\n timeout_seconds = 10\n\n\nclass Eye30(Page):\n form_model = models.Player\n form_fields = ['option_30']\n timeout_seconds = 10\n\n\nclass Eye31(Page):\n form_model = models.Player\n form_fields = ['option_31']\n timeout_seconds = 10\n\n\nclass Eye32(Page):\n form_model = models.Player\n form_fields = ['option_32']\n timeout_seconds = 10\n\n\nclass Eye33(Page):\n form_model = models.Player\n form_fields = ['option_33']\n timeout_seconds = 10\n\n\nclass Eye34(Page):\n form_model = models.Player\n form_fields = ['option_34']\n timeout_seconds = 10\n\n\nclass Eye35(Page):\n form_model = models.Player\n form_fields = ['option_35']\n timeout_seconds = 10\n\n\nclass Eye36(Page):\n form_model = models.Player\n form_fields = ['option_36']\n timeout_seconds = 10\n\n\nclass ResultsWaitPage(WaitPage):\n\n def after_all_players_arrive(self):\n self.group.set_payoffs()\n\n def is_displayed(self):\n return self.player.treatment != 4\n\n\nclass MyWaitPage(WaitPage):\n group_by_arrival_time = True\n players_per_group = 2\n\n def after_all_players_arrive(self):\n self.group.get_treatment()\n\n\nclass Player1(Page):\n form_model = models.Player\n form_fields = ['Message_12']\n\n def is_displayed(self):\n return self.player.id_in_group == 1 and self.player.treatment != 4\n timeout_seconds = 120\n timeout_submission = {'Message_12': 'Message 1'}\n\n\nclass Player2(Page):\n form_model = models.Player\n form_fields = ['option_AB']\n\n def is_displayed(self):\n return self.player.id_in_group == 2 and self.player.treatment != 4\n timeout_seconds = 120\n timeout_submission = {'option_AB': 'Option A'}\n\n\nclass treatment_4(Page):\n form_model = models.Player\n form_fields = ['option4_1', 'option4_2']\n\n def before_next_page(self):\n self.player.payoff = 0.1\n self.player.total = 0.3\n\n def is_displayed(self):\n return self.player.treatment == 4\n\n\nclass Result_123(Page):\n\n def vars_for_template(self):\n return {'task2': self.player.payoff - 0.2}\n\n\nclass Demographic(Page):\n form_model = models.Player\n form_fields = ['gender', 'age', 'religion', 'service']\n\n\nclass WaitforP1(WaitPage):\n\n def is_displayed(self):\n return self.player.treatment != 4\n\n\nclass Task3(Page):\n\n def is_displayed(self):\n return self.player.id_in_group == 2 and self.player.treatment != 4\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass Eye6(Page):\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Eye7(Page):\n form_model = models.Player\n form_fields = ['option_7']\n timeout_seconds = 10\n\n\nclass Eye8(Page):\n form_model = models.Player\n form_fields = ['option_8']\n timeout_seconds = 10\n\n\nclass Eye9(Page):\n form_model = models.Player\n form_fields = ['option_9']\n timeout_seconds = 10\n\n\nclass Eye10(Page):\n form_model = models.Player\n form_fields = ['option_10']\n timeout_seconds = 10\n\n\nclass Eye11(Page):\n form_model = models.Player\n form_fields = ['option_11']\n timeout_seconds = 10\n\n\nclass Eye12(Page):\n form_model = models.Player\n form_fields = ['option_12']\n timeout_seconds = 10\n\n\nclass Eye13(Page):\n form_model = models.Player\n form_fields = ['option_13']\n timeout_seconds = 10\n\n\nclass Eye14(Page):\n form_model = models.Player\n form_fields = ['option_14']\n timeout_seconds = 10\n\n\nclass Eye15(Page):\n form_model = models.Player\n form_fields = ['option_15']\n timeout_seconds = 10\n\n\nclass Eye16(Page):\n form_model = models.Player\n form_fields = ['option_16']\n timeout_seconds = 10\n\n\nclass Eye17(Page):\n form_model = models.Player\n form_fields = ['option_17']\n timeout_seconds = 10\n\n\nclass Eye18(Page):\n form_model = models.Player\n form_fields = ['option_18']\n timeout_seconds = 10\n\n\nclass Eye19(Page):\n form_model = models.Player\n form_fields = ['option_19']\n timeout_seconds = 10\n\n\nclass Eye20(Page):\n form_model = models.Player\n form_fields = ['option_20']\n timeout_seconds = 10\n\n\nclass Eye21(Page):\n form_model = models.Player\n form_fields = ['option_21']\n timeout_seconds = 10\n\n\nclass Eye22(Page):\n form_model = models.Player\n form_fields = ['option_22']\n timeout_seconds = 10\n\n\nclass Eye23(Page):\n form_model = models.Player\n form_fields = ['option_23']\n timeout_seconds = 10\n\n\nclass Eye24(Page):\n form_model = models.Player\n form_fields = ['option_24']\n timeout_seconds = 10\n\n\nclass Eye25(Page):\n form_model = models.Player\n form_fields = ['option_25']\n timeout_seconds = 10\n\n\nclass Eye26(Page):\n form_model = models.Player\n form_fields = ['option_26']\n timeout_seconds = 10\n\n\nclass Eye27(Page):\n form_model = models.Player\n form_fields = ['option_27']\n timeout_seconds = 10\n\n\nclass Eye28(Page):\n form_model = models.Player\n form_fields = ['option_28']\n timeout_seconds = 10\n\n\nclass Eye29(Page):\n form_model = models.Player\n form_fields = ['option_29']\n timeout_seconds = 10\n\n\nclass Eye30(Page):\n form_model = models.Player\n form_fields = ['option_30']\n timeout_seconds = 10\n\n\nclass Eye31(Page):\n form_model = models.Player\n form_fields = ['option_31']\n timeout_seconds = 10\n\n\nclass Eye32(Page):\n form_model = models.Player\n form_fields = ['option_32']\n timeout_seconds = 10\n\n\nclass Eye33(Page):\n form_model = models.Player\n form_fields = ['option_33']\n timeout_seconds = 10\n\n\nclass Eye34(Page):\n form_model = models.Player\n form_fields = ['option_34']\n timeout_seconds = 10\n\n\nclass Eye35(Page):\n form_model = models.Player\n form_fields = ['option_35']\n timeout_seconds = 10\n\n\nclass Eye36(Page):\n form_model = models.Player\n form_fields = ['option_36']\n timeout_seconds = 10\n\n\nclass ResultsWaitPage(WaitPage):\n\n def after_all_players_arrive(self):\n self.group.set_payoffs()\n\n def is_displayed(self):\n return self.player.treatment != 4\n\n\nclass MyWaitPage(WaitPage):\n group_by_arrival_time = True\n players_per_group = 2\n\n def after_all_players_arrive(self):\n self.group.get_treatment()\n\n\nclass Player1(Page):\n form_model = models.Player\n form_fields = ['Message_12']\n\n def is_displayed(self):\n return self.player.id_in_group == 1 and self.player.treatment != 4\n timeout_seconds = 120\n timeout_submission = {'Message_12': 'Message 1'}\n\n\nclass Player2(Page):\n form_model = models.Player\n form_fields = ['option_AB']\n\n def is_displayed(self):\n return self.player.id_in_group == 2 and self.player.treatment != 4\n timeout_seconds = 120\n timeout_submission = {'option_AB': 'Option A'}\n\n\nclass treatment_4(Page):\n form_model = models.Player\n form_fields = ['option4_1', 'option4_2']\n\n def before_next_page(self):\n self.player.payoff = 0.1\n self.player.total = 0.3\n\n def is_displayed(self):\n return self.player.treatment == 4\n\n\nclass Result_123(Page):\n\n def vars_for_template(self):\n return {'task2': self.player.payoff - 0.2}\n\n\nclass Demographic(Page):\n form_model = models.Player\n form_fields = ['gender', 'age', 'religion', 'service']\n\n\nclass WaitforP1(WaitPage):\n\n def is_displayed(self):\n return self.player.treatment != 4\n\n\nclass Task3(Page):\n\n def is_displayed(self):\n return self.player.id_in_group == 2 and self.player.treatment != 4\n\n\n<mask token>\n",
"step-4": "<mask token>\n\n\nclass Welcome(Page):\n timeout_seconds = 60\n\n\nclass Priming(Page):\n form_model = models.Player\n form_fields = ['text']\n\n\nclass Eye1(Page):\n form_model = models.Player\n form_fields = ['option_1']\n timeout_seconds = 10\n\n\nclass Eye2(Page):\n form_model = models.Player\n form_fields = ['option_2']\n timeout_seconds = 10\n\n\nclass Eye3(Page):\n form_model = models.Player\n form_fields = ['option_3']\n timeout_seconds = 10\n\n\nclass Eye4(Page):\n form_model = models.Player\n form_fields = ['option_4']\n timeout_seconds = 10\n\n\nclass Eye5(Page):\n form_model = models.Player\n form_fields = ['option_5']\n timeout_seconds = 10\n\n\nclass Eye6(Page):\n form_model = models.Player\n form_fields = ['option_6']\n timeout_seconds = 10\n\n\nclass Eye7(Page):\n form_model = models.Player\n form_fields = ['option_7']\n timeout_seconds = 10\n\n\nclass Eye8(Page):\n form_model = models.Player\n form_fields = ['option_8']\n timeout_seconds = 10\n\n\nclass Eye9(Page):\n form_model = models.Player\n form_fields = ['option_9']\n timeout_seconds = 10\n\n\nclass Eye10(Page):\n form_model = models.Player\n form_fields = ['option_10']\n timeout_seconds = 10\n\n\nclass Eye11(Page):\n form_model = models.Player\n form_fields = ['option_11']\n timeout_seconds = 10\n\n\nclass Eye12(Page):\n form_model = models.Player\n form_fields = ['option_12']\n timeout_seconds = 10\n\n\nclass Eye13(Page):\n form_model = models.Player\n form_fields = ['option_13']\n timeout_seconds = 10\n\n\nclass Eye14(Page):\n form_model = models.Player\n form_fields = ['option_14']\n timeout_seconds = 10\n\n\nclass Eye15(Page):\n form_model = models.Player\n form_fields = ['option_15']\n timeout_seconds = 10\n\n\nclass Eye16(Page):\n form_model = models.Player\n form_fields = ['option_16']\n timeout_seconds = 10\n\n\nclass Eye17(Page):\n form_model = models.Player\n form_fields = ['option_17']\n timeout_seconds = 10\n\n\nclass Eye18(Page):\n form_model = models.Player\n form_fields = ['option_18']\n timeout_seconds = 10\n\n\nclass Eye19(Page):\n form_model = models.Player\n form_fields = ['option_19']\n timeout_seconds = 10\n\n\nclass Eye20(Page):\n form_model = models.Player\n form_fields = ['option_20']\n timeout_seconds = 10\n\n\nclass Eye21(Page):\n form_model = models.Player\n form_fields = ['option_21']\n timeout_seconds = 10\n\n\nclass Eye22(Page):\n form_model = models.Player\n form_fields = ['option_22']\n timeout_seconds = 10\n\n\nclass Eye23(Page):\n form_model = models.Player\n form_fields = ['option_23']\n timeout_seconds = 10\n\n\nclass Eye24(Page):\n form_model = models.Player\n form_fields = ['option_24']\n timeout_seconds = 10\n\n\nclass Eye25(Page):\n form_model = models.Player\n form_fields = ['option_25']\n timeout_seconds = 10\n\n\nclass Eye26(Page):\n form_model = models.Player\n form_fields = ['option_26']\n timeout_seconds = 10\n\n\nclass Eye27(Page):\n form_model = models.Player\n form_fields = ['option_27']\n timeout_seconds = 10\n\n\nclass Eye28(Page):\n form_model = models.Player\n form_fields = ['option_28']\n timeout_seconds = 10\n\n\nclass Eye29(Page):\n form_model = models.Player\n form_fields = ['option_29']\n timeout_seconds = 10\n\n\nclass Eye30(Page):\n form_model = models.Player\n form_fields = ['option_30']\n timeout_seconds = 10\n\n\nclass Eye31(Page):\n form_model = models.Player\n form_fields = ['option_31']\n timeout_seconds = 10\n\n\nclass Eye32(Page):\n form_model = models.Player\n form_fields = ['option_32']\n timeout_seconds = 10\n\n\nclass Eye33(Page):\n form_model = models.Player\n form_fields = ['option_33']\n timeout_seconds = 10\n\n\nclass Eye34(Page):\n form_model = models.Player\n form_fields = ['option_34']\n timeout_seconds = 10\n\n\nclass Eye35(Page):\n form_model = models.Player\n form_fields = ['option_35']\n timeout_seconds = 10\n\n\nclass Eye36(Page):\n form_model = models.Player\n form_fields = ['option_36']\n timeout_seconds = 10\n\n\nclass ResultsWaitPage(WaitPage):\n\n def after_all_players_arrive(self):\n self.group.set_payoffs()\n\n def is_displayed(self):\n return self.player.treatment != 4\n\n\nclass MyWaitPage(WaitPage):\n group_by_arrival_time = True\n players_per_group = 2\n\n def after_all_players_arrive(self):\n self.group.get_treatment()\n\n\nclass Player1(Page):\n form_model = models.Player\n form_fields = ['Message_12']\n\n def is_displayed(self):\n return self.player.id_in_group == 1 and self.player.treatment != 4\n timeout_seconds = 120\n timeout_submission = {'Message_12': 'Message 1'}\n\n\nclass Player2(Page):\n form_model = models.Player\n form_fields = ['option_AB']\n\n def is_displayed(self):\n return self.player.id_in_group == 2 and self.player.treatment != 4\n timeout_seconds = 120\n timeout_submission = {'option_AB': 'Option A'}\n\n\nclass treatment_4(Page):\n form_model = models.Player\n form_fields = ['option4_1', 'option4_2']\n\n def before_next_page(self):\n self.player.payoff = 0.1\n self.player.total = 0.3\n\n def is_displayed(self):\n return self.player.treatment == 4\n\n\nclass Result_123(Page):\n\n def vars_for_template(self):\n return {'task2': self.player.payoff - 0.2}\n\n\nclass Demographic(Page):\n form_model = models.Player\n form_fields = ['gender', 'age', 'religion', 'service']\n\n\nclass WaitforP1(WaitPage):\n\n def is_displayed(self):\n return self.player.treatment != 4\n\n\nclass Task3(Page):\n\n def is_displayed(self):\n return self.player.id_in_group == 2 and self.player.treatment != 4\n\n\n<mask token>\n",
"step-5": "from otree.api import Currency as c, currency_range\nfrom . import models\nfrom ._builtin import Page, WaitPage\nfrom .models import Constants\n\n\nclass Introduction(Page):\n timeout_seconds = 60\n\n\nclass Welcome(Page):\n timeout_seconds = 60\n\n\nclass Priming(Page):\n form_model = models.Player\n form_fields = ['text']\n\n\nclass Eye1(Page):\n form_model = models.Player\n form_fields = ['option_1']\n\n timeout_seconds = 10\n\n\nclass Eye2(Page):\n form_model = models.Player\n form_fields = ['option_2']\n\n timeout_seconds = 10\n\n\nclass Eye3(Page):\n form_model = models.Player\n form_fields = ['option_3']\n\n timeout_seconds = 10\n\n\nclass Eye4(Page):\n form_model = models.Player\n form_fields = ['option_4']\n\n timeout_seconds = 10\n\n\nclass Eye5(Page):\n form_model = models.Player\n form_fields = ['option_5']\n\n timeout_seconds = 10\n\n\nclass Eye6(Page):\n form_model = models.Player\n form_fields = ['option_6']\n\n timeout_seconds = 10\n\n\nclass Eye7(Page):\n form_model = models.Player\n form_fields = ['option_7']\n\n timeout_seconds = 10\n\n\nclass Eye8(Page):\n form_model = models.Player\n form_fields = ['option_8']\n\n timeout_seconds = 10\n\n\nclass Eye9(Page):\n form_model = models.Player\n form_fields = ['option_9']\n\n timeout_seconds = 10\n\n\nclass Eye10(Page):\n form_model = models.Player\n form_fields = ['option_10']\n\n timeout_seconds = 10\n\n\nclass Eye11(Page):\n form_model = models.Player\n form_fields = ['option_11']\n\n timeout_seconds = 10\n\n\nclass Eye12(Page):\n form_model = models.Player\n form_fields = ['option_12']\n\n timeout_seconds = 10\n\n\nclass Eye13(Page):\n form_model = models.Player\n form_fields = ['option_13']\n\n timeout_seconds = 10\n\n\nclass Eye14(Page):\n form_model = models.Player\n form_fields = ['option_14']\n\n timeout_seconds = 10\n\n\nclass Eye15(Page):\n form_model = models.Player\n form_fields = ['option_15']\n\n timeout_seconds = 10\n\n\nclass Eye16(Page):\n form_model = models.Player\n form_fields = ['option_16']\n\n timeout_seconds = 10\n\n\nclass Eye17(Page):\n form_model = models.Player\n form_fields = ['option_17']\n\n timeout_seconds = 10\n\n\nclass Eye18(Page):\n form_model = models.Player\n form_fields = ['option_18']\n\n timeout_seconds = 10\n\n\nclass Eye19(Page):\n form_model = models.Player\n form_fields = ['option_19']\n\n timeout_seconds = 10\n\n\nclass Eye20(Page):\n form_model = models.Player\n form_fields = ['option_20']\n\n timeout_seconds = 10\n\n\nclass Eye21(Page):\n form_model = models.Player\n form_fields = ['option_21']\n\n timeout_seconds = 10\n\n\nclass Eye22(Page):\n form_model = models.Player\n form_fields = ['option_22']\n\n timeout_seconds = 10\n\n\nclass Eye23(Page):\n form_model = models.Player\n form_fields = ['option_23']\n\n timeout_seconds = 10\n\n\nclass Eye24(Page):\n form_model = models.Player\n form_fields = ['option_24']\n\n timeout_seconds = 10\n\n\nclass Eye25(Page):\n form_model = models.Player\n form_fields = ['option_25']\n\n timeout_seconds = 10\n\n\nclass Eye26(Page):\n form_model = models.Player\n form_fields = ['option_26']\n\n timeout_seconds = 10\n\n\nclass Eye27(Page):\n form_model = models.Player\n form_fields = ['option_27']\n\n timeout_seconds = 10\n\n\nclass Eye28(Page):\n form_model = models.Player\n form_fields = ['option_28']\n\n timeout_seconds = 10\n\n\nclass Eye29(Page):\n form_model = models.Player\n form_fields = ['option_29']\n\n timeout_seconds = 10\n\n\nclass Eye30(Page):\n form_model = models.Player\n form_fields = ['option_30']\n\n timeout_seconds = 10\n\n\nclass Eye31(Page):\n form_model = models.Player\n form_fields = ['option_31']\n\n timeout_seconds = 10\n\n\nclass Eye32(Page):\n form_model = models.Player\n form_fields = ['option_32']\n\n timeout_seconds = 10\n\n\nclass Eye33(Page):\n form_model = models.Player\n form_fields = ['option_33']\n\n timeout_seconds = 10\n\n\nclass Eye34(Page):\n form_model = models.Player\n form_fields = ['option_34']\n\n timeout_seconds = 10\n\n\nclass Eye35(Page):\n form_model = models.Player\n form_fields = ['option_35']\n\n timeout_seconds = 10\n\n\nclass Eye36(Page):\n form_model = models.Player\n form_fields = ['option_36']\n\n timeout_seconds = 10\n\n\nclass ResultsWaitPage(WaitPage):\n\n def after_all_players_arrive(self):\n self.group.set_payoffs()\n\n def is_displayed(self):\n return self.player.treatment != 4\n\n\nclass MyWaitPage(WaitPage):\n group_by_arrival_time = True\n players_per_group = 2\n\n def after_all_players_arrive(self):\n self.group.get_treatment()\n\n\nclass Player1(Page):\n form_model = models.Player\n form_fields = ['Message_12']\n\n def is_displayed(self):\n return self.player.id_in_group == 1 and self.player.treatment != 4\n\n timeout_seconds = 120\n timeout_submission = {'Message_12': 'Message 1'}\n\n\nclass Player2(Page):\n form_model = models.Player\n form_fields = ['option_AB']\n\n def is_displayed(self):\n return self.player.id_in_group == 2 and self.player.treatment != 4\n\n timeout_seconds = 120\n timeout_submission = {'option_AB': 'Option A'}\n\n\nclass treatment_4(Page):\n form_model = models.Player\n form_fields = ['option4_1', 'option4_2']\n\n def before_next_page(self):\n self.player.payoff = 0.10\n self.player.total = 0.30\n\n def is_displayed(self):\n return self.player.treatment == 4\n\n\nclass Result_123(Page):\n\n def vars_for_template(self):\n return {'task2': self.player.payoff - 0.20}\n\n\nclass Demographic(Page):\n form_model = models.Player\n form_fields = ['gender', 'age', 'religion', 'service'] #'getcode_1', 'getcode_2']\n\n\nclass WaitforP1(WaitPage):\n def is_displayed(self):\n return self.player.treatment != 4\n\n\nclass Task3(Page):\n def is_displayed(self):\n return self.player.id_in_group == 2 and self.player.treatment != 4\n\n\npage_sequence = [\n MyWaitPage,\n Welcome,\n Priming,\n Introduction,\n Eye1,\n Eye2,\n Eye3,\n Eye4,\n Eye5,\n Eye6,\n Eye7,\n Eye8,\n Eye9,\n Eye10,\n Eye11,\n Eye12,\n Eye13,\n Eye14,\n Eye15,\n Eye16,\n Eye17,\n Eye18,\n Eye19,\n Eye20,\n Eye21,\n Eye22,\n Eye23,\n Eye24,\n Eye25,\n Eye26,\n Eye27,\n Eye28,\n Eye29,\n Eye30,\n Eye31,\n Eye32,\n Eye33,\n Eye34,\n Eye35,\n Eye36,\n Player1,\n Task3,\n WaitforP1,\n Player2,\n treatment_4,\n Demographic,\n ResultsWaitPage,\n Result_123\n]\n",
"step-ids": [
76,
81,
85,
100,
105
]
}
|
[
76,
81,
85,
100,
105
] |
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
# This script is a wrapper for JSON primitives, such as validation.
# Using routines of this module permits us to replace the underlying
# implementation with a better one without disrupting client code.
#
# In particular, at the time of this writing, there weren't really great
# json validation packages available for python. We initially settled
# on validictory, but it has a number of shortcomings, such as:
# * format error diagnostic message isn't always helpful for diagnosis
# * doesn't support references
# * doesn't support application of defaults
# * doesn't support dependencies
#
# TODO: offer a combined json parsing/validation function that applies
# defaults from the schema
# TODO: duplicate of 'validate', 'ValidationError', 'loadJSONValueFromFile'
# in swarming.hypersearch.utils -- will want to remove that later
import json
import math
import os
import validictory
class ValidationError(validictory.ValidationError):
pass
class NaNInvalidator(validictory.SchemaValidator):
""" validictory.SchemaValidator subclass to not accept NaN values as numbers.
Usage:
validate(value, schemaDict, validator_cls=NaNInvalidator)
"""
def validate_type_number(self, val):
return not math.isnan(val) \
and super(NaNInvalidator, self).validate_type_number(val)
def validate(value, **kwds):
""" Validate a python value against json schema:
validate(value, schemaPath)
validate(value, schemaDict)
value: python object to validate against the schema
The json schema may be specified either as a path of the file containing
the json schema or as a python dictionary using one of the
following keywords as arguments:
schemaPath: Path of file containing the json schema object.
schemaDict: Python dictionary containing the json schema object
Returns: nothing
Raises:
ValidationError when value fails json validation
"""
assert len(kwds.keys()) >= 1
assert 'schemaPath' in kwds or 'schemaDict' in kwds
schemaDict = None
if 'schemaPath' in kwds:
schemaPath = kwds.pop('schemaPath')
schemaDict = loadJsonValueFromFile(schemaPath)
elif 'schemaDict' in kwds:
schemaDict = kwds.pop('schemaDict')
try:
validictory.validate(value, schemaDict, **kwds)
except validictory.ValidationError as e:
raise ValidationError(e)
def loadJsonValueFromFile(inputFilePath):
""" Loads a json value from a file and converts it to the corresponding python
object.
inputFilePath:
Path of the json file;
Returns:
python value that represents the loaded json value
"""
with open(inputFilePath) as fileObj:
value = json.load(fileObj)
return value
def test():
"""
"""
import sys
schemaDict = {
"description":"JSON schema for jsonhelpers.py test code",
"type":"object",
"additionalProperties":False,
"properties":{
"myBool":{
"description":"Some boolean property",
"required":True,
"type":"boolean"
}
}
}
d = {
'myBool': False
}
print "Validating schemaDict method in positive test..."
validate(d, schemaDict=schemaDict)
print "ok\n"
print "Validating schemaDict method in negative test..."
try:
validate({}, schemaDict=schemaDict)
except ValidationError:
print "ok\n"
else:
print "FAILED\n"
sys.exit(1)
schemaPath = os.path.join(os.path.dirname(__file__), "testSchema.json")
print "Validating schemaPath method in positive test using %s..." % \
(os.path.abspath(schemaPath),)
validate(d, schemaPath=schemaPath)
print "ok\n"
print "Validating schemaPath method in negative test using %s..." % \
(os.path.abspath(schemaPath),)
try:
validate({}, schemaPath=schemaPath)
except ValidationError:
print "ok\n"
else:
print "FAILED\n"
sys.exit(1)
return
if __name__ == "__main__":
test()
|
normal
|
{
"blob_id": "f0f4573808253ca4bff808104afa9f350d305a9c",
"index": 3501,
"step-1": "# ----------------------------------------------------------------------\n# Numenta Platform for Intelligent Computing (NuPIC)\n# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement\n# with Numenta, Inc., for a separate license for this software code, the\n# following terms and conditions apply:\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero Public License version 3 as\n# published by the Free Software Foundation.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n# See the GNU Affero Public License for more details.\n#\n# You should have received a copy of the GNU Affero Public License\n# along with this program. If not, see http://www.gnu.org/licenses.\n#\n# http://numenta.org/licenses/\n# ----------------------------------------------------------------------\n\n# This script is a wrapper for JSON primitives, such as validation.\n# Using routines of this module permits us to replace the underlying\n# implementation with a better one without disrupting client code.\n#\n# In particular, at the time of this writing, there weren't really great\n# json validation packages available for python. We initially settled\n# on validictory, but it has a number of shortcomings, such as:\n# * format error diagnostic message isn't always helpful for diagnosis\n# * doesn't support references\n# * doesn't support application of defaults\n# * doesn't support dependencies\n#\n# TODO: offer a combined json parsing/validation function that applies\n# defaults from the schema\n# TODO: duplicate of 'validate', 'ValidationError', 'loadJSONValueFromFile'\n# in swarming.hypersearch.utils -- will want to remove that later\n\nimport json\nimport math\nimport os\n\nimport validictory\n\n\nclass ValidationError(validictory.ValidationError):\n pass\n\n\nclass NaNInvalidator(validictory.SchemaValidator):\n \"\"\" validictory.SchemaValidator subclass to not accept NaN values as numbers.\n\n Usage:\n\n validate(value, schemaDict, validator_cls=NaNInvalidator)\n\n \"\"\"\n def validate_type_number(self, val):\n return not math.isnan(val) \\\n and super(NaNInvalidator, self).validate_type_number(val)\n\n\n\ndef validate(value, **kwds):\n \"\"\" Validate a python value against json schema:\n validate(value, schemaPath)\n validate(value, schemaDict)\n\n value: python object to validate against the schema\n\n The json schema may be specified either as a path of the file containing\n the json schema or as a python dictionary using one of the\n following keywords as arguments:\n schemaPath: Path of file containing the json schema object.\n schemaDict: Python dictionary containing the json schema object\n\n Returns: nothing\n\n Raises:\n ValidationError when value fails json validation\n \"\"\"\n\n assert len(kwds.keys()) >= 1\n assert 'schemaPath' in kwds or 'schemaDict' in kwds\n\n schemaDict = None\n if 'schemaPath' in kwds:\n schemaPath = kwds.pop('schemaPath')\n schemaDict = loadJsonValueFromFile(schemaPath)\n elif 'schemaDict' in kwds:\n schemaDict = kwds.pop('schemaDict')\n\n try:\n validictory.validate(value, schemaDict, **kwds)\n except validictory.ValidationError as e:\n raise ValidationError(e)\n\n\n\ndef loadJsonValueFromFile(inputFilePath):\n \"\"\" Loads a json value from a file and converts it to the corresponding python\n object.\n\n inputFilePath:\n Path of the json file;\n\n Returns:\n python value that represents the loaded json value\n\n \"\"\"\n with open(inputFilePath) as fileObj:\n value = json.load(fileObj)\n\n return value\n\n\n\ndef test():\n \"\"\"\n \"\"\"\n import sys\n\n schemaDict = {\n \"description\":\"JSON schema for jsonhelpers.py test code\",\n \"type\":\"object\",\n \"additionalProperties\":False,\n \"properties\":{\n \"myBool\":{\n \"description\":\"Some boolean property\",\n \"required\":True,\n \"type\":\"boolean\"\n }\n }\n }\n\n d = {\n 'myBool': False\n }\n\n print \"Validating schemaDict method in positive test...\"\n validate(d, schemaDict=schemaDict)\n print \"ok\\n\"\n\n print \"Validating schemaDict method in negative test...\"\n try:\n validate({}, schemaDict=schemaDict)\n except ValidationError:\n print \"ok\\n\"\n else:\n print \"FAILED\\n\"\n sys.exit(1)\n\n\n schemaPath = os.path.join(os.path.dirname(__file__), \"testSchema.json\")\n print \"Validating schemaPath method in positive test using %s...\" % \\\n (os.path.abspath(schemaPath),)\n validate(d, schemaPath=schemaPath)\n print \"ok\\n\"\n\n print \"Validating schemaPath method in negative test using %s...\" % \\\n (os.path.abspath(schemaPath),)\n try:\n validate({}, schemaPath=schemaPath)\n except ValidationError:\n print \"ok\\n\"\n else:\n print \"FAILED\\n\"\n sys.exit(1)\n\n\n\n return\n\n\n\nif __name__ == \"__main__\":\n test()\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
import os
templateFile = 'crab_template.py'
samples=[\
#"/TTJets_MSDecaysCKM_central_Tune4C_13TeV-madgraph-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM",
#"/TTJets_MSDecaysCKM_central_Tune4C_13TeV-madgraph-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v2/MINIAODSIM", #Identical? Same event count #miniAODTuple_e/
# "/TTJets_MSDecaysCKM_central_Tune4C_13TeV-madgraph-tauola/Spring14miniaod-PU_S14_POSTLS170_V6-v1/MINIAODSIM", #MiniAODTupleTT1e/
# "/WJetsToLNu_HT-200to400_Tune4C_13TeV-madgraph-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM", #/data/easilar/crab3WorkAreas/...
# "/WJetsToLNu_HT-400to600_Tune4C_13TeV-madgraph-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM", #/data/easilar/crab3WorkAreas/...
# "/WJetsToLNu_HT-600toInf_Tune4C_13TeV-madgraph-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM",
# "/WJetsToLNu_13TeV-madgraph-pythia8-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM",
# "/DYJetsToLL_M-50_HT-200to400_Tune4C_13TeV-madgraph-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM",
# "/DYJetsToLL_M-50_HT-400to600_Tune4C_13TeV-madgraph-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM",
# "/DYJetsToLL_M-50_HT-600toInf_Tune4C_13TeV-madgraph-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM",
# "/DYJetsToLL_M-50_13TeV-madgraph-pythia8/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM", #/data/easilar/crab3WorkAreas/...
# "/DYJetsToLL_M-50_13TeV-pythia6/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM",
# "/DYToEE_M-50_Tune4C_13TeV-pythia8/Spring14miniaod-castor-v2/MINIAODSIM",
# "/DYToEE_Tune4C_13TeV-pythia8/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM",
# "/DYToMuMu_M-15To50_Tune4C_13TeV-pythia8/Spring14miniaod-castor_PU20bx25_POSTLS170_V5-v1/MINIAODSIM",
# "/DYToMuMu_M-50_Tune4C_13TeV-pythia8/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM",
# "/DYToMuMu_M-50_Tune4C_13TeV-pythia8/Spring14miniaod-castor_PU20bx25_POSTLS170_V5-v1/MINIAODSIM",
# "/DYToMuMu_M-6To15_Tune4C_13TeV-pythia8/Spring14miniaod-castor_PU20bx25_POSTLS170_V5-v1/MINIAODSIM",
# "/DYToMuMu_Tune4C_13TeV-pythia8/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM",
# "/TToBLNu_s-channel-EMu_Tune4C_13TeV-madgraph-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM",
# "/TToBLNu_t-channel-EMu_Tune4C_13TeV-madgraph-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM",
# "/TToBLNu_tW-channel-DR-EMu_Tune4C_13TeV-madgraph-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v2/MINIAODSIM",
# "/TToLeptons_s-channel-CSA14_Tune4C_13TeV-aMCatNLO-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM",
# "/T_tW-channel-DR_Tune4C_13TeV-CSA14-powheg-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM",
# "/Tbar_tW-channel-DR_Tune4C_13TeV-CSA14-powheg-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM",
# "/TBarToLeptons_s-channel-CSA14_Tune4C_13TeV-aMCatNLO-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM",
# "/TBarToLeptons_t-channel_Tune4C_CSA14_13TeV-aMCatNLO-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM",
#"/WJetsToLNu_HT-100to200_Tune4C_13TeV-madgraph-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v2/MINIAODSIM",
#"/WJetsToLNu_HT-100to200_Tune4C_13TeV-madgraph-tauola/schoef-WJetsToLNu_HT-100to200_Tune4C_13TeV-madgraph-tauola_Spring14dr-PU_S14_POSTLS170_V6-v1-92bfc1aa0ef8c674e0edabb945b19298/USER",
#"/WJetsToLNu_HT-200to400_Tune4C_13TeV-madgraph-tauola/schoef-WJetsToLNu_HT-200to400_Tune4C_13TeV-madgraph-tauola_Spring14dr-PU_S14_POSTLS170_V6-v1-92bfc1aa0ef8c674e0edabb945b19298/USER",
#"/WJetsToLNu_HT-400to600_Tune4C_13TeV-madgraph-tauola/schoef-WJetsToLNu_HT-400to600_Tune4C_13TeV-madgraph-tauola_Spring14dr-PU_S14_POSTLS170_V6-v1-92bfc1aa0ef8c674e0edabb945b19298/USER",
#"/WJetsToLNu_HT-600toInf_Tune4C_13TeV-madgraph-tauola/schoef-WJetsToLNu_HT-600toInf_Tune4C_13TeV-madgraph-tauola_Spring14dr-PU_S14_POSTLS170_V6-v1-92bfc1aa0ef8c674e0edabb945b19298/USER",
"/T5Full_T5Full-1200-1000-800-Decay-MGMMatch50/schoef-T5Full_T5Full-1200-1000-800-Decay-MGMMatch50-miniAOD-92bfc1aa0ef8c674e0edabb945b19298/USER",
"/T5Full_T5Full-1500-800-100-Decay-MGMMatch50/schoef-T5Full_T5Full-1500-800-100-Decay-MGMMatch50-miniAOD-92bfc1aa0ef8c674e0edabb945b19298/USER"
]
for s in samples:
pySampleName = s[1:].replace('/','_')
#pySampleName = s[1:].replace('/','').replace('_','').replace('-','')
cfgFileName = 'New_crab_'+pySampleName+'.py'
print "Sample",s
print "Using template",templateFile
if os.path.isfile(cfgFileName) :
print "Skipping! File ",cfgFileName,"already there!!"
continue
ofile = file(cfgFileName,'w')
if not os.path.isfile(templateFile) :
print "Stop. TemplateFile not found:", templateFile
break
ifile = open(templateFile,'r')
replacements = [["DPMDIRECTORY", pySampleName], ["WORKINGDIRECTORY", '/data/easilar/crab3WorkAreas/'+pySampleName], ["SAMPLENAME", s]]
for line in ifile.readlines():
# print line
for r in replacements:
line=line.replace(r[0],r[1])
ofile.write(line)
ifile.close()
ofile.close()
print "Written",ofile.name
|
normal
|
{
"blob_id": "184b850e85b523f22a44cfde698efd96b94d819d",
"index": 2095,
"step-1": "import os\ntemplateFile = 'crab_template.py'\nsamples=[\\\n#\"/TTJets_MSDecaysCKM_central_Tune4C_13TeV-madgraph-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM\", \n#\"/TTJets_MSDecaysCKM_central_Tune4C_13TeV-madgraph-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v2/MINIAODSIM\", #Identical? Same event count #miniAODTuple_e/\n# \"/TTJets_MSDecaysCKM_central_Tune4C_13TeV-madgraph-tauola/Spring14miniaod-PU_S14_POSTLS170_V6-v1/MINIAODSIM\", #MiniAODTupleTT1e/\n# \"/WJetsToLNu_HT-200to400_Tune4C_13TeV-madgraph-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM\", #/data/easilar/crab3WorkAreas/...\n# \"/WJetsToLNu_HT-400to600_Tune4C_13TeV-madgraph-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM\", #/data/easilar/crab3WorkAreas/...\n# \"/WJetsToLNu_HT-600toInf_Tune4C_13TeV-madgraph-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM\",\n# \"/WJetsToLNu_13TeV-madgraph-pythia8-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM\",\n# \"/DYJetsToLL_M-50_HT-200to400_Tune4C_13TeV-madgraph-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM\",\n# \"/DYJetsToLL_M-50_HT-400to600_Tune4C_13TeV-madgraph-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM\",\n# \"/DYJetsToLL_M-50_HT-600toInf_Tune4C_13TeV-madgraph-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM\",\n# \"/DYJetsToLL_M-50_13TeV-madgraph-pythia8/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM\", #/data/easilar/crab3WorkAreas/...\n# \"/DYJetsToLL_M-50_13TeV-pythia6/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM\",\n# \"/DYToEE_M-50_Tune4C_13TeV-pythia8/Spring14miniaod-castor-v2/MINIAODSIM\",\n# \"/DYToEE_Tune4C_13TeV-pythia8/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM\",\n# \"/DYToMuMu_M-15To50_Tune4C_13TeV-pythia8/Spring14miniaod-castor_PU20bx25_POSTLS170_V5-v1/MINIAODSIM\",\n# \"/DYToMuMu_M-50_Tune4C_13TeV-pythia8/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM\",\n# \"/DYToMuMu_M-50_Tune4C_13TeV-pythia8/Spring14miniaod-castor_PU20bx25_POSTLS170_V5-v1/MINIAODSIM\",\n# \"/DYToMuMu_M-6To15_Tune4C_13TeV-pythia8/Spring14miniaod-castor_PU20bx25_POSTLS170_V5-v1/MINIAODSIM\",\n# \"/DYToMuMu_Tune4C_13TeV-pythia8/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM\",\n# \"/TToBLNu_s-channel-EMu_Tune4C_13TeV-madgraph-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM\",\n# \"/TToBLNu_t-channel-EMu_Tune4C_13TeV-madgraph-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM\",\n# \"/TToBLNu_tW-channel-DR-EMu_Tune4C_13TeV-madgraph-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v2/MINIAODSIM\",\n# \"/TToLeptons_s-channel-CSA14_Tune4C_13TeV-aMCatNLO-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM\",\n# \"/T_tW-channel-DR_Tune4C_13TeV-CSA14-powheg-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM\",\n# \"/Tbar_tW-channel-DR_Tune4C_13TeV-CSA14-powheg-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM\",\n# \"/TBarToLeptons_s-channel-CSA14_Tune4C_13TeV-aMCatNLO-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM\",\n# \"/TBarToLeptons_t-channel_Tune4C_CSA14_13TeV-aMCatNLO-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v1/MINIAODSIM\",\n#\"/WJetsToLNu_HT-100to200_Tune4C_13TeV-madgraph-tauola/Spring14miniaod-PU20bx25_POSTLS170_V5-v2/MINIAODSIM\",\n\n#\"/WJetsToLNu_HT-100to200_Tune4C_13TeV-madgraph-tauola/schoef-WJetsToLNu_HT-100to200_Tune4C_13TeV-madgraph-tauola_Spring14dr-PU_S14_POSTLS170_V6-v1-92bfc1aa0ef8c674e0edabb945b19298/USER\",\n#\"/WJetsToLNu_HT-200to400_Tune4C_13TeV-madgraph-tauola/schoef-WJetsToLNu_HT-200to400_Tune4C_13TeV-madgraph-tauola_Spring14dr-PU_S14_POSTLS170_V6-v1-92bfc1aa0ef8c674e0edabb945b19298/USER\",\n#\"/WJetsToLNu_HT-400to600_Tune4C_13TeV-madgraph-tauola/schoef-WJetsToLNu_HT-400to600_Tune4C_13TeV-madgraph-tauola_Spring14dr-PU_S14_POSTLS170_V6-v1-92bfc1aa0ef8c674e0edabb945b19298/USER\",\n#\"/WJetsToLNu_HT-600toInf_Tune4C_13TeV-madgraph-tauola/schoef-WJetsToLNu_HT-600toInf_Tune4C_13TeV-madgraph-tauola_Spring14dr-PU_S14_POSTLS170_V6-v1-92bfc1aa0ef8c674e0edabb945b19298/USER\",\n\"/T5Full_T5Full-1200-1000-800-Decay-MGMMatch50/schoef-T5Full_T5Full-1200-1000-800-Decay-MGMMatch50-miniAOD-92bfc1aa0ef8c674e0edabb945b19298/USER\",\n\"/T5Full_T5Full-1500-800-100-Decay-MGMMatch50/schoef-T5Full_T5Full-1500-800-100-Decay-MGMMatch50-miniAOD-92bfc1aa0ef8c674e0edabb945b19298/USER\"\n]\n\nfor s in samples:\n pySampleName = s[1:].replace('/','_')\n #pySampleName = s[1:].replace('/','').replace('_','').replace('-','')\n cfgFileName = 'New_crab_'+pySampleName+'.py'\n print \"Sample\",s\n print \"Using template\",templateFile\n if os.path.isfile(cfgFileName) :\n print \"Skipping! File \",cfgFileName,\"already there!!\"\n continue\n ofile = file(cfgFileName,'w')\n\n if not os.path.isfile(templateFile) :\n print \"Stop. TemplateFile not found:\", templateFile\n break\n ifile = open(templateFile,'r')\n\n replacements = [[\"DPMDIRECTORY\", pySampleName], [\"WORKINGDIRECTORY\", '/data/easilar/crab3WorkAreas/'+pySampleName], [\"SAMPLENAME\", s]]\n\n for line in ifile.readlines():\n# print line\n for r in replacements:\n line=line.replace(r[0],r[1])\n ofile.write(line)\n ifile.close()\n ofile.close()\n print \"Written\",ofile.name\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
class CacheDecorator:
<|reserved_special_token_0|>
def cachedFunc(self, *args):
if args not in self.cache:
print('Ergebnis berechnet')
self.cache[args] = self.func(*args)
else:
print('Ergebnis geladen')
return self.cache[args]
def __call__(self, func):
self.func = func
return self.cachedFunc
<|reserved_special_token_0|>
<|reserved_special_token_1|>
class CacheDecorator:
def __init__(self):
self.cache = {}
self.func = None
def cachedFunc(self, *args):
if args not in self.cache:
print('Ergebnis berechnet')
self.cache[args] = self.func(*args)
else:
print('Ergebnis geladen')
return self.cache[args]
def __call__(self, func):
self.func = func
return self.cachedFunc
<|reserved_special_token_0|>
<|reserved_special_token_1|>
class CacheDecorator:
def __init__(self):
self.cache = {}
self.func = None
def cachedFunc(self, *args):
if args not in self.cache:
print('Ergebnis berechnet')
self.cache[args] = self.func(*args)
else:
print('Ergebnis geladen')
return self.cache[args]
def __call__(self, func):
self.func = func
return self.cachedFunc
@CacheDecorator()
def fak(n):
ergebnis = 1
for i in range(2, n + 1):
ergebnis *= i
return ergebnis
<|reserved_special_token_0|>
<|reserved_special_token_1|>
class CacheDecorator:
def __init__(self):
self.cache = {}
self.func = None
def cachedFunc(self, *args):
if args not in self.cache:
print('Ergebnis berechnet')
self.cache[args] = self.func(*args)
else:
print('Ergebnis geladen')
return self.cache[args]
def __call__(self, func):
self.func = func
return self.cachedFunc
@CacheDecorator()
def fak(n):
ergebnis = 1
for i in range(2, n + 1):
ergebnis *= i
return ergebnis
print(fak(10))
print(fak(20))
print(fak(20))
print(fak(10))
<|reserved_special_token_1|>
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class CacheDecorator:
def __init__(self):
self.cache = {}
self.func = None
def cachedFunc(self, *args):
if args not in self.cache:
print("Ergebnis berechnet")
self.cache[args] = self.func(*args)
else:
print("Ergebnis geladen")
return self.cache[args]
def __call__(self, func):
self.func = func
return self.cachedFunc
@CacheDecorator()
def fak(n):
ergebnis = 1
for i in range(2, n+1):
ergebnis *= i
return ergebnis
print(fak(10))
print(fak(20))
print(fak(20))
print(fak(10))
|
flexible
|
{
"blob_id": "b7f6207fe6c013a964258255445004c3f4e0adbb",
"index": 7217,
"step-1": "class CacheDecorator:\n <mask token>\n\n def cachedFunc(self, *args):\n if args not in self.cache:\n print('Ergebnis berechnet')\n self.cache[args] = self.func(*args)\n else:\n print('Ergebnis geladen')\n return self.cache[args]\n\n def __call__(self, func):\n self.func = func\n return self.cachedFunc\n\n\n<mask token>\n",
"step-2": "class CacheDecorator:\n\n def __init__(self):\n self.cache = {}\n self.func = None\n\n def cachedFunc(self, *args):\n if args not in self.cache:\n print('Ergebnis berechnet')\n self.cache[args] = self.func(*args)\n else:\n print('Ergebnis geladen')\n return self.cache[args]\n\n def __call__(self, func):\n self.func = func\n return self.cachedFunc\n\n\n<mask token>\n",
"step-3": "class CacheDecorator:\n\n def __init__(self):\n self.cache = {}\n self.func = None\n\n def cachedFunc(self, *args):\n if args not in self.cache:\n print('Ergebnis berechnet')\n self.cache[args] = self.func(*args)\n else:\n print('Ergebnis geladen')\n return self.cache[args]\n\n def __call__(self, func):\n self.func = func\n return self.cachedFunc\n\n\n@CacheDecorator()\ndef fak(n):\n ergebnis = 1\n for i in range(2, n + 1):\n ergebnis *= i\n return ergebnis\n\n\n<mask token>\n",
"step-4": "class CacheDecorator:\n\n def __init__(self):\n self.cache = {}\n self.func = None\n\n def cachedFunc(self, *args):\n if args not in self.cache:\n print('Ergebnis berechnet')\n self.cache[args] = self.func(*args)\n else:\n print('Ergebnis geladen')\n return self.cache[args]\n\n def __call__(self, func):\n self.func = func\n return self.cachedFunc\n\n\n@CacheDecorator()\ndef fak(n):\n ergebnis = 1\n for i in range(2, n + 1):\n ergebnis *= i\n return ergebnis\n\n\nprint(fak(10))\nprint(fak(20))\nprint(fak(20))\nprint(fak(10))\n",
"step-5": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nclass CacheDecorator:\n def __init__(self):\n self.cache = {}\n self.func = None\n \n def cachedFunc(self, *args):\n if args not in self.cache:\n print(\"Ergebnis berechnet\")\n self.cache[args] = self.func(*args)\n else:\n print(\"Ergebnis geladen\")\n return self.cache[args]\n \n def __call__(self, func):\n self.func = func\n return self.cachedFunc\n\n@CacheDecorator()\ndef fak(n):\n ergebnis = 1\n for i in range(2, n+1):\n ergebnis *= i\n return ergebnis\n\nprint(fak(10))\nprint(fak(20))\nprint(fak(20))\nprint(fak(10))\n",
"step-ids": [
3,
4,
5,
6,
7
]
}
|
[
3,
4,
5,
6,
7
] |
# coding: utf-8
import os, sys
import numpy as np
from math import exp, sqrt, pi
def factorial(n):
value = 1
for i in range(n,1,-1):
value *= i
return value
def double_factorial(n):
k = 1
for i in range(n, 1, -2):
k *= i
#print("n:", n, "double factorial:", k)
return k
"""\int_0^\infty r^m e^{-alpha * r^2} dr"""
def gaussian_integral(alpha, m):
if int(m/2)*2 == m: # even number
n = int(m/2)
value = double_factorial(2*n-1) * sqrt(pi) / pow(2, n+1) / pow(alpha, n+0.5)
else:
n = int((m-1)/2)
value = factorial(n) / 2 / pow(alpha, n+1)
return value
def overlap_s_gaussians(expo1, expo2, power_of_r):
norm1 = pow(2*expo1/pi, 0.75)
norm2 = pow(2*expo2/pi, 0.75)
value = norm1 * norm2 * 4 * pi * gaussian_integral(expo1+expo2, power_of_r+2)
return value
|
normal
|
{
"blob_id": "005650e2747c61b730960a29891b6ba6c8bd381b",
"index": 1334,
"step-1": "<mask token>\n\n\ndef double_factorial(n):\n k = 1\n for i in range(n, 1, -2):\n k *= i\n return k\n\n\n<mask token>\n\n\ndef gaussian_integral(alpha, m):\n if int(m / 2) * 2 == m:\n n = int(m / 2)\n value = double_factorial(2 * n - 1) * sqrt(pi) / pow(2, n + 1) / pow(\n alpha, n + 0.5)\n else:\n n = int((m - 1) / 2)\n value = factorial(n) / 2 / pow(alpha, n + 1)\n return value\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef factorial(n):\n value = 1\n for i in range(n, 1, -1):\n value *= i\n return value\n\n\ndef double_factorial(n):\n k = 1\n for i in range(n, 1, -2):\n k *= i\n return k\n\n\n<mask token>\n\n\ndef gaussian_integral(alpha, m):\n if int(m / 2) * 2 == m:\n n = int(m / 2)\n value = double_factorial(2 * n - 1) * sqrt(pi) / pow(2, n + 1) / pow(\n alpha, n + 0.5)\n else:\n n = int((m - 1) / 2)\n value = factorial(n) / 2 / pow(alpha, n + 1)\n return value\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef factorial(n):\n value = 1\n for i in range(n, 1, -1):\n value *= i\n return value\n\n\ndef double_factorial(n):\n k = 1\n for i in range(n, 1, -2):\n k *= i\n return k\n\n\n<mask token>\n\n\ndef gaussian_integral(alpha, m):\n if int(m / 2) * 2 == m:\n n = int(m / 2)\n value = double_factorial(2 * n - 1) * sqrt(pi) / pow(2, n + 1) / pow(\n alpha, n + 0.5)\n else:\n n = int((m - 1) / 2)\n value = factorial(n) / 2 / pow(alpha, n + 1)\n return value\n\n\ndef overlap_s_gaussians(expo1, expo2, power_of_r):\n norm1 = pow(2 * expo1 / pi, 0.75)\n norm2 = pow(2 * expo2 / pi, 0.75)\n value = norm1 * norm2 * 4 * pi * gaussian_integral(expo1 + expo2, \n power_of_r + 2)\n return value\n",
"step-4": "import os, sys\nimport numpy as np\nfrom math import exp, sqrt, pi\n\n\ndef factorial(n):\n value = 1\n for i in range(n, 1, -1):\n value *= i\n return value\n\n\ndef double_factorial(n):\n k = 1\n for i in range(n, 1, -2):\n k *= i\n return k\n\n\n<mask token>\n\n\ndef gaussian_integral(alpha, m):\n if int(m / 2) * 2 == m:\n n = int(m / 2)\n value = double_factorial(2 * n - 1) * sqrt(pi) / pow(2, n + 1) / pow(\n alpha, n + 0.5)\n else:\n n = int((m - 1) / 2)\n value = factorial(n) / 2 / pow(alpha, n + 1)\n return value\n\n\ndef overlap_s_gaussians(expo1, expo2, power_of_r):\n norm1 = pow(2 * expo1 / pi, 0.75)\n norm2 = pow(2 * expo2 / pi, 0.75)\n value = norm1 * norm2 * 4 * pi * gaussian_integral(expo1 + expo2, \n power_of_r + 2)\n return value\n",
"step-5": "# coding: utf-8\n\nimport os, sys\nimport numpy as np\nfrom math import exp, sqrt, pi\n\ndef factorial(n):\n value = 1\n for i in range(n,1,-1):\n value *= i\n return value\n \ndef double_factorial(n):\n k = 1\n for i in range(n, 1, -2):\n k *= i\n #print(\"n:\", n, \"double factorial:\", k)\n return k\n\n\"\"\"\\int_0^\\infty r^m e^{-alpha * r^2} dr\"\"\"\ndef gaussian_integral(alpha, m):\n if int(m/2)*2 == m: # even number\n n = int(m/2)\n value = double_factorial(2*n-1) * sqrt(pi) / pow(2, n+1) / pow(alpha, n+0.5)\n else:\n n = int((m-1)/2)\n value = factorial(n) / 2 / pow(alpha, n+1)\n return value\n\ndef overlap_s_gaussians(expo1, expo2, power_of_r):\n norm1 = pow(2*expo1/pi, 0.75)\n norm2 = pow(2*expo2/pi, 0.75)\n value = norm1 * norm2 * 4 * pi * gaussian_integral(expo1+expo2, power_of_r+2)\n return value\n\n",
"step-ids": [
2,
3,
4,
5,
6
]
}
|
[
2,
3,
4,
5,
6
] |
"""
You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.
The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.
https://leetcode.com/problems/next-greater-element-i/?tab=Description
"""
class Solution(object):
def nextGreaterElement(self, findNums, nums):
"""
:type findNums: List[int]
:type nums: List[int]
:rtype: List[int]
"""
for k,v in enumerate(findNums):
try:
index = nums.index(v)
except ValueError:
findNums[k] = -1
else:
findNums[k] = -1
for i in range(index+1, len(nums)):
if nums[i] > v:
findNums[k] = nums[i]
break
return findNums
def test():
sol = Solution()
findnums = [2,4]
nums = [1,2,3,4]
print(sol.nextGreaterElement(findnums,nums))
test()
|
normal
|
{
"blob_id": "3abeac4fb80244d2da14e14a6048c09b0c0c1393",
"index": 6047,
"step-1": "<mask token>\n\n\nclass Solution(object):\n <mask token>\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass Solution(object):\n\n def nextGreaterElement(self, findNums, nums):\n \"\"\"\n :type findNums: List[int]\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n for k, v in enumerate(findNums):\n try:\n index = nums.index(v)\n except ValueError:\n findNums[k] = -1\n else:\n findNums[k] = -1\n for i in range(index + 1, len(nums)):\n if nums[i] > v:\n findNums[k] = nums[i]\n break\n return findNums\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass Solution(object):\n\n def nextGreaterElement(self, findNums, nums):\n \"\"\"\n :type findNums: List[int]\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n for k, v in enumerate(findNums):\n try:\n index = nums.index(v)\n except ValueError:\n findNums[k] = -1\n else:\n findNums[k] = -1\n for i in range(index + 1, len(nums)):\n if nums[i] > v:\n findNums[k] = nums[i]\n break\n return findNums\n\n\ndef test():\n sol = Solution()\n findnums = [2, 4]\n nums = [1, 2, 3, 4]\n print(sol.nextGreaterElement(findnums, nums))\n\n\n<mask token>\n",
"step-4": "<mask token>\n\n\nclass Solution(object):\n\n def nextGreaterElement(self, findNums, nums):\n \"\"\"\n :type findNums: List[int]\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n for k, v in enumerate(findNums):\n try:\n index = nums.index(v)\n except ValueError:\n findNums[k] = -1\n else:\n findNums[k] = -1\n for i in range(index + 1, len(nums)):\n if nums[i] > v:\n findNums[k] = nums[i]\n break\n return findNums\n\n\ndef test():\n sol = Solution()\n findnums = [2, 4]\n nums = [1, 2, 3, 4]\n print(sol.nextGreaterElement(findnums, nums))\n\n\ntest()\n",
"step-5": "\"\"\"\nYou are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.\n\nThe Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.\nhttps://leetcode.com/problems/next-greater-element-i/?tab=Description\n\"\"\"\nclass Solution(object):\n def nextGreaterElement(self, findNums, nums):\n \"\"\"\n :type findNums: List[int]\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n for k,v in enumerate(findNums):\n try:\n index = nums.index(v)\n except ValueError:\n findNums[k] = -1\n else:\n findNums[k] = -1\n for i in range(index+1, len(nums)):\n if nums[i] > v:\n findNums[k] = nums[i]\n break\n return findNums\n\ndef test():\n sol = Solution()\n findnums = [2,4]\n nums = [1,2,3,4]\n print(sol.nextGreaterElement(findnums,nums))\n\ntest()",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
try:
from local_settings import *
except ImportError:
pass
if SENTRY_URL:
import sentry_sdk
sentry_sdk.init(SENTRY_URL)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
WOO_HOST = os.environ.get('WOO_HOST')
WOO_CONSUMER_KEY = os.environ.get('WOO_CONSUMER_KEY')
WOO_CONSUMER_SECRET = os.environ.get('WOO_CONSUMER_SECRET')
XML_FEED_FILENAME = os.environ.get('XML_FEED_FILENAME', 'feedXML')
XML_SITE_NAME = os.environ.get('XML_SITE_NAME')
XML_SITE_HOST = os.environ.get('XML_SITE_HOST')
XML_FEED_DESCRIPTION = os.environ.get('XML_FEED_DESCRIPTION',
'Feed XML autogenerated')
XML_CONFIG_FILENAME = os.environ.get('XML_CONFIG_FILENAME', 'config.json')
PRODUCTS_STATUS_CODE = os.environ.get('PRODUCTS_STATUS_CODE', 'publish')
CRONTAB_HOUR = os.environ.get('CRONTAB_HOUR', '*/7')
REDIS_HOST = os.environ.get('REDIS_HOST', 'redis')
SENTRY_URL = os.environ.get('SENTRY_URL')
try:
from local_settings import *
except ImportError:
pass
if SENTRY_URL:
import sentry_sdk
sentry_sdk.init(SENTRY_URL)
<|reserved_special_token_1|>
import os
WOO_HOST = os.environ.get('WOO_HOST')
WOO_CONSUMER_KEY = os.environ.get('WOO_CONSUMER_KEY')
WOO_CONSUMER_SECRET = os.environ.get('WOO_CONSUMER_SECRET')
XML_FEED_FILENAME = os.environ.get('XML_FEED_FILENAME', 'feedXML')
XML_SITE_NAME = os.environ.get('XML_SITE_NAME')
XML_SITE_HOST = os.environ.get('XML_SITE_HOST')
XML_FEED_DESCRIPTION = os.environ.get('XML_FEED_DESCRIPTION',
'Feed XML autogenerated')
XML_CONFIG_FILENAME = os.environ.get('XML_CONFIG_FILENAME', 'config.json')
PRODUCTS_STATUS_CODE = os.environ.get('PRODUCTS_STATUS_CODE', 'publish')
CRONTAB_HOUR = os.environ.get('CRONTAB_HOUR', '*/7')
REDIS_HOST = os.environ.get('REDIS_HOST', 'redis')
SENTRY_URL = os.environ.get('SENTRY_URL')
try:
from local_settings import *
except ImportError:
pass
if SENTRY_URL:
import sentry_sdk
sentry_sdk.init(SENTRY_URL)
<|reserved_special_token_1|>
import os
WOO_HOST = os.environ.get('WOO_HOST')
#WooCommerce key credentials
WOO_CONSUMER_KEY = os.environ.get('WOO_CONSUMER_KEY')
WOO_CONSUMER_SECRET = os.environ.get('WOO_CONSUMER_SECRET')
#XML feed fields and settings
XML_FEED_FILENAME = os.environ.get('XML_FEED_FILENAME', 'feedXML')
XML_SITE_NAME = os.environ.get('XML_SITE_NAME')
XML_SITE_HOST = os.environ.get('XML_SITE_HOST')
XML_FEED_DESCRIPTION = os.environ.get('XML_FEED_DESCRIPTION', 'Feed XML autogenerated')
XML_CONFIG_FILENAME = os.environ.get('XML_CONFIG_FILENAME', 'config.json')
PRODUCTS_STATUS_CODE = os.environ.get('PRODUCTS_STATUS_CODE', 'publish')
CRONTAB_HOUR = os.environ.get('CRONTAB_HOUR', '*/7')
REDIS_HOST = os.environ.get('REDIS_HOST', 'redis')
SENTRY_URL = os.environ.get('SENTRY_URL')
try:
from local_settings import *
except ImportError:
pass
if SENTRY_URL:
import sentry_sdk
sentry_sdk.init(SENTRY_URL)
|
flexible
|
{
"blob_id": "386fa51b9b285d36c75d6446f9348f6713e0dbaa",
"index": 2794,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ntry:\n from local_settings import *\nexcept ImportError:\n pass\nif SENTRY_URL:\n import sentry_sdk\n sentry_sdk.init(SENTRY_URL)\n",
"step-3": "<mask token>\nWOO_HOST = os.environ.get('WOO_HOST')\nWOO_CONSUMER_KEY = os.environ.get('WOO_CONSUMER_KEY')\nWOO_CONSUMER_SECRET = os.environ.get('WOO_CONSUMER_SECRET')\nXML_FEED_FILENAME = os.environ.get('XML_FEED_FILENAME', 'feedXML')\nXML_SITE_NAME = os.environ.get('XML_SITE_NAME')\nXML_SITE_HOST = os.environ.get('XML_SITE_HOST')\nXML_FEED_DESCRIPTION = os.environ.get('XML_FEED_DESCRIPTION',\n 'Feed XML autogenerated')\nXML_CONFIG_FILENAME = os.environ.get('XML_CONFIG_FILENAME', 'config.json')\nPRODUCTS_STATUS_CODE = os.environ.get('PRODUCTS_STATUS_CODE', 'publish')\nCRONTAB_HOUR = os.environ.get('CRONTAB_HOUR', '*/7')\nREDIS_HOST = os.environ.get('REDIS_HOST', 'redis')\nSENTRY_URL = os.environ.get('SENTRY_URL')\ntry:\n from local_settings import *\nexcept ImportError:\n pass\nif SENTRY_URL:\n import sentry_sdk\n sentry_sdk.init(SENTRY_URL)\n",
"step-4": "import os\nWOO_HOST = os.environ.get('WOO_HOST')\nWOO_CONSUMER_KEY = os.environ.get('WOO_CONSUMER_KEY')\nWOO_CONSUMER_SECRET = os.environ.get('WOO_CONSUMER_SECRET')\nXML_FEED_FILENAME = os.environ.get('XML_FEED_FILENAME', 'feedXML')\nXML_SITE_NAME = os.environ.get('XML_SITE_NAME')\nXML_SITE_HOST = os.environ.get('XML_SITE_HOST')\nXML_FEED_DESCRIPTION = os.environ.get('XML_FEED_DESCRIPTION',\n 'Feed XML autogenerated')\nXML_CONFIG_FILENAME = os.environ.get('XML_CONFIG_FILENAME', 'config.json')\nPRODUCTS_STATUS_CODE = os.environ.get('PRODUCTS_STATUS_CODE', 'publish')\nCRONTAB_HOUR = os.environ.get('CRONTAB_HOUR', '*/7')\nREDIS_HOST = os.environ.get('REDIS_HOST', 'redis')\nSENTRY_URL = os.environ.get('SENTRY_URL')\ntry:\n from local_settings import *\nexcept ImportError:\n pass\nif SENTRY_URL:\n import sentry_sdk\n sentry_sdk.init(SENTRY_URL)\n",
"step-5": "import os\n\nWOO_HOST = os.environ.get('WOO_HOST')\n\n#WooCommerce key credentials\nWOO_CONSUMER_KEY = os.environ.get('WOO_CONSUMER_KEY')\nWOO_CONSUMER_SECRET = os.environ.get('WOO_CONSUMER_SECRET')\n\n#XML feed fields and settings\nXML_FEED_FILENAME = os.environ.get('XML_FEED_FILENAME', 'feedXML')\nXML_SITE_NAME = os.environ.get('XML_SITE_NAME')\nXML_SITE_HOST = os.environ.get('XML_SITE_HOST')\nXML_FEED_DESCRIPTION = os.environ.get('XML_FEED_DESCRIPTION', 'Feed XML autogenerated')\nXML_CONFIG_FILENAME = os.environ.get('XML_CONFIG_FILENAME', 'config.json')\n\nPRODUCTS_STATUS_CODE = os.environ.get('PRODUCTS_STATUS_CODE', 'publish')\n\nCRONTAB_HOUR = os.environ.get('CRONTAB_HOUR', '*/7')\n\nREDIS_HOST = os.environ.get('REDIS_HOST', 'redis')\n\nSENTRY_URL = os.environ.get('SENTRY_URL')\n\ntry:\n from local_settings import *\nexcept ImportError:\n pass\n\nif SENTRY_URL:\n import sentry_sdk\n sentry_sdk.init(SENTRY_URL)\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
from tkinter import *
root = Tk()
ent = Entry(root)
ent.pack()
def click():
ent_text = ent.get()
lab = Label(root, text=ent_text)
lab.pack()
btn = Button(root, text="Click Me!", command=click)
btn.pack()
root.mainloop()
|
normal
|
{
"blob_id": "49f1b4c9c6d15b8322b83396c22e1027d241da33",
"index": 2311,
"step-1": "<mask token>\n\n\ndef click():\n ent_text = ent.get()\n lab = Label(root, text=ent_text)\n lab.pack()\n\n\n<mask token>\n",
"step-2": "<mask token>\nent.pack()\n\n\ndef click():\n ent_text = ent.get()\n lab = Label(root, text=ent_text)\n lab.pack()\n\n\n<mask token>\nbtn.pack()\nroot.mainloop()\n",
"step-3": "<mask token>\nroot = Tk()\nent = Entry(root)\nent.pack()\n\n\ndef click():\n ent_text = ent.get()\n lab = Label(root, text=ent_text)\n lab.pack()\n\n\nbtn = Button(root, text='Click Me!', command=click)\nbtn.pack()\nroot.mainloop()\n",
"step-4": "from tkinter import *\nroot = Tk()\nent = Entry(root)\nent.pack()\n\n\ndef click():\n ent_text = ent.get()\n lab = Label(root, text=ent_text)\n lab.pack()\n\n\nbtn = Button(root, text='Click Me!', command=click)\nbtn.pack()\nroot.mainloop()\n",
"step-5": "from tkinter import *\n\nroot = Tk()\nent = Entry(root)\nent.pack()\n\n\ndef click():\n ent_text = ent.get()\n lab = Label(root, text=ent_text)\n lab.pack()\n\n\nbtn = Button(root, text=\"Click Me!\", command=click)\nbtn.pack()\n\nroot.mainloop()\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
<|reserved_special_token_0|>
def get_all_countries():
response = requests.get('{}/countries'.format(ROOT_URL))
return response.json()['countries']
def get_country_probability(countryIds):
body = {'countryIds': countryIds}
response = requests.get('{}/countries/probability'.format(ROOT_URL),
data=body)
return response.json()['probability']
def add_country(country_name, country_code):
body = {'country_name': country_name, 'country_code': country_code}
response = requests.post('{}/countries'.format(ROOT_URL), data=body)
return response.json()
def update_country(id, country_name=None, country_code=None):
body = {'id': id}
if country_name != None:
body['country_name'] = country_name
if country_code != None:
body['country_code'] = country_code
response = requests.put('{}/countries'.format(ROOT_URL), data=body)
return response.json()['updates']
<|reserved_special_token_0|>
def get_all_symptoms():
response = requests.get('{}/symptoms'.format(ROOT_URL))
return response.json()['symptoms']
def get_symptom_probability(symptomIds):
body = {'symptomIds': symptomIds}
response = requests.get('{}/symptoms/probability'.format(ROOT_URL),
data=body)
return response.json()['probability']
<|reserved_special_token_0|>
def update_symptom(id, name=None):
body = {'id': id}
if name != None:
body['name'] = name
response = requests.put('{}/symptoms'.format(ROOT_URL), data=body)
return response.json()['updates']
def delete_symptom(id):
body = {'id': id}
response = requests.delete('{}/symptoms'.format(ROOT_URL), data=body)
return response.json()
def get_diagnosis(id):
id = str(id)
response = requests.get('{}/diagnoses?id={}'.format(ROOT_URL, id))
return response.json()['diagnosis']
def get_all_diagnoses():
response = requests.get('{}/diagnoses'.format(ROOT_URL))
return response.json()['diagnoses']
def add_diagnosis(name, temperature, result, countryIds, symptomIds):
body = {'name': name, 'temperature': temperature, 'result': result,
'countryIds': countryIds, 'symptomIds': symptomIds}
response = requests.post('{}/diagnoses'.format(ROOT_URL), data=body)
return response.json()
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def get_all_countries():
response = requests.get('{}/countries'.format(ROOT_URL))
return response.json()['countries']
def get_country_probability(countryIds):
body = {'countryIds': countryIds}
response = requests.get('{}/countries/probability'.format(ROOT_URL),
data=body)
return response.json()['probability']
def add_country(country_name, country_code):
body = {'country_name': country_name, 'country_code': country_code}
response = requests.post('{}/countries'.format(ROOT_URL), data=body)
return response.json()
def update_country(id, country_name=None, country_code=None):
body = {'id': id}
if country_name != None:
body['country_name'] = country_name
if country_code != None:
body['country_code'] = country_code
response = requests.put('{}/countries'.format(ROOT_URL), data=body)
return response.json()['updates']
<|reserved_special_token_0|>
def get_all_symptoms():
response = requests.get('{}/symptoms'.format(ROOT_URL))
return response.json()['symptoms']
def get_symptom_probability(symptomIds):
body = {'symptomIds': symptomIds}
response = requests.get('{}/symptoms/probability'.format(ROOT_URL),
data=body)
return response.json()['probability']
<|reserved_special_token_0|>
def update_symptom(id, name=None):
body = {'id': id}
if name != None:
body['name'] = name
response = requests.put('{}/symptoms'.format(ROOT_URL), data=body)
return response.json()['updates']
def delete_symptom(id):
body = {'id': id}
response = requests.delete('{}/symptoms'.format(ROOT_URL), data=body)
return response.json()
def get_diagnosis(id):
id = str(id)
response = requests.get('{}/diagnoses?id={}'.format(ROOT_URL, id))
return response.json()['diagnosis']
def get_all_diagnoses():
response = requests.get('{}/diagnoses'.format(ROOT_URL))
return response.json()['diagnoses']
def add_diagnosis(name, temperature, result, countryIds, symptomIds):
body = {'name': name, 'temperature': temperature, 'result': result,
'countryIds': countryIds, 'symptomIds': symptomIds}
response = requests.post('{}/diagnoses'.format(ROOT_URL), data=body)
return response.json()
def delete_diagnosis(id):
body = {'id': id}
response = requests.delete('{}/diagnoses'.format(ROOT_URL), data=body)
return response.json()
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def get_all_countries():
response = requests.get('{}/countries'.format(ROOT_URL))
return response.json()['countries']
def get_country_probability(countryIds):
body = {'countryIds': countryIds}
response = requests.get('{}/countries/probability'.format(ROOT_URL),
data=body)
return response.json()['probability']
def add_country(country_name, country_code):
body = {'country_name': country_name, 'country_code': country_code}
response = requests.post('{}/countries'.format(ROOT_URL), data=body)
return response.json()
def update_country(id, country_name=None, country_code=None):
body = {'id': id}
if country_name != None:
body['country_name'] = country_name
if country_code != None:
body['country_code'] = country_code
response = requests.put('{}/countries'.format(ROOT_URL), data=body)
return response.json()['updates']
def delete_country(id):
body = {'id': id}
response = requests.delete('{}/countries'.format(ROOT_URL), data=body)
return response.json()
def get_all_symptoms():
response = requests.get('{}/symptoms'.format(ROOT_URL))
return response.json()['symptoms']
def get_symptom_probability(symptomIds):
body = {'symptomIds': symptomIds}
response = requests.get('{}/symptoms/probability'.format(ROOT_URL),
data=body)
return response.json()['probability']
def add_symptom(name):
body = {'name': name}
response = requests.post('{}/symptoms'.format(ROOT_URL), data=body)
return response.json()
def update_symptom(id, name=None):
body = {'id': id}
if name != None:
body['name'] = name
response = requests.put('{}/symptoms'.format(ROOT_URL), data=body)
return response.json()['updates']
def delete_symptom(id):
body = {'id': id}
response = requests.delete('{}/symptoms'.format(ROOT_URL), data=body)
return response.json()
def get_diagnosis(id):
id = str(id)
response = requests.get('{}/diagnoses?id={}'.format(ROOT_URL, id))
return response.json()['diagnosis']
def get_all_diagnoses():
response = requests.get('{}/diagnoses'.format(ROOT_URL))
return response.json()['diagnoses']
def add_diagnosis(name, temperature, result, countryIds, symptomIds):
body = {'name': name, 'temperature': temperature, 'result': result,
'countryIds': countryIds, 'symptomIds': symptomIds}
response = requests.post('{}/diagnoses'.format(ROOT_URL), data=body)
return response.json()
def delete_diagnosis(id):
body = {'id': id}
response = requests.delete('{}/diagnoses'.format(ROOT_URL), data=body)
return response.json()
if __name__ == '__main__':
pass
<|reserved_special_token_1|>
import requests
import json
ROOT_URL = 'http://localhost:5000'
def get_all_countries():
response = requests.get('{}/countries'.format(ROOT_URL))
return response.json()['countries']
def get_country_probability(countryIds):
body = {'countryIds': countryIds}
response = requests.get('{}/countries/probability'.format(ROOT_URL),
data=body)
return response.json()['probability']
def add_country(country_name, country_code):
body = {'country_name': country_name, 'country_code': country_code}
response = requests.post('{}/countries'.format(ROOT_URL), data=body)
return response.json()
def update_country(id, country_name=None, country_code=None):
body = {'id': id}
if country_name != None:
body['country_name'] = country_name
if country_code != None:
body['country_code'] = country_code
response = requests.put('{}/countries'.format(ROOT_URL), data=body)
return response.json()['updates']
def delete_country(id):
body = {'id': id}
response = requests.delete('{}/countries'.format(ROOT_URL), data=body)
return response.json()
def get_all_symptoms():
response = requests.get('{}/symptoms'.format(ROOT_URL))
return response.json()['symptoms']
def get_symptom_probability(symptomIds):
body = {'symptomIds': symptomIds}
response = requests.get('{}/symptoms/probability'.format(ROOT_URL),
data=body)
return response.json()['probability']
def add_symptom(name):
body = {'name': name}
response = requests.post('{}/symptoms'.format(ROOT_URL), data=body)
return response.json()
def update_symptom(id, name=None):
body = {'id': id}
if name != None:
body['name'] = name
response = requests.put('{}/symptoms'.format(ROOT_URL), data=body)
return response.json()['updates']
def delete_symptom(id):
body = {'id': id}
response = requests.delete('{}/symptoms'.format(ROOT_URL), data=body)
return response.json()
def get_diagnosis(id):
id = str(id)
response = requests.get('{}/diagnoses?id={}'.format(ROOT_URL, id))
return response.json()['diagnosis']
def get_all_diagnoses():
response = requests.get('{}/diagnoses'.format(ROOT_URL))
return response.json()['diagnoses']
def add_diagnosis(name, temperature, result, countryIds, symptomIds):
body = {'name': name, 'temperature': temperature, 'result': result,
'countryIds': countryIds, 'symptomIds': symptomIds}
response = requests.post('{}/diagnoses'.format(ROOT_URL), data=body)
return response.json()
def delete_diagnosis(id):
body = {'id': id}
response = requests.delete('{}/diagnoses'.format(ROOT_URL), data=body)
return response.json()
if __name__ == '__main__':
pass
<|reserved_special_token_1|>
import requests
import json
ROOT_URL = "http://localhost:5000"
def get_all_countries():
response = requests.get("{}/countries".format(ROOT_URL))
return response.json()["countries"]
def get_country_probability(countryIds):
body = {"countryIds": countryIds}
response = requests.get("{}/countries/probability".format(ROOT_URL), data=body)
return response.json()["probability"]
def add_country(country_name, country_code):
body = {"country_name": country_name, "country_code": country_code}
response = requests.post("{}/countries".format(ROOT_URL), data=body)
return response.json()
def update_country(id, country_name=None, country_code=None):
body = {"id": id}
if country_name != None:
body["country_name"] = country_name
if country_code != None:
body["country_code"] = country_code
response = requests.put("{}/countries".format(ROOT_URL), data=body)
return response.json()["updates"]
def delete_country(id):
body = {"id": id}
response = requests.delete("{}/countries".format(ROOT_URL), data=body)
return response.json()
def get_all_symptoms():
response = requests.get("{}/symptoms".format(ROOT_URL))
return response.json()["symptoms"]
def get_symptom_probability(symptomIds):
body = {"symptomIds": symptomIds}
response = requests.get("{}/symptoms/probability".format(ROOT_URL), data=body)
return response.json()["probability"]
def add_symptom(name):
body = {"name": name}
response = requests.post("{}/symptoms".format(ROOT_URL), data=body)
return response.json()
def update_symptom(id, name=None):
body = {"id": id}
if name != None:
body["name"] = name
response = requests.put("{}/symptoms".format(ROOT_URL), data=body)
return response.json()["updates"]
def delete_symptom(id):
body = {"id": id}
response = requests.delete("{}/symptoms".format(ROOT_URL), data=body)
return response.json()
def get_diagnosis(id):
id = str(id)
response = requests.get("{}/diagnoses?id={}".format(ROOT_URL, id))
return response.json()["diagnosis"]
def get_all_diagnoses():
response = requests.get("{}/diagnoses".format(ROOT_URL))
return response.json()["diagnoses"]
def add_diagnosis(name, temperature, result, countryIds, symptomIds):
body = {"name": name, "temperature": temperature, "result": result, "countryIds": countryIds, "symptomIds": symptomIds}
response = requests.post("{}/diagnoses".format(ROOT_URL), data=body)
return response.json()
def delete_diagnosis(id):
body = {"id": id}
response = requests.delete("{}/diagnoses".format(ROOT_URL), data=body)
return response.json()
if __name__ == '__main__':
pass
|
flexible
|
{
"blob_id": "6aa7114db66a76cfa9659f5537b1056f40f47bd2",
"index": 3975,
"step-1": "<mask token>\n\n\ndef get_all_countries():\n response = requests.get('{}/countries'.format(ROOT_URL))\n return response.json()['countries']\n\n\ndef get_country_probability(countryIds):\n body = {'countryIds': countryIds}\n response = requests.get('{}/countries/probability'.format(ROOT_URL),\n data=body)\n return response.json()['probability']\n\n\ndef add_country(country_name, country_code):\n body = {'country_name': country_name, 'country_code': country_code}\n response = requests.post('{}/countries'.format(ROOT_URL), data=body)\n return response.json()\n\n\ndef update_country(id, country_name=None, country_code=None):\n body = {'id': id}\n if country_name != None:\n body['country_name'] = country_name\n if country_code != None:\n body['country_code'] = country_code\n response = requests.put('{}/countries'.format(ROOT_URL), data=body)\n return response.json()['updates']\n\n\n<mask token>\n\n\ndef get_all_symptoms():\n response = requests.get('{}/symptoms'.format(ROOT_URL))\n return response.json()['symptoms']\n\n\ndef get_symptom_probability(symptomIds):\n body = {'symptomIds': symptomIds}\n response = requests.get('{}/symptoms/probability'.format(ROOT_URL),\n data=body)\n return response.json()['probability']\n\n\n<mask token>\n\n\ndef update_symptom(id, name=None):\n body = {'id': id}\n if name != None:\n body['name'] = name\n response = requests.put('{}/symptoms'.format(ROOT_URL), data=body)\n return response.json()['updates']\n\n\ndef delete_symptom(id):\n body = {'id': id}\n response = requests.delete('{}/symptoms'.format(ROOT_URL), data=body)\n return response.json()\n\n\ndef get_diagnosis(id):\n id = str(id)\n response = requests.get('{}/diagnoses?id={}'.format(ROOT_URL, id))\n return response.json()['diagnosis']\n\n\ndef get_all_diagnoses():\n response = requests.get('{}/diagnoses'.format(ROOT_URL))\n return response.json()['diagnoses']\n\n\ndef add_diagnosis(name, temperature, result, countryIds, symptomIds):\n body = {'name': name, 'temperature': temperature, 'result': result,\n 'countryIds': countryIds, 'symptomIds': symptomIds}\n response = requests.post('{}/diagnoses'.format(ROOT_URL), data=body)\n return response.json()\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef get_all_countries():\n response = requests.get('{}/countries'.format(ROOT_URL))\n return response.json()['countries']\n\n\ndef get_country_probability(countryIds):\n body = {'countryIds': countryIds}\n response = requests.get('{}/countries/probability'.format(ROOT_URL),\n data=body)\n return response.json()['probability']\n\n\ndef add_country(country_name, country_code):\n body = {'country_name': country_name, 'country_code': country_code}\n response = requests.post('{}/countries'.format(ROOT_URL), data=body)\n return response.json()\n\n\ndef update_country(id, country_name=None, country_code=None):\n body = {'id': id}\n if country_name != None:\n body['country_name'] = country_name\n if country_code != None:\n body['country_code'] = country_code\n response = requests.put('{}/countries'.format(ROOT_URL), data=body)\n return response.json()['updates']\n\n\n<mask token>\n\n\ndef get_all_symptoms():\n response = requests.get('{}/symptoms'.format(ROOT_URL))\n return response.json()['symptoms']\n\n\ndef get_symptom_probability(symptomIds):\n body = {'symptomIds': symptomIds}\n response = requests.get('{}/symptoms/probability'.format(ROOT_URL),\n data=body)\n return response.json()['probability']\n\n\n<mask token>\n\n\ndef update_symptom(id, name=None):\n body = {'id': id}\n if name != None:\n body['name'] = name\n response = requests.put('{}/symptoms'.format(ROOT_URL), data=body)\n return response.json()['updates']\n\n\ndef delete_symptom(id):\n body = {'id': id}\n response = requests.delete('{}/symptoms'.format(ROOT_URL), data=body)\n return response.json()\n\n\ndef get_diagnosis(id):\n id = str(id)\n response = requests.get('{}/diagnoses?id={}'.format(ROOT_URL, id))\n return response.json()['diagnosis']\n\n\ndef get_all_diagnoses():\n response = requests.get('{}/diagnoses'.format(ROOT_URL))\n return response.json()['diagnoses']\n\n\ndef add_diagnosis(name, temperature, result, countryIds, symptomIds):\n body = {'name': name, 'temperature': temperature, 'result': result,\n 'countryIds': countryIds, 'symptomIds': symptomIds}\n response = requests.post('{}/diagnoses'.format(ROOT_URL), data=body)\n return response.json()\n\n\ndef delete_diagnosis(id):\n body = {'id': id}\n response = requests.delete('{}/diagnoses'.format(ROOT_URL), data=body)\n return response.json()\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef get_all_countries():\n response = requests.get('{}/countries'.format(ROOT_URL))\n return response.json()['countries']\n\n\ndef get_country_probability(countryIds):\n body = {'countryIds': countryIds}\n response = requests.get('{}/countries/probability'.format(ROOT_URL),\n data=body)\n return response.json()['probability']\n\n\ndef add_country(country_name, country_code):\n body = {'country_name': country_name, 'country_code': country_code}\n response = requests.post('{}/countries'.format(ROOT_URL), data=body)\n return response.json()\n\n\ndef update_country(id, country_name=None, country_code=None):\n body = {'id': id}\n if country_name != None:\n body['country_name'] = country_name\n if country_code != None:\n body['country_code'] = country_code\n response = requests.put('{}/countries'.format(ROOT_URL), data=body)\n return response.json()['updates']\n\n\ndef delete_country(id):\n body = {'id': id}\n response = requests.delete('{}/countries'.format(ROOT_URL), data=body)\n return response.json()\n\n\ndef get_all_symptoms():\n response = requests.get('{}/symptoms'.format(ROOT_URL))\n return response.json()['symptoms']\n\n\ndef get_symptom_probability(symptomIds):\n body = {'symptomIds': symptomIds}\n response = requests.get('{}/symptoms/probability'.format(ROOT_URL),\n data=body)\n return response.json()['probability']\n\n\ndef add_symptom(name):\n body = {'name': name}\n response = requests.post('{}/symptoms'.format(ROOT_URL), data=body)\n return response.json()\n\n\ndef update_symptom(id, name=None):\n body = {'id': id}\n if name != None:\n body['name'] = name\n response = requests.put('{}/symptoms'.format(ROOT_URL), data=body)\n return response.json()['updates']\n\n\ndef delete_symptom(id):\n body = {'id': id}\n response = requests.delete('{}/symptoms'.format(ROOT_URL), data=body)\n return response.json()\n\n\ndef get_diagnosis(id):\n id = str(id)\n response = requests.get('{}/diagnoses?id={}'.format(ROOT_URL, id))\n return response.json()['diagnosis']\n\n\ndef get_all_diagnoses():\n response = requests.get('{}/diagnoses'.format(ROOT_URL))\n return response.json()['diagnoses']\n\n\ndef add_diagnosis(name, temperature, result, countryIds, symptomIds):\n body = {'name': name, 'temperature': temperature, 'result': result,\n 'countryIds': countryIds, 'symptomIds': symptomIds}\n response = requests.post('{}/diagnoses'.format(ROOT_URL), data=body)\n return response.json()\n\n\ndef delete_diagnosis(id):\n body = {'id': id}\n response = requests.delete('{}/diagnoses'.format(ROOT_URL), data=body)\n return response.json()\n\n\nif __name__ == '__main__':\n pass\n",
"step-4": "import requests\nimport json\nROOT_URL = 'http://localhost:5000'\n\n\ndef get_all_countries():\n response = requests.get('{}/countries'.format(ROOT_URL))\n return response.json()['countries']\n\n\ndef get_country_probability(countryIds):\n body = {'countryIds': countryIds}\n response = requests.get('{}/countries/probability'.format(ROOT_URL),\n data=body)\n return response.json()['probability']\n\n\ndef add_country(country_name, country_code):\n body = {'country_name': country_name, 'country_code': country_code}\n response = requests.post('{}/countries'.format(ROOT_URL), data=body)\n return response.json()\n\n\ndef update_country(id, country_name=None, country_code=None):\n body = {'id': id}\n if country_name != None:\n body['country_name'] = country_name\n if country_code != None:\n body['country_code'] = country_code\n response = requests.put('{}/countries'.format(ROOT_URL), data=body)\n return response.json()['updates']\n\n\ndef delete_country(id):\n body = {'id': id}\n response = requests.delete('{}/countries'.format(ROOT_URL), data=body)\n return response.json()\n\n\ndef get_all_symptoms():\n response = requests.get('{}/symptoms'.format(ROOT_URL))\n return response.json()['symptoms']\n\n\ndef get_symptom_probability(symptomIds):\n body = {'symptomIds': symptomIds}\n response = requests.get('{}/symptoms/probability'.format(ROOT_URL),\n data=body)\n return response.json()['probability']\n\n\ndef add_symptom(name):\n body = {'name': name}\n response = requests.post('{}/symptoms'.format(ROOT_URL), data=body)\n return response.json()\n\n\ndef update_symptom(id, name=None):\n body = {'id': id}\n if name != None:\n body['name'] = name\n response = requests.put('{}/symptoms'.format(ROOT_URL), data=body)\n return response.json()['updates']\n\n\ndef delete_symptom(id):\n body = {'id': id}\n response = requests.delete('{}/symptoms'.format(ROOT_URL), data=body)\n return response.json()\n\n\ndef get_diagnosis(id):\n id = str(id)\n response = requests.get('{}/diagnoses?id={}'.format(ROOT_URL, id))\n return response.json()['diagnosis']\n\n\ndef get_all_diagnoses():\n response = requests.get('{}/diagnoses'.format(ROOT_URL))\n return response.json()['diagnoses']\n\n\ndef add_diagnosis(name, temperature, result, countryIds, symptomIds):\n body = {'name': name, 'temperature': temperature, 'result': result,\n 'countryIds': countryIds, 'symptomIds': symptomIds}\n response = requests.post('{}/diagnoses'.format(ROOT_URL), data=body)\n return response.json()\n\n\ndef delete_diagnosis(id):\n body = {'id': id}\n response = requests.delete('{}/diagnoses'.format(ROOT_URL), data=body)\n return response.json()\n\n\nif __name__ == '__main__':\n pass\n",
"step-5": "import requests\nimport json\n\nROOT_URL = \"http://localhost:5000\"\n\ndef get_all_countries():\n\tresponse = requests.get(\"{}/countries\".format(ROOT_URL))\n\treturn response.json()[\"countries\"]\n\ndef get_country_probability(countryIds):\n\tbody = {\"countryIds\": countryIds}\n\tresponse = requests.get(\"{}/countries/probability\".format(ROOT_URL), data=body)\n\treturn response.json()[\"probability\"]\n\ndef add_country(country_name, country_code):\n\tbody = {\"country_name\": country_name, \"country_code\": country_code}\n\tresponse = requests.post(\"{}/countries\".format(ROOT_URL), data=body)\n\treturn response.json()\n\ndef update_country(id, country_name=None, country_code=None):\n\tbody = {\"id\": id}\n\tif country_name != None:\n\t\tbody[\"country_name\"] = country_name\n\tif country_code != None:\n\t\tbody[\"country_code\"] = country_code\n\tresponse = requests.put(\"{}/countries\".format(ROOT_URL), data=body)\n\treturn response.json()[\"updates\"]\n\ndef delete_country(id):\n\tbody = {\"id\": id}\n\tresponse = requests.delete(\"{}/countries\".format(ROOT_URL), data=body)\n\treturn response.json()\n\ndef get_all_symptoms():\n\tresponse = requests.get(\"{}/symptoms\".format(ROOT_URL))\n\treturn response.json()[\"symptoms\"]\n\ndef get_symptom_probability(symptomIds):\n\tbody = {\"symptomIds\": symptomIds}\n\tresponse = requests.get(\"{}/symptoms/probability\".format(ROOT_URL), data=body)\n\treturn response.json()[\"probability\"]\n\ndef add_symptom(name):\n\tbody = {\"name\": name}\n\tresponse = requests.post(\"{}/symptoms\".format(ROOT_URL), data=body)\n\treturn response.json()\n\ndef update_symptom(id, name=None):\n\tbody = {\"id\": id}\n\tif name != None:\n\t\tbody[\"name\"] = name\n\n\tresponse = requests.put(\"{}/symptoms\".format(ROOT_URL), data=body)\n\treturn response.json()[\"updates\"]\n\ndef delete_symptom(id):\n\tbody = {\"id\": id}\n\tresponse = requests.delete(\"{}/symptoms\".format(ROOT_URL), data=body)\n\treturn response.json()\n\ndef get_diagnosis(id):\n\tid = str(id)\n\tresponse = requests.get(\"{}/diagnoses?id={}\".format(ROOT_URL, id))\n\treturn response.json()[\"diagnosis\"]\n\ndef get_all_diagnoses():\n\tresponse = requests.get(\"{}/diagnoses\".format(ROOT_URL))\n\treturn response.json()[\"diagnoses\"]\n\ndef add_diagnosis(name, temperature, result, countryIds, symptomIds):\n\tbody = {\"name\": name, \"temperature\": temperature, \"result\": result, \"countryIds\": countryIds, \"symptomIds\": symptomIds}\n\tresponse = requests.post(\"{}/diagnoses\".format(ROOT_URL), data=body)\n\treturn response.json()\n\ndef delete_diagnosis(id):\n\tbody = {\"id\": id}\n\tresponse = requests.delete(\"{}/diagnoses\".format(ROOT_URL), data=body)\n\treturn response.json()\n\nif __name__ == '__main__':\n\tpass\n",
"step-ids": [
11,
12,
15,
17,
18
]
}
|
[
11,
12,
15,
17,
18
] |
import glob
import logging
import os
import sqlite3
from aiogram import Bot, Dispatcher, executor, types
TOKEN = '1772334389:AAE5wv8gssOFOgxQjQwKk7rUSKQHr6NTjus'
logging.basicConfig(level=logging.INFO)
bot = Bot(token=TOKEN)
dp = Dispatcher(bot)
path1 = 'C:\\Users\\const\\PycharmProjects\\t'
conn = sqlite3.connect('kustoge.db')
cur = conn.cursor()
chunksize = 10
idfolder = "C:\\Users\\const\\PycharmProjects\\goskustoge\\data\\id"
@dp.message_handler(commands=['start', 'help'])
async def send_welcome(message: types.Message):
await message.reply(
"Портал Государственных услуг округа Кустоже\n\n Используете команду /id + номер_паспорта \n для "
"получения информации о владельце.\n\n Так же можно использовать команду /fullname + имя + фамилия, "
"для получения информации о гражданине, регистр и порядок не важен\n\n Для получения информации о гражданах по "
"фамилии воспользуйтесь командой /lastname + Фамилия \n\n Для получения данных о гражданах по национальности "
"используйте /get_scan_nat+ брасогорец\отовичанин \n\n Для добавления гражданина "
"воспользуйтесь командой /add_person ИМЯ+ФАМИЛИЯ+НОМЕР_ПАСПОРТА+НАЦИОНАЛЬНОСТЬ+НОМЕР_ЛИЦЕНЗИИ_"
"ОРУЖЕЙНОЙ+Преступление ( если нет лицензии и преступления пишем НЕТ \n\n Для удаления гражданина "
"используйте /delete_person + номер паспорта \n\n Для добавления лицензии на оружение воспользуйтесь командой "
"/add_gun_lic+id+номер_лицензии \n\n "
"Для удалениея /delete_gun_lic + id \n\n Для добавления преступления гражданину используйте команду "
"/add_crime +id + преступление \n Для удаления преступления воспользуйтесь командой /delete_crime + id")
@dp.message_handler(commands=['id'])
async def echo(message: types.Message):
print("попросили данные по ID")
arguments = message.get_args()
print(arguments)
cur.execute("select * from barsa where id=:id", {"id": arguments})
res = cur.fetchone()
cur.execute("select count(*) from barsa where lastname=:lastname",
{"lastname": res[2]})
res2 = cur.fetchone()
print(res2)
result = 'Имя:' + ' ' + res[1] + '\n' + 'Фамилия:' + ' ' + res[2] + '\n' + 'Номер Паспорта:' + ' ' + \
res[3] + '\n' + 'Национальность:' + ' ' + res[4] + "\n" + "Родвественников:" + ' ' + str(
res2[0]) + '\n' + "Номер " \
"лицензии на " \
"оружие:" + " " + \
res[5] + '\n' + "Преступление:" + " " + res[6]
await bot.send_message(message.from_user.id, result)
os.chdir(idfolder)
for file in glob.glob(res[3] + ".jpg"):
img = open(file, "rb")
await bot.send_photo(message.from_user.id, img)
@dp.message_handler(commands=['fullname'])
async def echo(message: types.Message):
print("попросили данные по имени")
arguments = message.get_args()
print(arguments)
s = arguments.lower()
s = s.split()
cur.execute("select * from barsa where name=:name and lastname=:lastname or name=:lastname and lastname=:name",
{"name": s[0], "lastname": s[1]})
res = cur.fetchone()
cur.execute("select count(*) from barsa where lastname=:lastname",
{"lastname": s[1]})
res2 = cur.fetchone()
print(res2[0])
result = 'Имя:' + ' ' + res[1] + '\n' + 'Фамилия:' + ' ' + res[2] + '\n' + 'Номер Паспорта:' + ' ' + \
res[3] + '\n' + 'Национальность:' + ' ' + res[4] + "\n" + "Родвественников:" + ' ' + str(
res2[0]) + '\n' + "Номер " \
"лицензии на " \
"оружие:" + " " + \
res[5] + '\n' + \
"Преступление:" + " " + res[6]
await bot.send_message(message.from_user.id, result)
os.chdir(idfolder)
for file in glob.glob(res[3] + ".jpg"):
img = open(file, "rb")
await bot.send_photo(message.from_user.id, img)
@dp.message_handler(commands=['lastname'])
async def echo(message: types.Message):
arguments = message.get_args()
print("попросили данные по Фамилии:", arguments)
s = arguments.lower()
cur.execute("select * from barsa where lastname=:lastname ",
{"lastname": s})
res = cur.fetchall()
os.chdir(idfolder)
for f in res:
print(f)
cur.execute("select * from barsa where id=:id", {"id": f[3]})
res = cur.fetchone()
req = 'Имя:' + ' ' + res[1] + '\n' + 'Фамилия:' + ' ' + res[
2] + '\n' + 'Номер Паспорта:' + ' ' + res[3] + '\n' + 'Национальность:' + ' ' + res[
4] + '\n' + "Номер " \
"лицензии на " \
"оружие:" + " " + \
res[5] + '\n' + \
"Преступление:" + " " + res[6]
await bot.send_message(message.from_user.id, req)
for file in glob.glob(res[3] + ".jpg"):
img = open(file, "rb")
await bot.send_photo(message.from_user.id, img)
@dp.message_handler(commands=['get_scan_nat'])
async def echo(message: types.Message):
print("попросили ВСЕ СКАНЫ по по национальности")
arguments = message.get_args()
print(arguments)
s = arguments
s = s.capitalize()
cur.execute("select id from barsa where nat_=:nat_", {"nat_": s})
res = cur.fetchall()
out = [item for t in res for item in t]
out = [s.replace(" ", "") for s in out]
os.chdir(idfolder)
for f in out:
print(f)
if f == '472-641218' or f == '757-067985' or f == '642-741978' or f == '696-082959' or f == '442-446766' or f == '702-973965':
cur.execute("select * from barsa where id=:id", {"id": f})
res = cur.fetchone()
req = 'Имя:' + ' ' + res[1] + '\n' + 'Фамилия:' + ' ' + res[
2] + '\n' + 'Номер Паспорта:' + ' ' + res[3] + '\n' + 'Национальность:' + ' ' + res[
4] + '\n' + "Номер " \
"лицензии на " \
"оружие:" + " " + \
res[5] + '\n' + \
"Преступление:" + " " + res[6]
await bot.send_message(message.from_user.id, req)
else:
img = open(f + '.jpg', "rb")
print('ok')
await bot.send_photo(message.from_user.id, img)
@dp.message_handler(commands=['add_person'])
async def echo(message: types.Message):
arguments = message.get_args()
s = arguments.split()
print(s)
sqlite_insert_query = """INSERT INTO barsa
(name, lastname, id, nat_,gunlic,crime)
VALUES
(?,?,?,?,?,?)"""
data_tuple = (s[0], s[1], s[2], s[3], s[4], s[5])
cur.execute(sqlite_insert_query, data_tuple)
conn.commit()
print("Запись о гражданине успешно добавлена ")
cur.execute("select * from barsa where id=:id", {"id": s[2]})
res = cur.fetchone()
req = 'Имя:' + ' ' + res[1] + '\n' + 'Фамилия:' + ' ' + res[
2] + '\n' + 'Номер Паспорта:' + ' ' + res[3] + '\n' + 'Национальность:' + ' ' + res[4] + '\n' + "Номер " \
"лицензии на " \
"оружие:" + " " + \
res[5] + '\n' + \
"Преступление:" + " " + res[6]
await bot.send_message(message.from_user.id, req)
@dp.message_handler(commands=['delete_person'])
async def echo(message: types.Message):
arguments = message.get_args()
print("попросили удалить гражаднина с ID:", arguments)
s = arguments
cur.execute("delete from barsa where id=:id", {"id": s})
conn.commit()
print("Гражданин с ID :", arguments, 'удален')
res = "Гражданин с ID :", arguments, 'удален'
await bot.send_message(message.from_user.id, res)
@dp.message_handler(commands=['add_gun_lic'])
async def echo(message: types.Message):
arguments = message.get_args()
s = arguments.split()
print(s[0], s[1])
cur.execute(" update barsa set gunlic=:gunlic where id=:id", {"gunlic": s[1], "id": s[0]})
conn.commit()
print("Record Updated successfully ")
cur.execute("select * from barsa where id=:id", {"id": s[0]})
res = cur.fetchone()
print(res)
req = 'Имя:' + ' ' + res[1] + '\n' + 'Фамилия:' + ' ' + res[
2] + '\n' + 'Номер Паспорта:' + ' ' + res[3] + '\n' + 'Национальность:' + ' ' + res[4] + '\n' + "Номер " \
"лицензии на " \
"оружие:" + " " + \
res[5]
await bot.send_message(message.from_user.id, req)
@dp.message_handler(commands=['gun_lic'])
async def echo(message: types.Message):
arguments = message.get_args()
s = arguments
print(s)
cur.execute("select * from barsa where gunlic=:gunlic", {"gunlic": s})
res = cur.fetchone()
print(res)
req = 'Имя:' + ' ' + res[1] + '\n' + 'Фамилия:' + ' ' + res[
2] + '\n' + 'Номер Паспорта:' + ' ' + res[3] + '\n' + 'Национальность:' + ' ' + res[4] + '\n' + "Номер " \
"лицензии на " \
"оружие:" + " " + \
res[5] + '\n' + \
"Преступление:" + " " + res[6]
await bot.send_message(message.from_user.id, req)
@dp.message_handler(commands=['delete_gun_lic'])
async def echo(message: types.Message):
arguments = message.get_args()
s = arguments
print(s)
no = 'нет'
cur.execute("update barsa set gunlic=:gunlic1 where id=:id", {"gunlic1": no, "id": s})
res1 = cur.fetchone()
conn.commit()
ans = "Оружейная лицения гражданина:",s, " удалена"
await bot.send_message(message.from_user.id, ans)
@dp.message_handler(commands=['add_crime'])
async def echo(message: types.Message):
arguments = message.get_args()
s = arguments.split()
print(s[0], s[1])
cur.execute(" update barsa set crime=:crime where id=:id", {"crime": s[1], "id": s[0]})
conn.commit()
print("Record Updated successfully ")
cur.execute("select * from barsa where id=:id", {"id": s[0]})
res = cur.fetchone()
print(res)
req = 'Имя:' + ' ' + res[1] + '\n' + 'Фамилия:' + ' ' + res[
2] + '\n' + 'Номер Паспорта:' + ' ' + res[3] + '\n' + 'Национальность:' + ' ' + res[4] + '\n' + "Номер " \
"лицензии на " \
"оружие:" + " " + \
res[5] + '\n' + \
"Преступление:" + " " + res[6]
await bot.send_message(message.from_user.id, req)
@dp.message_handler(commands=['delete_crime'])
async def echo(message: types.Message):
arguments = message.get_args()
s = arguments
print(s)
no = 'нет'
cur.execute("update barsa set crime=:crime where id=:id", {"crime": no, "id": s})
res1 = cur.fetchone()
conn.commit()
ans = "Преступление гражданина:",s, " удалено"
await bot.send_message(message.from_user.id, ans)
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=False)
|
normal
|
{
"blob_id": "4193fa992d06890afb660c072842cf1b85a43774",
"index": 3207,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nlogging.basicConfig(level=logging.INFO)\n<mask token>\n\n\n@dp.message_handler(commands=['start', 'help'])\nasync def send_welcome(message: types.Message):\n await message.reply(\n \"\"\"Портал Государственных услуг округа Кустоже\n\n Используете команду /id + номер_паспорта \n для получения информации о владельце.\n\n Так же можно использовать команду /fullname + имя + фамилия, для получения информации о гражданине, регистр и порядок не важен\n\n Для получения информации о гражданах по фамилии воспользуйтесь командой /lastname + Фамилия \n\n Для получения данных о гражданах по национальности используйте /get_scan_nat+ брасогорец\\\\отовичанин \n\n Для добавления гражданина воспользуйтесь командой /add_person ИМЯ+ФАМИЛИЯ+НОМЕР_ПАСПОРТА+НАЦИОНАЛЬНОСТЬ+НОМЕР_ЛИЦЕНЗИИ_ОРУЖЕЙНОЙ+Преступление ( если нет лицензии и преступления пишем НЕТ \n\n Для удаления гражданина используйте /delete_person + номер паспорта \n\n Для добавления лицензии на оружение воспользуйтесь командой /add_gun_lic+id+номер_лицензии \n\n Для удалениея /delete_gun_lic + id \n\n Для добавления преступления гражданину используйте команду /add_crime +id + преступление \n Для удаления преступления воспользуйтесь командой /delete_crime + id\"\"\"\n )\n\n\n@dp.message_handler(commands=['id'])\nasync def echo(message: types.Message):\n print('попросили данные по ID')\n arguments = message.get_args()\n print(arguments)\n cur.execute('select * from barsa where id=:id', {'id': arguments})\n res = cur.fetchone()\n cur.execute('select count(*) from barsa where lastname=:lastname', {\n 'lastname': res[2]})\n res2 = cur.fetchone()\n print(res2)\n result = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[2\n ] + '\\n' + 'Номер Паспорта:' + ' ' + res[3\n ] + '\\n' + 'Национальность:' + ' ' + res[4\n ] + '\\n' + 'Родвественников:' + ' ' + str(res2[0]\n ) + '\\n' + 'Номер лицензии на оружие:' + ' ' + res[5\n ] + '\\n' + 'Преступление:' + ' ' + res[6]\n await bot.send_message(message.from_user.id, result)\n os.chdir(idfolder)\n for file in glob.glob(res[3] + '.jpg'):\n img = open(file, 'rb')\n await bot.send_photo(message.from_user.id, img)\n\n\n@dp.message_handler(commands=['fullname'])\nasync def echo(message: types.Message):\n print('попросили данные по имени')\n arguments = message.get_args()\n print(arguments)\n s = arguments.lower()\n s = s.split()\n cur.execute(\n 'select * from barsa where name=:name and lastname=:lastname or name=:lastname and lastname=:name'\n , {'name': s[0], 'lastname': s[1]})\n res = cur.fetchone()\n cur.execute('select count(*) from barsa where lastname=:lastname', {\n 'lastname': s[1]})\n res2 = cur.fetchone()\n print(res2[0])\n result = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[2\n ] + '\\n' + 'Номер Паспорта:' + ' ' + res[3\n ] + '\\n' + 'Национальность:' + ' ' + res[4\n ] + '\\n' + 'Родвественников:' + ' ' + str(res2[0]\n ) + '\\n' + 'Номер лицензии на оружие:' + ' ' + res[5\n ] + '\\n' + 'Преступление:' + ' ' + res[6]\n await bot.send_message(message.from_user.id, result)\n os.chdir(idfolder)\n for file in glob.glob(res[3] + '.jpg'):\n img = open(file, 'rb')\n await bot.send_photo(message.from_user.id, img)\n\n\n@dp.message_handler(commands=['lastname'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n print('попросили данные по Фамилии:', arguments)\n s = arguments.lower()\n cur.execute('select * from barsa where lastname=:lastname ', {\n 'lastname': s})\n res = cur.fetchall()\n os.chdir(idfolder)\n for f in res:\n print(f)\n cur.execute('select * from barsa where id=:id', {'id': f[3]})\n res = cur.fetchone()\n req = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[2\n ] + '\\n' + 'Номер Паспорта:' + ' ' + res[3\n ] + '\\n' + 'Национальность:' + ' ' + res[4\n ] + '\\n' + 'Номер лицензии на оружие:' + ' ' + res[5\n ] + '\\n' + 'Преступление:' + ' ' + res[6]\n await bot.send_message(message.from_user.id, req)\n for file in glob.glob(res[3] + '.jpg'):\n img = open(file, 'rb')\n await bot.send_photo(message.from_user.id, img)\n\n\n@dp.message_handler(commands=['get_scan_nat'])\nasync def echo(message: types.Message):\n print('попросили ВСЕ СКАНЫ по по национальности')\n arguments = message.get_args()\n print(arguments)\n s = arguments\n s = s.capitalize()\n cur.execute('select id from barsa where nat_=:nat_', {'nat_': s})\n res = cur.fetchall()\n out = [item for t in res for item in t]\n out = [s.replace(' ', '') for s in out]\n os.chdir(idfolder)\n for f in out:\n print(f)\n if (f == '472-641218' or f == '757-067985' or f == '642-741978' or \n f == '696-082959' or f == '442-446766' or f == '702-973965'):\n cur.execute('select * from barsa where id=:id', {'id': f})\n res = cur.fetchone()\n req = 'Имя:' + ' ' + res[1\n ] + '\\n' + 'Фамилия:' + ' ' + res[2\n ] + '\\n' + 'Номер Паспорта:' + ' ' + res[3\n ] + '\\n' + 'Национальность:' + ' ' + res[4\n ] + '\\n' + 'Номер лицензии на оружие:' + ' ' + res[5\n ] + '\\n' + 'Преступление:' + ' ' + res[6]\n await bot.send_message(message.from_user.id, req)\n else:\n img = open(f + '.jpg', 'rb')\n print('ok')\n await bot.send_photo(message.from_user.id, img)\n\n\n@dp.message_handler(commands=['add_person'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n s = arguments.split()\n print(s)\n sqlite_insert_query = \"\"\"INSERT INTO barsa\n (name, lastname, id, nat_,gunlic,crime)\n VALUES\n (?,?,?,?,?,?)\"\"\"\n data_tuple = s[0], s[1], s[2], s[3], s[4], s[5]\n cur.execute(sqlite_insert_query, data_tuple)\n conn.commit()\n print('Запись о гражданине успешно добавлена ')\n cur.execute('select * from barsa where id=:id', {'id': s[2]})\n res = cur.fetchone()\n req = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[2\n ] + '\\n' + 'Номер Паспорта:' + ' ' + res[3\n ] + '\\n' + 'Национальность:' + ' ' + res[4\n ] + '\\n' + 'Номер лицензии на оружие:' + ' ' + res[5\n ] + '\\n' + 'Преступление:' + ' ' + res[6]\n await bot.send_message(message.from_user.id, req)\n\n\n@dp.message_handler(commands=['delete_person'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n print('попросили удалить гражаднина с ID:', arguments)\n s = arguments\n cur.execute('delete from barsa where id=:id', {'id': s})\n conn.commit()\n print('Гражданин с ID :', arguments, 'удален')\n res = 'Гражданин с ID :', arguments, 'удален'\n await bot.send_message(message.from_user.id, res)\n\n\n@dp.message_handler(commands=['add_gun_lic'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n s = arguments.split()\n print(s[0], s[1])\n cur.execute(' update barsa set gunlic=:gunlic where id=:id', {'gunlic':\n s[1], 'id': s[0]})\n conn.commit()\n print('Record Updated successfully ')\n cur.execute('select * from barsa where id=:id', {'id': s[0]})\n res = cur.fetchone()\n print(res)\n req = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[2\n ] + '\\n' + 'Номер Паспорта:' + ' ' + res[3\n ] + '\\n' + 'Национальность:' + ' ' + res[4\n ] + '\\n' + 'Номер лицензии на оружие:' + ' ' + res[5]\n await bot.send_message(message.from_user.id, req)\n\n\n@dp.message_handler(commands=['gun_lic'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n s = arguments\n print(s)\n cur.execute('select * from barsa where gunlic=:gunlic', {'gunlic': s})\n res = cur.fetchone()\n print(res)\n req = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[2\n ] + '\\n' + 'Номер Паспорта:' + ' ' + res[3\n ] + '\\n' + 'Национальность:' + ' ' + res[4\n ] + '\\n' + 'Номер лицензии на оружие:' + ' ' + res[5\n ] + '\\n' + 'Преступление:' + ' ' + res[6]\n await bot.send_message(message.from_user.id, req)\n\n\n@dp.message_handler(commands=['delete_gun_lic'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n s = arguments\n print(s)\n no = 'нет'\n cur.execute('update barsa set gunlic=:gunlic1 where id=:id', {'gunlic1':\n no, 'id': s})\n res1 = cur.fetchone()\n conn.commit()\n ans = 'Оружейная лицения гражданина:', s, ' удалена'\n await bot.send_message(message.from_user.id, ans)\n\n\n@dp.message_handler(commands=['add_crime'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n s = arguments.split()\n print(s[0], s[1])\n cur.execute(' update barsa set crime=:crime where id=:id', {'crime': s[\n 1], 'id': s[0]})\n conn.commit()\n print('Record Updated successfully ')\n cur.execute('select * from barsa where id=:id', {'id': s[0]})\n res = cur.fetchone()\n print(res)\n req = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[2\n ] + '\\n' + 'Номер Паспорта:' + ' ' + res[3\n ] + '\\n' + 'Национальность:' + ' ' + res[4\n ] + '\\n' + 'Номер лицензии на оружие:' + ' ' + res[5\n ] + '\\n' + 'Преступление:' + ' ' + res[6]\n await bot.send_message(message.from_user.id, req)\n\n\n@dp.message_handler(commands=['delete_crime'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n s = arguments\n print(s)\n no = 'нет'\n cur.execute('update barsa set crime=:crime where id=:id', {'crime': no,\n 'id': s})\n res1 = cur.fetchone()\n conn.commit()\n ans = 'Преступление гражданина:', s, ' удалено'\n await bot.send_message(message.from_user.id, ans)\n\n\nif __name__ == '__main__':\n executor.start_polling(dp, skip_updates=False)\n",
"step-3": "<mask token>\nTOKEN = '1772334389:AAE5wv8gssOFOgxQjQwKk7rUSKQHr6NTjus'\nlogging.basicConfig(level=logging.INFO)\nbot = Bot(token=TOKEN)\ndp = Dispatcher(bot)\npath1 = 'C:\\\\Users\\\\const\\\\PycharmProjects\\\\t'\nconn = sqlite3.connect('kustoge.db')\ncur = conn.cursor()\nchunksize = 10\nidfolder = 'C:\\\\Users\\\\const\\\\PycharmProjects\\\\goskustoge\\\\data\\\\id'\n\n\n@dp.message_handler(commands=['start', 'help'])\nasync def send_welcome(message: types.Message):\n await message.reply(\n \"\"\"Портал Государственных услуг округа Кустоже\n\n Используете команду /id + номер_паспорта \n для получения информации о владельце.\n\n Так же можно использовать команду /fullname + имя + фамилия, для получения информации о гражданине, регистр и порядок не важен\n\n Для получения информации о гражданах по фамилии воспользуйтесь командой /lastname + Фамилия \n\n Для получения данных о гражданах по национальности используйте /get_scan_nat+ брасогорец\\\\отовичанин \n\n Для добавления гражданина воспользуйтесь командой /add_person ИМЯ+ФАМИЛИЯ+НОМЕР_ПАСПОРТА+НАЦИОНАЛЬНОСТЬ+НОМЕР_ЛИЦЕНЗИИ_ОРУЖЕЙНОЙ+Преступление ( если нет лицензии и преступления пишем НЕТ \n\n Для удаления гражданина используйте /delete_person + номер паспорта \n\n Для добавления лицензии на оружение воспользуйтесь командой /add_gun_lic+id+номер_лицензии \n\n Для удалениея /delete_gun_lic + id \n\n Для добавления преступления гражданину используйте команду /add_crime +id + преступление \n Для удаления преступления воспользуйтесь командой /delete_crime + id\"\"\"\n )\n\n\n@dp.message_handler(commands=['id'])\nasync def echo(message: types.Message):\n print('попросили данные по ID')\n arguments = message.get_args()\n print(arguments)\n cur.execute('select * from barsa where id=:id', {'id': arguments})\n res = cur.fetchone()\n cur.execute('select count(*) from barsa where lastname=:lastname', {\n 'lastname': res[2]})\n res2 = cur.fetchone()\n print(res2)\n result = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[2\n ] + '\\n' + 'Номер Паспорта:' + ' ' + res[3\n ] + '\\n' + 'Национальность:' + ' ' + res[4\n ] + '\\n' + 'Родвественников:' + ' ' + str(res2[0]\n ) + '\\n' + 'Номер лицензии на оружие:' + ' ' + res[5\n ] + '\\n' + 'Преступление:' + ' ' + res[6]\n await bot.send_message(message.from_user.id, result)\n os.chdir(idfolder)\n for file in glob.glob(res[3] + '.jpg'):\n img = open(file, 'rb')\n await bot.send_photo(message.from_user.id, img)\n\n\n@dp.message_handler(commands=['fullname'])\nasync def echo(message: types.Message):\n print('попросили данные по имени')\n arguments = message.get_args()\n print(arguments)\n s = arguments.lower()\n s = s.split()\n cur.execute(\n 'select * from barsa where name=:name and lastname=:lastname or name=:lastname and lastname=:name'\n , {'name': s[0], 'lastname': s[1]})\n res = cur.fetchone()\n cur.execute('select count(*) from barsa where lastname=:lastname', {\n 'lastname': s[1]})\n res2 = cur.fetchone()\n print(res2[0])\n result = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[2\n ] + '\\n' + 'Номер Паспорта:' + ' ' + res[3\n ] + '\\n' + 'Национальность:' + ' ' + res[4\n ] + '\\n' + 'Родвественников:' + ' ' + str(res2[0]\n ) + '\\n' + 'Номер лицензии на оружие:' + ' ' + res[5\n ] + '\\n' + 'Преступление:' + ' ' + res[6]\n await bot.send_message(message.from_user.id, result)\n os.chdir(idfolder)\n for file in glob.glob(res[3] + '.jpg'):\n img = open(file, 'rb')\n await bot.send_photo(message.from_user.id, img)\n\n\n@dp.message_handler(commands=['lastname'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n print('попросили данные по Фамилии:', arguments)\n s = arguments.lower()\n cur.execute('select * from barsa where lastname=:lastname ', {\n 'lastname': s})\n res = cur.fetchall()\n os.chdir(idfolder)\n for f in res:\n print(f)\n cur.execute('select * from barsa where id=:id', {'id': f[3]})\n res = cur.fetchone()\n req = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[2\n ] + '\\n' + 'Номер Паспорта:' + ' ' + res[3\n ] + '\\n' + 'Национальность:' + ' ' + res[4\n ] + '\\n' + 'Номер лицензии на оружие:' + ' ' + res[5\n ] + '\\n' + 'Преступление:' + ' ' + res[6]\n await bot.send_message(message.from_user.id, req)\n for file in glob.glob(res[3] + '.jpg'):\n img = open(file, 'rb')\n await bot.send_photo(message.from_user.id, img)\n\n\n@dp.message_handler(commands=['get_scan_nat'])\nasync def echo(message: types.Message):\n print('попросили ВСЕ СКАНЫ по по национальности')\n arguments = message.get_args()\n print(arguments)\n s = arguments\n s = s.capitalize()\n cur.execute('select id from barsa where nat_=:nat_', {'nat_': s})\n res = cur.fetchall()\n out = [item for t in res for item in t]\n out = [s.replace(' ', '') for s in out]\n os.chdir(idfolder)\n for f in out:\n print(f)\n if (f == '472-641218' or f == '757-067985' or f == '642-741978' or \n f == '696-082959' or f == '442-446766' or f == '702-973965'):\n cur.execute('select * from barsa where id=:id', {'id': f})\n res = cur.fetchone()\n req = 'Имя:' + ' ' + res[1\n ] + '\\n' + 'Фамилия:' + ' ' + res[2\n ] + '\\n' + 'Номер Паспорта:' + ' ' + res[3\n ] + '\\n' + 'Национальность:' + ' ' + res[4\n ] + '\\n' + 'Номер лицензии на оружие:' + ' ' + res[5\n ] + '\\n' + 'Преступление:' + ' ' + res[6]\n await bot.send_message(message.from_user.id, req)\n else:\n img = open(f + '.jpg', 'rb')\n print('ok')\n await bot.send_photo(message.from_user.id, img)\n\n\n@dp.message_handler(commands=['add_person'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n s = arguments.split()\n print(s)\n sqlite_insert_query = \"\"\"INSERT INTO barsa\n (name, lastname, id, nat_,gunlic,crime)\n VALUES\n (?,?,?,?,?,?)\"\"\"\n data_tuple = s[0], s[1], s[2], s[3], s[4], s[5]\n cur.execute(sqlite_insert_query, data_tuple)\n conn.commit()\n print('Запись о гражданине успешно добавлена ')\n cur.execute('select * from barsa where id=:id', {'id': s[2]})\n res = cur.fetchone()\n req = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[2\n ] + '\\n' + 'Номер Паспорта:' + ' ' + res[3\n ] + '\\n' + 'Национальность:' + ' ' + res[4\n ] + '\\n' + 'Номер лицензии на оружие:' + ' ' + res[5\n ] + '\\n' + 'Преступление:' + ' ' + res[6]\n await bot.send_message(message.from_user.id, req)\n\n\n@dp.message_handler(commands=['delete_person'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n print('попросили удалить гражаднина с ID:', arguments)\n s = arguments\n cur.execute('delete from barsa where id=:id', {'id': s})\n conn.commit()\n print('Гражданин с ID :', arguments, 'удален')\n res = 'Гражданин с ID :', arguments, 'удален'\n await bot.send_message(message.from_user.id, res)\n\n\n@dp.message_handler(commands=['add_gun_lic'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n s = arguments.split()\n print(s[0], s[1])\n cur.execute(' update barsa set gunlic=:gunlic where id=:id', {'gunlic':\n s[1], 'id': s[0]})\n conn.commit()\n print('Record Updated successfully ')\n cur.execute('select * from barsa where id=:id', {'id': s[0]})\n res = cur.fetchone()\n print(res)\n req = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[2\n ] + '\\n' + 'Номер Паспорта:' + ' ' + res[3\n ] + '\\n' + 'Национальность:' + ' ' + res[4\n ] + '\\n' + 'Номер лицензии на оружие:' + ' ' + res[5]\n await bot.send_message(message.from_user.id, req)\n\n\n@dp.message_handler(commands=['gun_lic'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n s = arguments\n print(s)\n cur.execute('select * from barsa where gunlic=:gunlic', {'gunlic': s})\n res = cur.fetchone()\n print(res)\n req = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[2\n ] + '\\n' + 'Номер Паспорта:' + ' ' + res[3\n ] + '\\n' + 'Национальность:' + ' ' + res[4\n ] + '\\n' + 'Номер лицензии на оружие:' + ' ' + res[5\n ] + '\\n' + 'Преступление:' + ' ' + res[6]\n await bot.send_message(message.from_user.id, req)\n\n\n@dp.message_handler(commands=['delete_gun_lic'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n s = arguments\n print(s)\n no = 'нет'\n cur.execute('update barsa set gunlic=:gunlic1 where id=:id', {'gunlic1':\n no, 'id': s})\n res1 = cur.fetchone()\n conn.commit()\n ans = 'Оружейная лицения гражданина:', s, ' удалена'\n await bot.send_message(message.from_user.id, ans)\n\n\n@dp.message_handler(commands=['add_crime'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n s = arguments.split()\n print(s[0], s[1])\n cur.execute(' update barsa set crime=:crime where id=:id', {'crime': s[\n 1], 'id': s[0]})\n conn.commit()\n print('Record Updated successfully ')\n cur.execute('select * from barsa where id=:id', {'id': s[0]})\n res = cur.fetchone()\n print(res)\n req = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[2\n ] + '\\n' + 'Номер Паспорта:' + ' ' + res[3\n ] + '\\n' + 'Национальность:' + ' ' + res[4\n ] + '\\n' + 'Номер лицензии на оружие:' + ' ' + res[5\n ] + '\\n' + 'Преступление:' + ' ' + res[6]\n await bot.send_message(message.from_user.id, req)\n\n\n@dp.message_handler(commands=['delete_crime'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n s = arguments\n print(s)\n no = 'нет'\n cur.execute('update barsa set crime=:crime where id=:id', {'crime': no,\n 'id': s})\n res1 = cur.fetchone()\n conn.commit()\n ans = 'Преступление гражданина:', s, ' удалено'\n await bot.send_message(message.from_user.id, ans)\n\n\nif __name__ == '__main__':\n executor.start_polling(dp, skip_updates=False)\n",
"step-4": "import glob\nimport logging\nimport os\nimport sqlite3\nfrom aiogram import Bot, Dispatcher, executor, types\nTOKEN = '1772334389:AAE5wv8gssOFOgxQjQwKk7rUSKQHr6NTjus'\nlogging.basicConfig(level=logging.INFO)\nbot = Bot(token=TOKEN)\ndp = Dispatcher(bot)\npath1 = 'C:\\\\Users\\\\const\\\\PycharmProjects\\\\t'\nconn = sqlite3.connect('kustoge.db')\ncur = conn.cursor()\nchunksize = 10\nidfolder = 'C:\\\\Users\\\\const\\\\PycharmProjects\\\\goskustoge\\\\data\\\\id'\n\n\n@dp.message_handler(commands=['start', 'help'])\nasync def send_welcome(message: types.Message):\n await message.reply(\n \"\"\"Портал Государственных услуг округа Кустоже\n\n Используете команду /id + номер_паспорта \n для получения информации о владельце.\n\n Так же можно использовать команду /fullname + имя + фамилия, для получения информации о гражданине, регистр и порядок не важен\n\n Для получения информации о гражданах по фамилии воспользуйтесь командой /lastname + Фамилия \n\n Для получения данных о гражданах по национальности используйте /get_scan_nat+ брасогорец\\\\отовичанин \n\n Для добавления гражданина воспользуйтесь командой /add_person ИМЯ+ФАМИЛИЯ+НОМЕР_ПАСПОРТА+НАЦИОНАЛЬНОСТЬ+НОМЕР_ЛИЦЕНЗИИ_ОРУЖЕЙНОЙ+Преступление ( если нет лицензии и преступления пишем НЕТ \n\n Для удаления гражданина используйте /delete_person + номер паспорта \n\n Для добавления лицензии на оружение воспользуйтесь командой /add_gun_lic+id+номер_лицензии \n\n Для удалениея /delete_gun_lic + id \n\n Для добавления преступления гражданину используйте команду /add_crime +id + преступление \n Для удаления преступления воспользуйтесь командой /delete_crime + id\"\"\"\n )\n\n\n@dp.message_handler(commands=['id'])\nasync def echo(message: types.Message):\n print('попросили данные по ID')\n arguments = message.get_args()\n print(arguments)\n cur.execute('select * from barsa where id=:id', {'id': arguments})\n res = cur.fetchone()\n cur.execute('select count(*) from barsa where lastname=:lastname', {\n 'lastname': res[2]})\n res2 = cur.fetchone()\n print(res2)\n result = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[2\n ] + '\\n' + 'Номер Паспорта:' + ' ' + res[3\n ] + '\\n' + 'Национальность:' + ' ' + res[4\n ] + '\\n' + 'Родвественников:' + ' ' + str(res2[0]\n ) + '\\n' + 'Номер лицензии на оружие:' + ' ' + res[5\n ] + '\\n' + 'Преступление:' + ' ' + res[6]\n await bot.send_message(message.from_user.id, result)\n os.chdir(idfolder)\n for file in glob.glob(res[3] + '.jpg'):\n img = open(file, 'rb')\n await bot.send_photo(message.from_user.id, img)\n\n\n@dp.message_handler(commands=['fullname'])\nasync def echo(message: types.Message):\n print('попросили данные по имени')\n arguments = message.get_args()\n print(arguments)\n s = arguments.lower()\n s = s.split()\n cur.execute(\n 'select * from barsa where name=:name and lastname=:lastname or name=:lastname and lastname=:name'\n , {'name': s[0], 'lastname': s[1]})\n res = cur.fetchone()\n cur.execute('select count(*) from barsa where lastname=:lastname', {\n 'lastname': s[1]})\n res2 = cur.fetchone()\n print(res2[0])\n result = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[2\n ] + '\\n' + 'Номер Паспорта:' + ' ' + res[3\n ] + '\\n' + 'Национальность:' + ' ' + res[4\n ] + '\\n' + 'Родвественников:' + ' ' + str(res2[0]\n ) + '\\n' + 'Номер лицензии на оружие:' + ' ' + res[5\n ] + '\\n' + 'Преступление:' + ' ' + res[6]\n await bot.send_message(message.from_user.id, result)\n os.chdir(idfolder)\n for file in glob.glob(res[3] + '.jpg'):\n img = open(file, 'rb')\n await bot.send_photo(message.from_user.id, img)\n\n\n@dp.message_handler(commands=['lastname'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n print('попросили данные по Фамилии:', arguments)\n s = arguments.lower()\n cur.execute('select * from barsa where lastname=:lastname ', {\n 'lastname': s})\n res = cur.fetchall()\n os.chdir(idfolder)\n for f in res:\n print(f)\n cur.execute('select * from barsa where id=:id', {'id': f[3]})\n res = cur.fetchone()\n req = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[2\n ] + '\\n' + 'Номер Паспорта:' + ' ' + res[3\n ] + '\\n' + 'Национальность:' + ' ' + res[4\n ] + '\\n' + 'Номер лицензии на оружие:' + ' ' + res[5\n ] + '\\n' + 'Преступление:' + ' ' + res[6]\n await bot.send_message(message.from_user.id, req)\n for file in glob.glob(res[3] + '.jpg'):\n img = open(file, 'rb')\n await bot.send_photo(message.from_user.id, img)\n\n\n@dp.message_handler(commands=['get_scan_nat'])\nasync def echo(message: types.Message):\n print('попросили ВСЕ СКАНЫ по по национальности')\n arguments = message.get_args()\n print(arguments)\n s = arguments\n s = s.capitalize()\n cur.execute('select id from barsa where nat_=:nat_', {'nat_': s})\n res = cur.fetchall()\n out = [item for t in res for item in t]\n out = [s.replace(' ', '') for s in out]\n os.chdir(idfolder)\n for f in out:\n print(f)\n if (f == '472-641218' or f == '757-067985' or f == '642-741978' or \n f == '696-082959' or f == '442-446766' or f == '702-973965'):\n cur.execute('select * from barsa where id=:id', {'id': f})\n res = cur.fetchone()\n req = 'Имя:' + ' ' + res[1\n ] + '\\n' + 'Фамилия:' + ' ' + res[2\n ] + '\\n' + 'Номер Паспорта:' + ' ' + res[3\n ] + '\\n' + 'Национальность:' + ' ' + res[4\n ] + '\\n' + 'Номер лицензии на оружие:' + ' ' + res[5\n ] + '\\n' + 'Преступление:' + ' ' + res[6]\n await bot.send_message(message.from_user.id, req)\n else:\n img = open(f + '.jpg', 'rb')\n print('ok')\n await bot.send_photo(message.from_user.id, img)\n\n\n@dp.message_handler(commands=['add_person'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n s = arguments.split()\n print(s)\n sqlite_insert_query = \"\"\"INSERT INTO barsa\n (name, lastname, id, nat_,gunlic,crime)\n VALUES\n (?,?,?,?,?,?)\"\"\"\n data_tuple = s[0], s[1], s[2], s[3], s[4], s[5]\n cur.execute(sqlite_insert_query, data_tuple)\n conn.commit()\n print('Запись о гражданине успешно добавлена ')\n cur.execute('select * from barsa where id=:id', {'id': s[2]})\n res = cur.fetchone()\n req = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[2\n ] + '\\n' + 'Номер Паспорта:' + ' ' + res[3\n ] + '\\n' + 'Национальность:' + ' ' + res[4\n ] + '\\n' + 'Номер лицензии на оружие:' + ' ' + res[5\n ] + '\\n' + 'Преступление:' + ' ' + res[6]\n await bot.send_message(message.from_user.id, req)\n\n\n@dp.message_handler(commands=['delete_person'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n print('попросили удалить гражаднина с ID:', arguments)\n s = arguments\n cur.execute('delete from barsa where id=:id', {'id': s})\n conn.commit()\n print('Гражданин с ID :', arguments, 'удален')\n res = 'Гражданин с ID :', arguments, 'удален'\n await bot.send_message(message.from_user.id, res)\n\n\n@dp.message_handler(commands=['add_gun_lic'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n s = arguments.split()\n print(s[0], s[1])\n cur.execute(' update barsa set gunlic=:gunlic where id=:id', {'gunlic':\n s[1], 'id': s[0]})\n conn.commit()\n print('Record Updated successfully ')\n cur.execute('select * from barsa where id=:id', {'id': s[0]})\n res = cur.fetchone()\n print(res)\n req = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[2\n ] + '\\n' + 'Номер Паспорта:' + ' ' + res[3\n ] + '\\n' + 'Национальность:' + ' ' + res[4\n ] + '\\n' + 'Номер лицензии на оружие:' + ' ' + res[5]\n await bot.send_message(message.from_user.id, req)\n\n\n@dp.message_handler(commands=['gun_lic'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n s = arguments\n print(s)\n cur.execute('select * from barsa where gunlic=:gunlic', {'gunlic': s})\n res = cur.fetchone()\n print(res)\n req = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[2\n ] + '\\n' + 'Номер Паспорта:' + ' ' + res[3\n ] + '\\n' + 'Национальность:' + ' ' + res[4\n ] + '\\n' + 'Номер лицензии на оружие:' + ' ' + res[5\n ] + '\\n' + 'Преступление:' + ' ' + res[6]\n await bot.send_message(message.from_user.id, req)\n\n\n@dp.message_handler(commands=['delete_gun_lic'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n s = arguments\n print(s)\n no = 'нет'\n cur.execute('update barsa set gunlic=:gunlic1 where id=:id', {'gunlic1':\n no, 'id': s})\n res1 = cur.fetchone()\n conn.commit()\n ans = 'Оружейная лицения гражданина:', s, ' удалена'\n await bot.send_message(message.from_user.id, ans)\n\n\n@dp.message_handler(commands=['add_crime'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n s = arguments.split()\n print(s[0], s[1])\n cur.execute(' update barsa set crime=:crime where id=:id', {'crime': s[\n 1], 'id': s[0]})\n conn.commit()\n print('Record Updated successfully ')\n cur.execute('select * from barsa where id=:id', {'id': s[0]})\n res = cur.fetchone()\n print(res)\n req = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[2\n ] + '\\n' + 'Номер Паспорта:' + ' ' + res[3\n ] + '\\n' + 'Национальность:' + ' ' + res[4\n ] + '\\n' + 'Номер лицензии на оружие:' + ' ' + res[5\n ] + '\\n' + 'Преступление:' + ' ' + res[6]\n await bot.send_message(message.from_user.id, req)\n\n\n@dp.message_handler(commands=['delete_crime'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n s = arguments\n print(s)\n no = 'нет'\n cur.execute('update barsa set crime=:crime where id=:id', {'crime': no,\n 'id': s})\n res1 = cur.fetchone()\n conn.commit()\n ans = 'Преступление гражданина:', s, ' удалено'\n await bot.send_message(message.from_user.id, ans)\n\n\nif __name__ == '__main__':\n executor.start_polling(dp, skip_updates=False)\n",
"step-5": "import glob\nimport logging\nimport os\nimport sqlite3\n\nfrom aiogram import Bot, Dispatcher, executor, types\n\nTOKEN = '1772334389:AAE5wv8gssOFOgxQjQwKk7rUSKQHr6NTjus'\nlogging.basicConfig(level=logging.INFO)\nbot = Bot(token=TOKEN)\ndp = Dispatcher(bot)\npath1 = 'C:\\\\Users\\\\const\\\\PycharmProjects\\\\t'\n\nconn = sqlite3.connect('kustoge.db')\ncur = conn.cursor()\nchunksize = 10\n\nidfolder = \"C:\\\\Users\\\\const\\\\PycharmProjects\\\\goskustoge\\\\data\\\\id\"\n\n\n@dp.message_handler(commands=['start', 'help'])\nasync def send_welcome(message: types.Message):\n await message.reply(\n \"Портал Государственных услуг округа Кустоже\\n\\n Используете команду /id + номер_паспорта \\n для \"\n \"получения информации о владельце.\\n\\n Так же можно использовать команду /fullname + имя + фамилия, \"\n \"для получения информации о гражданине, регистр и порядок не важен\\n\\n Для получения информации о гражданах по \"\n \"фамилии воспользуйтесь командой /lastname + Фамилия \\n\\n Для получения данных о гражданах по национальности \"\n \"используйте /get_scan_nat+ брасогорец\\отовичанин \\n\\n Для добавления гражданина \"\n \"воспользуйтесь командой /add_person ИМЯ+ФАМИЛИЯ+НОМЕР_ПАСПОРТА+НАЦИОНАЛЬНОСТЬ+НОМЕР_ЛИЦЕНЗИИ_\"\n \"ОРУЖЕЙНОЙ+Преступление ( если нет лицензии и преступления пишем НЕТ \\n\\n Для удаления гражданина \"\n \"используйте /delete_person + номер паспорта \\n\\n Для добавления лицензии на оружение воспользуйтесь командой \"\n \"/add_gun_lic+id+номер_лицензии \\n\\n \"\n \"Для удалениея /delete_gun_lic + id \\n\\n Для добавления преступления гражданину используйте команду \"\n \"/add_crime +id + преступление \\n Для удаления преступления воспользуйтесь командой /delete_crime + id\")\n\n\n@dp.message_handler(commands=['id'])\nasync def echo(message: types.Message):\n print(\"попросили данные по ID\")\n arguments = message.get_args()\n print(arguments)\n cur.execute(\"select * from barsa where id=:id\", {\"id\": arguments})\n res = cur.fetchone()\n cur.execute(\"select count(*) from barsa where lastname=:lastname\",\n {\"lastname\": res[2]})\n res2 = cur.fetchone()\n print(res2)\n result = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[2] + '\\n' + 'Номер Паспорта:' + ' ' + \\\n res[3] + '\\n' + 'Национальность:' + ' ' + res[4] + \"\\n\" + \"Родвественников:\" + ' ' + str(\n res2[0]) + '\\n' + \"Номер \" \\\n \"лицензии на \" \\\n \"оружие:\" + \" \" + \\\n res[5] + '\\n' + \"Преступление:\" + \" \" + res[6]\n await bot.send_message(message.from_user.id, result)\n os.chdir(idfolder)\n for file in glob.glob(res[3] + \".jpg\"):\n img = open(file, \"rb\")\n await bot.send_photo(message.from_user.id, img)\n\n\n@dp.message_handler(commands=['fullname'])\nasync def echo(message: types.Message):\n print(\"попросили данные по имени\")\n arguments = message.get_args()\n print(arguments)\n s = arguments.lower()\n s = s.split()\n cur.execute(\"select * from barsa where name=:name and lastname=:lastname or name=:lastname and lastname=:name\",\n {\"name\": s[0], \"lastname\": s[1]})\n res = cur.fetchone()\n cur.execute(\"select count(*) from barsa where lastname=:lastname\",\n {\"lastname\": s[1]})\n res2 = cur.fetchone()\n print(res2[0])\n result = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[2] + '\\n' + 'Номер Паспорта:' + ' ' + \\\n res[3] + '\\n' + 'Национальность:' + ' ' + res[4] + \"\\n\" + \"Родвественников:\" + ' ' + str(\n res2[0]) + '\\n' + \"Номер \" \\\n \"лицензии на \" \\\n \"оружие:\" + \" \" + \\\n res[5] + '\\n' + \\\n \"Преступление:\" + \" \" + res[6]\n await bot.send_message(message.from_user.id, result)\n os.chdir(idfolder)\n for file in glob.glob(res[3] + \".jpg\"):\n img = open(file, \"rb\")\n await bot.send_photo(message.from_user.id, img)\n\n\n@dp.message_handler(commands=['lastname'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n print(\"попросили данные по Фамилии:\", arguments)\n s = arguments.lower()\n cur.execute(\"select * from barsa where lastname=:lastname \",\n {\"lastname\": s})\n res = cur.fetchall()\n os.chdir(idfolder)\n for f in res:\n print(f)\n cur.execute(\"select * from barsa where id=:id\", {\"id\": f[3]})\n res = cur.fetchone()\n req = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[\n 2] + '\\n' + 'Номер Паспорта:' + ' ' + res[3] + '\\n' + 'Национальность:' + ' ' + res[\n 4] + '\\n' + \"Номер \" \\\n \"лицензии на \" \\\n \"оружие:\" + \" \" + \\\n res[5] + '\\n' + \\\n \"Преступление:\" + \" \" + res[6]\n await bot.send_message(message.from_user.id, req)\n\n for file in glob.glob(res[3] + \".jpg\"):\n img = open(file, \"rb\")\n await bot.send_photo(message.from_user.id, img)\n\n\n@dp.message_handler(commands=['get_scan_nat'])\nasync def echo(message: types.Message):\n print(\"попросили ВСЕ СКАНЫ по по национальности\")\n arguments = message.get_args()\n print(arguments)\n s = arguments\n s = s.capitalize()\n cur.execute(\"select id from barsa where nat_=:nat_\", {\"nat_\": s})\n res = cur.fetchall()\n out = [item for t in res for item in t]\n out = [s.replace(\" \", \"\") for s in out]\n os.chdir(idfolder)\n for f in out:\n print(f)\n if f == '472-641218' or f == '757-067985' or f == '642-741978' or f == '696-082959' or f == '442-446766' or f == '702-973965':\n cur.execute(\"select * from barsa where id=:id\", {\"id\": f})\n res = cur.fetchone()\n req = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[\n 2] + '\\n' + 'Номер Паспорта:' + ' ' + res[3] + '\\n' + 'Национальность:' + ' ' + res[\n 4] + '\\n' + \"Номер \" \\\n \"лицензии на \" \\\n \"оружие:\" + \" \" + \\\n res[5] + '\\n' + \\\n \"Преступление:\" + \" \" + res[6]\n await bot.send_message(message.from_user.id, req)\n else:\n img = open(f + '.jpg', \"rb\")\n print('ok')\n await bot.send_photo(message.from_user.id, img)\n\n\n@dp.message_handler(commands=['add_person'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n s = arguments.split()\n print(s)\n sqlite_insert_query = \"\"\"INSERT INTO barsa\n (name, lastname, id, nat_,gunlic,crime)\n VALUES\n (?,?,?,?,?,?)\"\"\"\n data_tuple = (s[0], s[1], s[2], s[3], s[4], s[5])\n cur.execute(sqlite_insert_query, data_tuple)\n conn.commit()\n\n print(\"Запись о гражданине успешно добавлена \")\n cur.execute(\"select * from barsa where id=:id\", {\"id\": s[2]})\n res = cur.fetchone()\n req = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[\n 2] + '\\n' + 'Номер Паспорта:' + ' ' + res[3] + '\\n' + 'Национальность:' + ' ' + res[4] + '\\n' + \"Номер \" \\\n \"лицензии на \" \\\n \"оружие:\" + \" \" + \\\n res[5] + '\\n' + \\\n \"Преступление:\" + \" \" + res[6]\n await bot.send_message(message.from_user.id, req)\n\n\n@dp.message_handler(commands=['delete_person'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n print(\"попросили удалить гражаднина с ID:\", arguments)\n s = arguments\n cur.execute(\"delete from barsa where id=:id\", {\"id\": s})\n conn.commit()\n print(\"Гражданин с ID :\", arguments, 'удален')\n res = \"Гражданин с ID :\", arguments, 'удален'\n await bot.send_message(message.from_user.id, res)\n\n\n@dp.message_handler(commands=['add_gun_lic'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n s = arguments.split()\n print(s[0], s[1])\n cur.execute(\" update barsa set gunlic=:gunlic where id=:id\", {\"gunlic\": s[1], \"id\": s[0]})\n conn.commit()\n print(\"Record Updated successfully \")\n cur.execute(\"select * from barsa where id=:id\", {\"id\": s[0]})\n res = cur.fetchone()\n print(res)\n req = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[\n 2] + '\\n' + 'Номер Паспорта:' + ' ' + res[3] + '\\n' + 'Национальность:' + ' ' + res[4] + '\\n' + \"Номер \" \\\n \"лицензии на \" \\\n \"оружие:\" + \" \" + \\\n res[5]\n await bot.send_message(message.from_user.id, req)\n\n\n@dp.message_handler(commands=['gun_lic'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n s = arguments\n print(s)\n cur.execute(\"select * from barsa where gunlic=:gunlic\", {\"gunlic\": s})\n res = cur.fetchone()\n print(res)\n req = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[\n 2] + '\\n' + 'Номер Паспорта:' + ' ' + res[3] + '\\n' + 'Национальность:' + ' ' + res[4] + '\\n' + \"Номер \" \\\n \"лицензии на \" \\\n \"оружие:\" + \" \" + \\\n res[5] + '\\n' + \\\n \"Преступление:\" + \" \" + res[6]\n await bot.send_message(message.from_user.id, req)\n\n\n@dp.message_handler(commands=['delete_gun_lic'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n s = arguments\n print(s)\n no = 'нет'\n cur.execute(\"update barsa set gunlic=:gunlic1 where id=:id\", {\"gunlic1\": no, \"id\": s})\n res1 = cur.fetchone()\n conn.commit()\n ans = \"Оружейная лицения гражданина:\",s, \" удалена\"\n await bot.send_message(message.from_user.id, ans)\n\n\n@dp.message_handler(commands=['add_crime'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n s = arguments.split()\n print(s[0], s[1])\n cur.execute(\" update barsa set crime=:crime where id=:id\", {\"crime\": s[1], \"id\": s[0]})\n conn.commit()\n print(\"Record Updated successfully \")\n cur.execute(\"select * from barsa where id=:id\", {\"id\": s[0]})\n res = cur.fetchone()\n print(res)\n req = 'Имя:' + ' ' + res[1] + '\\n' + 'Фамилия:' + ' ' + res[\n 2] + '\\n' + 'Номер Паспорта:' + ' ' + res[3] + '\\n' + 'Национальность:' + ' ' + res[4] + '\\n' + \"Номер \" \\\n \"лицензии на \" \\\n \"оружие:\" + \" \" + \\\n res[5] + '\\n' + \\\n \"Преступление:\" + \" \" + res[6]\n await bot.send_message(message.from_user.id, req)\n\n@dp.message_handler(commands=['delete_crime'])\nasync def echo(message: types.Message):\n arguments = message.get_args()\n s = arguments\n print(s)\n no = 'нет'\n cur.execute(\"update barsa set crime=:crime where id=:id\", {\"crime\": no, \"id\": s})\n res1 = cur.fetchone()\n conn.commit()\n ans = \"Преступление гражданина:\",s, \" удалено\"\n await bot.send_message(message.from_user.id, ans)\n\n\nif __name__ == '__main__':\n executor.start_polling(dp, skip_updates=False)\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse
from django.contrib import messages
# Create your views here.
from User.models import User, check_if_auth_user
from .models import Chat
# def recv_chat(request, id = None):
# check = check_if_auth_user(request)
# if not check:
# messages.error(request, "Perform login first to start chatting")
# return redirect("home:welcome")
# current_user = User.objects.filter(user_id = check)[0]
# other_user = get_object_or_404(User, auto_id = id)
# message = request.POST.get('chat_msg')
# try:
# if current_user and other_user and message:
# #sql = """INSERT INTO User_user( name, user_id, user_pwd, contact, address)
# # Values(%s,%s,%s,%s,%s)""" % ( name, email, pwd, con, add)
# chat = Chat(
# chat_sender = current_user.user_id,
# chat_reciever = other_user.user_id,
# message = message)
# chat.save()
# return redirect(chat.get_return_url())
# except Exception,error:
# messages.error(request, "Some Internal Error. Try again")
# return redirect(chat.get_return_url())
def begin_chat(request, id = None):
check = check_if_auth_user(request)
if not check:
messages.error(request, "Perform login first to start chatting")
return redirect("home:welcome")
current_user = User.objects.filter(user_id = check)[0]
other_user = get_object_or_404(User, auto_id = id)
sql = """SELECT * FROM chat_start_chat
WHERE chat_sender='{0}' and chat_reciever='{1}'
OR chat_sender='{1}' and chat_reciever='{0}';"""
chat_list = Chat.objects.raw(sql.format(current_user.user_id,other_user.user_id))
context_data = {
"user" : current_user,
"other_user" : other_user,
"chatmessage_list": chat_list,
}
return render(request, "chat.html",context_data)
|
normal
|
{
"blob_id": "9dfb3f58127b30467651ac4209277cd947643c65",
"index": 7411,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef begin_chat(request, id=None):\n check = check_if_auth_user(request)\n if not check:\n messages.error(request, 'Perform login first to start chatting')\n return redirect('home:welcome')\n current_user = User.objects.filter(user_id=check)[0]\n other_user = get_object_or_404(User, auto_id=id)\n sql = \"\"\"SELECT * FROM chat_start_chat\n\t\t\t WHERE chat_sender='{0}' and chat_reciever='{1}'\n\t\t\t OR chat_sender='{1}' and chat_reciever='{0}';\"\"\"\n chat_list = Chat.objects.raw(sql.format(current_user.user_id,\n other_user.user_id))\n context_data = {'user': current_user, 'other_user': other_user,\n 'chatmessage_list': chat_list}\n return render(request, 'chat.html', context_data)\n",
"step-3": "from django.shortcuts import render, redirect, get_object_or_404\nfrom django.http import HttpResponse\nfrom django.contrib import messages\nfrom User.models import User, check_if_auth_user\nfrom .models import Chat\n\n\ndef begin_chat(request, id=None):\n check = check_if_auth_user(request)\n if not check:\n messages.error(request, 'Perform login first to start chatting')\n return redirect('home:welcome')\n current_user = User.objects.filter(user_id=check)[0]\n other_user = get_object_or_404(User, auto_id=id)\n sql = \"\"\"SELECT * FROM chat_start_chat\n\t\t\t WHERE chat_sender='{0}' and chat_reciever='{1}'\n\t\t\t OR chat_sender='{1}' and chat_reciever='{0}';\"\"\"\n chat_list = Chat.objects.raw(sql.format(current_user.user_id,\n other_user.user_id))\n context_data = {'user': current_user, 'other_user': other_user,\n 'chatmessage_list': chat_list}\n return render(request, 'chat.html', context_data)\n",
"step-4": "from django.shortcuts import render, redirect, get_object_or_404\nfrom django.http import HttpResponse\nfrom django.contrib import messages\n# Create your views here.\nfrom User.models import User, check_if_auth_user\nfrom .models import Chat\n\n# def recv_chat(request, id = None):\n# \tcheck = check_if_auth_user(request)\n# \tif not check:\n# \t\tmessages.error(request, \"Perform login first to start chatting\")\n# \t\treturn redirect(\"home:welcome\")\n\n# \tcurrent_user = User.objects.filter(user_id = check)[0]\n# \tother_user = get_object_or_404(User, auto_id = id)\n# \tmessage = request.POST.get('chat_msg')\n\n# \ttry:\n# \t\tif current_user and other_user and message:\n# \t\t\t#sql = \"\"\"INSERT INTO User_user( name, user_id, user_pwd, contact, address) \n# \t\t\t#\t\tValues(%s,%s,%s,%s,%s)\"\"\" % ( name, email, pwd, con, add)\n# \t\t\tchat = Chat(\n# \t\t\t\t\tchat_sender = current_user.user_id,\n# \t\t\t\t\tchat_reciever = other_user.user_id,\n# \t\t\t\t\tmessage = message)\n# \t\t\tchat.save()\n# \t\t\treturn redirect(chat.get_return_url())\n# \texcept Exception,error:\n# \t\tmessages.error(request, \"Some Internal Error. Try again\")\n# \treturn redirect(chat.get_return_url())\n\n\ndef begin_chat(request, id = None):\n\tcheck = check_if_auth_user(request)\n\tif not check:\n\t\tmessages.error(request, \"Perform login first to start chatting\")\n\t\treturn redirect(\"home:welcome\")\n\tcurrent_user = User.objects.filter(user_id = check)[0]\n\tother_user = get_object_or_404(User, auto_id = id)\n\t\n\tsql = \"\"\"SELECT * FROM chat_start_chat\n\t\t\t WHERE chat_sender='{0}' and chat_reciever='{1}'\n\t\t\t OR chat_sender='{1}' and chat_reciever='{0}';\"\"\"\n\n\tchat_list = Chat.objects.raw(sql.format(current_user.user_id,other_user.user_id))\n\tcontext_data = {\n\t\t\"user\" : current_user,\n\t\t\"other_user\" : other_user,\n\t\t\"chatmessage_list\": chat_list,\n\t}\n\treturn render(request, \"chat.html\",context_data)\n\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
import matplotlib
matplotlib.use('Agg')
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1 import make_axes_locatable
def plot_overscan(overscan, img, TITLE, OUT_DIR):
""" plot overscan in 9x2 plots with 16 channels """
fig = plt.figure(figsize=(20, 20))
gs0 = gridspec.GridSpec(3, 3)
for i, f in enumerate(img):
x = f.dev_index % 3
gs = gridspec.GridSpecFromSubplotSpec(
1, 2, wspace=0, subplot_spec=gs0[f.dev_index])
ax2 = plt.subplot(gs[0, 0])
for j in range(9, 17):
plt.plot(overscan[i, j - 1] + 500 *
(j - 8), label='seg' + str(j + 1))
plt.legend(fontsize=6, loc='upper center', ncol=4)
if x != 0:
ax2.set_yticklabels([])
plt.grid()
plt.xlim(0, 2100)
plt.ylim(0, 4500)
ax2.set_title(f.dev_name + ' (seg 10-17)')
ax1 = plt.subplot(gs[0, 1])
for j in range(1, 9):
plt.plot(overscan[i, j - 1] + 500 * j, label='seg' + str(j - 1))
plt.legend(fontsize=6, loc='upper center', ncol=4)
if x != 2:
ax1.set_yticklabels([])
if x == 2:
ax1.yaxis.tick_right()
plt.grid()
plt.xlim(0, 2100)
plt.ylim(0, 4500)
ax1.set_title(f.dev_name + ' (seg 0-7)')
fig.suptitle('Overscan ' + TITLE, y=0.94, size=20)
plt.subplots_adjust(wspace=0.05)
plt.savefig(OUT_DIR + TITLE + '_spatial.png')
plt.close(fig)
def plot_overscan_diff(overscan, img, TITLE, OUT_DIR):
""" plot overscan with subtracted 7th / 17th channel """
fig = plt.figure(figsize=(20, 20))
gs0 = gridspec.GridSpec(3, 3)
for i, f in enumerate(img):
x = f.dev_index % 3
gs = gridspec.GridSpecFromSubplotSpec(
1, 2, wspace=0, subplot_spec=gs0[f.dev_index])
ax2 = plt.subplot(gs[0, 0])
for j in range(9, 17):
plt.plot(overscan[i, j - 1] - overscan[i, 15] +
500 * (j - 8), label='seg' + str(j + 1))
plt.legend(fontsize=6, loc='upper center', ncol=4)
if(x != 0):
ax2.set_yticklabels([])
plt.grid()
plt.xlim(0, 2100)
plt.ylim(0, 4500)
ax2.set_title(f.dev_name + ' (seg 10-17)')
ax1 = plt.subplot(gs[0, 1])
for j in range(1, 9):
plt.plot(overscan[i, j - 1] - overscan[i, 7] +
500 * j, label='seg' + str(j - 1))
plt.legend(fontsize=6, loc='upper center', ncol=4)
if(x != 2):
ax1.set_yticklabels([])
if(x == 2):
ax1.yaxis.tick_right()
plt.grid()
plt.xlim(0, 2100)
plt.ylim(0, 4500)
ax1.set_title(f.dev_name + ' (seg 0-7)')
# ax1.set_title('S-'+f[7:9]+' (seg 0-7)')
fig.suptitle('Overscan (diff) ' + TITLE, y=0.94, size=20)
plt.subplots_adjust(wspace=0.05)
plt.savefig(OUT_DIR + TITLE + '_diff_spatial.png')
plt.close(fig)
def plot_mean_std_stddelta(m, n, nd, img, TITLE, OUT_DIR):
""" plot std vs. mean vs. std_delta (comparison) """
fig = plt.figure(figsize=(15, 10))
for i, f in enumerate(img):
ax1 = plt.subplot(3, 3, f.dev_index + 1)
lns1 = ax1.plot(m[i], 'o', color='green', label='offset')
ax1.set_ylabel('mean')
ax1.set_xlabel('segment num')
ax2 = ax1.twinx()
lns2 = ax2.plot(n[i], '^', color='blue', label='noise')
ax2.set_ylabel('stdev')
lns3 = ax2.plot(nd[i], 'v', color='red', label='dnoise')
lns = lns1 + lns2 + lns3
labs = [l.get_label() for l in lns]
ax1.legend(lns, labs, bbox_to_anchor=(0., 1.07, 1., .102),
fontsize='small', ncol=3, numpoints=1, loc=9)
plt.grid()
plt.title(' ' + f.dev_name, y=1.15)
fig.suptitle('Offset, noise, dnoise comparison ' + TITLE, y=0.99, size=20)
plt.subplots_adjust(wspace=0.5, hspace=0.6)
plt.savefig(OUT_DIR + TITLE + '_std_vs_mean.png')
plt.close(fig)
def plot_histogram_mean(m, TITLE, OUT_DIR):
fig = plt.figure(figsize=(15, 15))
m_all = m.ravel()
for bin_num in np.arange(10, 100, 10):
plt.subplot(3, 3, bin_num / 10)
plt.hist(m_all, bin_num, facecolor='green')
plt.title('Bins = ' + str(bin_num))
plt.subplots_adjust(wspace=0.2, hspace=0.2)
fig.suptitle('offset histogram ' + TITLE, y=0.92, size=20)
plt.savefig(OUT_DIR + TITLE + '_mean_histo.png')
plt.close(fig)
def plot_histogram_std(n, TITLE, OUT_DIR):
fig = plt.figure(figsize=(15, 15))
n_all = n.ravel()
for bin_num in np.arange(10, 100, 10):
plt.subplot(3, 3, bin_num / 10)
plt.hist(n_all, bin_num, facecolor='green')
plt.title('Bins = ' + str(bin_num))
fig.suptitle('noise histogram ' + TITLE, y=0.92, size=20)
plt.subplots_adjust(wspace=0.2, hspace=0.2)
plt.savefig(OUT_DIR + TITLE + '_std_histo.png')
plt.close(fig)
def plot_histogram_std_dev(nd, TITLE, OUT_DIR):
fig = plt.figure(figsize=(15, 15))
nd_all = nd.ravel()
for bin_num in np.arange(10, 100, 10):
plt.subplot(3, 3, bin_num / 10)
plt.hist(nd_all, bin_num, facecolor='green')
plt.title('Bins = ' + str(bin_num))
fig.suptitle('dnoise histogram ' + TITLE, y=0.92, size=20)
plt.subplots_adjust(wspace=0.2, hspace=0.2)
plt.savefig(OUT_DIR + TITLE + '_stddelta_histo.png')
plt.close(fig)
def plot_histogram_all(m, n, nd, TITLE, OUT_DIR):
plot_histogram_mean(m, TITLE, OUT_DIR)
plot_histogram_std(n, TITLE, OUT_DIR)
plot_histogram_std_dev(nd, TITLE, OUT_DIR)
def plot_histogram_all_one_binning(m, n, nd, TITLE, OUT_DIR, bin_num=45,
num_ccd=9, omit_REBs=[], read_REBs=set([0, 1, 2])):
from matplotlib.patches import Rectangle
if num_ccd != len(read_REBs) * 3:
print "ERROR! num_ccd = %i while number of REBs being read is %i." % (
num_ccd, len(read_REBs)
)
return "\n"
fig = plt.figure(figsize=(15, 6))
m_all = m.ravel()
m_all = m_all[0:16 * num_ccd]
n_all = n.ravel()
n_all = n_all[0:16 * num_ccd]
nd_all = nd.ravel()
nd_all = nd_all[0:16 * num_ccd]
# detect dead channels, DEF: noise <= 5
dead = []
for i in range(16 * num_ccd):
if n_all[i] <= 5:
dead.append(i)
# not count not-clocking REBs for statistics
# data stored in order 22, 21, 20 (REB 2), 12, 11, 10 (REB 1),...
omit_REBs = set(omit_REBs)
for REB in omit_REBs:
if REB not in [0, 1, 2]:
print "WARNING! Wrong configuration of REBs to omit %s - unrecognized REBs.\nContinuing with all REBs." % str(omit_REBs)
break
else:
if omit_REBs:
print "Omiting REBs %s" % omit_REBs
i = -1
for REB in read_REBs:
i += 1
if REB not in omit_REBs:
continue
pos = len(read_REBs) - i - 1
omit = np.arange(pos * 48, pos * 48 + 48)
dead = np.append(dead, omit)
m_no_dead = np.delete(m_all, dead)
n_no_dead = np.delete(n_all, dead)
# get rid of subtracted channels for dnoise
sub = np.arange(7, 16 * num_ccd, 8)
dead = np.append(dead, sub)
nd_no_dead = np.delete(nd_all, dead)
nd_all = np.delete(nd_all, sub)
# summary statstics computed only with live channels
if len(n_no_dead):
n_mean, n_median, n_std = np.mean(
n_no_dead), np.median(n_no_dead), np.std(n_no_dead)
else:
n_mean, n_median, n_std = 0, 0, 0
if len(m_no_dead):
m_mean, m_median, m_std = np.mean(
m_no_dead), np.median(m_no_dead), np.std(m_no_dead)
else:
m_mean, m_median, m_std = 0, 0, 0
if len(nd_no_dead):
nd_mean, nd_median, nd_std = np.mean(
nd_no_dead), np.median(nd_no_dead), np.std(nd_no_dead)
else:
nd_mean, nd_median, nd_std = 0, 0, 0
bin_num_lin = 4 * bin_num / 5
bin_num_log = 1 * bin_num / 5
bins_lin = np.linspace(0, 30, bin_num_lin)
val_max = max(max(n_all), max(nd_all))
if val_max <= 30:
val_max = 50
bins_log = np.logspace(np.log10(30), np.log10(val_max), bin_num_log)
ax1 = fig.add_subplot(1, 2, 1)
plt.hist(m_all, bin_num, facecolor='green')
plt.title('Offset')
textstr1 = '$\mu=%.0f$\n$\mathrm{median}=%.0f$\n$\sigma=%.0f$' % (
m_mean, m_median, m_std)
props1 = dict(boxstyle='round', facecolor='green', alpha=0.4)
ax1.text(0.76, 0.97, textstr1, transform=ax1.transAxes, fontsize=10,
verticalalignment='top', bbox=props1)
ax2 = fig.add_subplot(1, 2, 2)
plt.hist(n_all, bins_lin, facecolor='blue', alpha=0.5, label='noise')
plt.hist(nd_all, bins_lin, facecolor='red', alpha=0.5, label='dnoise')
plt.title('Noises')
plt.legend(loc='upper left')
ax2.axvspan(0, 5, hatch='x', fill=False)
ax2.set_xscale('linear')
ax2.set_xlim((0, 30))
ax2.set_xlim(left=0)
ax2.spines['right'].set_visible(False)
ax2.yaxis.set_ticks_position('left')
plt.setp(ax2.get_xticklabels(), visible=True)
divider = make_axes_locatable(ax2)
axLin = divider.append_axes("right", size=1.4, pad=0, sharey=ax2)
axLin.set_xscale('log')
axLin.hist(n_all, bins_log, facecolor='blue', alpha=0.5, label='noise')
axLin.hist(nd_all, bins_log, facecolor='red', alpha=0.5, label='dnoise')
axLin.autoscale()
axLin.set_xlim(left=30)
axLin.spines['left'].set_visible(False)
axLin.yaxis.set_visible(False)
axLin.yaxis.set_ticks_position('left')
textstr2 = '$\mu=%.1f$\n$\mathrm{median}=%.1f$\n$\sigma=%.1f$' % (
n_mean, n_median, n_std)
props2 = dict(boxstyle='round', facecolor='blue', alpha=0.4)
plt.text(1.98, 0.97, textstr2, transform=ax1.transAxes, fontsize=10,
verticalalignment='top', bbox=props2)
textstr3 = '$\mu=%.1f$\n$\mathrm{median}=%.1f$\n$\sigma=%.1f$' % (
nd_mean, nd_median, nd_std)
props3 = dict(boxstyle='round', facecolor='red', alpha=0.4)
plt.text(1.98, 0.80, textstr3, transform=ax1.transAxes, fontsize=10,
verticalalignment='top', bbox=props3)
fig.suptitle(TITLE, y=0.98, size=20)
# plt.subplots_adjust(wspace=0.2, hspace=0.2)
plt.savefig(OUT_DIR + TITLE + '_histo.png')
plt.close(fig)
string_info = "\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\n" % (
m_mean, m_median, m_std, n_mean, n_median, n_std, nd_mean, nd_median, nd_std)
return string_info
def plot_summary(data, run, OUT_DIR, SUPTITLE="Runs comparison"):
cols = len(data)
fig = plt.figure(figsize=(25, 9))
x = range(cols)
ax1 = plt.subplot(3, 1, 1)
ax1.plot(x, data[:, 0], 'o', color='darkgreen', label='mean')
ax1.errorbar(x, data[:, 0], marker='o',
color='darkgreen', yerr=data[x, 2], linestyle='None')
ax1.plot(x, data[:, 1], 'o', color='greenyellow', label='median')
ax1.set_ylabel('Offset', color='green')
ax1.legend(numpoints=1)
ax2 = plt.subplot(3, 1, 2)
ax2.plot(x, data[:, 3], 'o', color='darkblue', label='mean')
ax2.errorbar(x, data[:, 3], marker='o', color='darkblue',
yerr=data[x, 5], linestyle='None')
ax2.plot(x, data[:, 4], 'o', color='lightskyblue', label='median')
ax2.set_ylabel('Noise', color='blue')
ax2.set_ylim([0, 20])
# ax2.set_ylim(bottom=0)
ax2.legend(numpoints=1)
ax3 = plt.subplot(3, 1, 3)
ax3.plot(x, data[:, 6], 'o', color='darkred', label='mean')
ax3.errorbar(x, data[:, 6], marker='o', color='darkred',
yerr=data[x, 8], linestyle='None')
ax3.plot(x, data[:, 7], 'o', color='salmon', label='median')
ax3.set_ylabel('DNoise', color='red')
ax3.set_ylim([0, 20])
# ax3.set_ylim(bottom=0)
ax3.legend(numpoints=1)
plt.xticks(x, run, rotation=45, ha='right', fontsize=7)
fig.suptitle(SUPTITLE, y=0.96, size=20)
plt.subplots_adjust(hspace=0.0, bottom=0.20, left=0.05)
plt.savefig(OUT_DIR + 'Runs_summary.png')
plt.close(fig)
def plot_one_run_summary(f, OUT_DIR, SUPTITLE="Run summary"):
data = np.loadtxt(f, usecols=range(1, 10))
run = np.loadtxt(f, usecols=[0], dtype=str)
if data.size == 9:
print "WARNING! Only one row in '%s'. Summary is not plotting.\n" % f
return
plot_summary(data, run, OUT_DIR, SUPTITLE)
def plot_cor_ccd(a, img, TITLE, OUT_DIR, vmin=0, vmax=0.2):
fig = plt.figure(figsize=(15, 15))
seg = [0, 7, 8, 15]
lab = ["0", "7", "10", "17"]
for i, f in enumerate(img):
ax1 = plt.subplot(3, 3, f.dev_index + 1)
i_min = 16 * i
i_max = i_min + 16
aa = a[i_min:i_max, i_min:i_max]
im = plt.imshow(aa, interpolation='nearest', cmap='jet', vmin=vmin, vmax=vmax)
ax1.set_title(f.dev_name)
ax1.set_xlim(15.5, -0.5)
ax1.set_ylim(-0.5, 15.5)
ax1.set_xticks(seg)
ax1.set_xticklabels(lab)
ax1.set_yticks(seg)
ax1.set_yticklabels(lab)
fig.subplots_adjust(right=0.8)
cbar_ax = fig.add_axes([0.85, 0.137, 0.05, 0.73])
fig.colorbar(im, cax=cbar_ax)
fig.suptitle("Inter CCD correlations " + TITLE, y=0.93, size=20)
plt.savefig(OUT_DIR + TITLE + '_cor_ccd.png')
plt.close(fig)
def plot_cor_all(a, img, TITLE, OUT_DIR, vmin=0, vmax=0.2):
fig = plt.figure(figsize=(15, 15))
im = plt.imshow(a, interpolation='nearest', cmap='jet', vmin=vmin, vmax=vmax)
seg = np.arange(0, len(a), 16)
r = img.ccd_num / 9.0
plt.xticks(seg)
plt.yticks(seg)
for i, f in enumerate(img):
plt.text(-10 * r, 8 + 16 * i, f.dev_name,
size=15, verticalalignment='center')
widthB = 54 / img.ccd_num
widthB = str(widthB)
for i in np.arange(0, img.ccd_num, 3):
REB = 'REB' + img[i].dev_name[1:2]
plt.annotate(REB, xy=(-11 * r, 24 + i * 16), xytext=(-18 * r, 24 + i * 16), xycoords='data',
fontsize=20, annotation_clip=False, ha='center', va='center',
arrowprops=dict(arrowstyle='-[, widthB=%s, lengthB=1.5' % widthB, lw=2.0))
fig.subplots_adjust(right=0.82)
cbar_ax = fig.add_axes([0.85, 0.155, 0.05, 0.695])
fig.colorbar(im, cax=cbar_ax)
fig.suptitle("Overall correlations " + TITLE, y=0.91, size=20)
plt.savefig(OUT_DIR + TITLE + '_cor_all.png')
plt.close(fig)
def plot_cor_ccd_mean(a, img, TITLE, OUT_DIR, vmin=-1, vmax=1):
fig = plt.figure(figsize=(15, 15))
im = plt.imshow(a, interpolation='nearest', cmap='jet', vmin=vmin, vmax=vmax)
loc = range(img.ccd_num)
labels = []
for fli in img:
labels.append(fli.dev_name)
plt.xticks(loc, labels)
plt.yticks(loc, labels)
fig.subplots_adjust(right=0.82)
cbar_ax = fig.add_axes([0.85, 0.155, 0.05, 0.695])
fig.colorbar(im, cax=cbar_ax)
fig.suptitle("Correlations of means of CCDs " + TITLE, y=0.91, size=20)
plt.savefig(OUT_DIR + TITLE + '_cor_ccd_mean.png')
plt.close(fig)
def plot_gains(gains, gain_ref, TITLES, OUT_DIR):
""" plot gains with respect to the reference gain,
whre reference gain is number => gains[gain_ref]"""
# print 'directory: %s' % OUT_DIR
# print 'TITLES:%s', TITLES
gain_ref_np = np.array(gains[gain_ref].gain)
ratios = []
for gain in gains:
gain_np = np.array(gain.gain)
dim = (min(gain_ref_np.shape[0], gain_np.shape[0]),
min(gain_ref_np.shape[1], gain_np.shape[1])
)
# print 'dim = ', dim
ratios.append(gain_np[0:dim[0], 0:dim[1]] / gain_ref_np[0:dim[0], 0:dim[1]])
# print 'Ratios = ', ratios
rows = 2*((len(ratios) -1) / 6 + 1)
cmap = plt.get_cmap('gnuplot')
colors = [cmap(i) for i in np.linspace(0, 1, len(ratios))]
fig, axes = plt.subplots(nrows=rows, ncols=6)
fig.set_size_inches(20,20)
axfl = axes.flatten()
for i, ratio in enumerate(ratios):
# print 'Plotting %s', TITLES[i]
j = (i / 6)*12 + i % 6
ax = axfl[j]
ax2 = axfl[j+6]
ax.hist(np.reshape(ratio, -1), 20, range=(0.9, 1.1), facecolor=colors[i])
ax.set_title(TITLES[i], size=20)
ax2.hist(np.reshape(ratio, -1), 50, range=(0., 2.), facecolor=colors[i])
fig.suptitle("Gains with ref gain '%s'" % TITLES[gain_ref], y=0.95, size=25)
# fig.tight_layout()
plt.savefig(OUT_DIR + 'gain.png')
plt.close(fig)
def plot_raft_map(data, img, TITLE, OUTDIR, vmin=None, vmax=None):
""" create a raft map 6x24 for data in CCDsx16 array """
map = np.zeros((6, 24))
for i, fli in enumerate(img):
x = (fli.dev_index / 3) * 2 # [0, 2, 4]
y = (fli.dev_index % 3) * 8 # [0, 8, 16]
for j in range(16):
xx = x + j / 8 # [0, 1,..., 5]
yy = y + j % 8 # [0, 1,..., 23]
map[xx, yy] = data[i, j]
yseg = range(6)
ylab = ["00-07", "10-17", "00-07", "10-17", "00-07", "10-17"]
xseg = range(0, 24, 4)
xlab = ["0", "4", "0", "4", "0", "4"]
fig = plt.figure(figsize=(10, 10))
ax1 = fig.add_subplot(111)
im = ax1.imshow(map, interpolation='nearest', cmap='jet', aspect=4, vmin=vmin, vmax=vmax)
plt.yticks(yseg, ylab)
plt.xticks(xseg, xlab)
plt.annotate('S22', xy=(0, 0), xytext=(4, -0.8), fontsize=15, ha='center', va='center')
plt.annotate('S12', xy=(0, 0), xytext=(12, -0.8), fontsize=15, ha='center', va='center')
plt.annotate('S02', xy=(0, 0), xytext=(20, -0.8), fontsize=15, ha='center', va='center')
plt.annotate('S02', xy=(0, 0), xytext=(24., 0.5), fontsize=15, ha='left', va='center')
plt.annotate('S01', xy=(0, 0), xytext=(24., 2.5), fontsize=15, ha='left', va='center')
plt.annotate('S00', xy=(0, 0), xytext=(24., 4.5), fontsize=15, ha='left', va='center')
ax1.vlines(7.5, -0.5, 5.5)
ax1.vlines(15.5, -0.5, 5.5)
ax1.hlines(1.5, -0.5, 23.5)
ax1.hlines(3.5, -0.5, 23.5)
plt.subplots_adjust(left=0.07, bottom=0.05, right=0.8, top=0.95, wspace=0, hspace=0)
#cbar_ax = fig.add_axes([0.15, 0.03, 0.7, 0.05])
#fig.colorbar(im, cax=cbar_ax, orientation="horizontal")
cbar_ax = fig.add_axes([0.87, 0.15, 0.05, 0.7])
fig.colorbar(im, cax=cbar_ax)
fig.suptitle(TITLE, y=0.98, size=19)
plt.savefig(OUTDIR + TITLE + '.png')
plt.show()
plt.close(fig)
def plot_voltage_all(x, data, imgs, title, out_dir, suptitle=''):
if suptitle == '':
suptitle = title
fig = plt.figure(figsize=(20, 24))
cmap = plt.get_cmap('gist_ncar')
colors = [cmap(i) for i in np.linspace(0, 1, 16)]
for k in range(9):
ax1 = plt.subplot(3, 3, imgs[0][k].dev_index + 1)
ax1.set_title(imgs[0][k].dev_name)
for j in range(16):
y = []
for i in range(len(x)):
y.append(data[i][k][j])
plt.plot(x, y, label='Segment %i' % j, color=colors[j])
fig.suptitle(suptitle + '; all segments', y=0.99, size=20)
plt.legend(loc='lower left', bbox_to_anchor=(0.87, 1.1), ncol=4)
plt.subplots_adjust(bottom=0.04, left=0.04, top=0.88, right=0.96, wspace=0.1, hspace=0.1)
plt.savefig(out_dir + title + '_all.png')
plt.close(fig)
def plot_voltage_ccd(x, data, imgs, title, out_dir, suptitle=''):
if suptitle == '':
suptitle = title
fig = plt.figure(figsize=(15, 15))
for k in range(9):
ax1 = plt.subplot(3, 3, imgs[0][k].dev_index + 1)
ax1.set_title(imgs[0][k].dev_name)
y = []
for i in range(len(x)):
y.append(np.mean(data[i][k]))
plt.plot(x, y)
fig.suptitle(suptitle + '; mean of segments, per CCD', y=0.94, size=20)
plt.savefig(out_dir + title + '_CCD.png')
plt.close(fig)
def plot_voltage_raft(x, data, imgs, title, out_dir, suptitle=''):
if suptitle == '':
suptitle = title
fig = plt.figure(figsize=(7, 7))
y = []
for i in range(len(x)):
y.append(np.mean(data[i]))
plt.plot(x, y)
fig.suptitle(suptitle + '; mean of all segments', y=0.96, size=20)
plt.savefig(out_dir + title + '_raft.png')
plt.close(fig)
|
normal
|
{
"blob_id": "736861f18936c7a87ecf3deb134f589b9d7eed92",
"index": 3934,
"step-1": "\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.gridspec as gridspec\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\n\n\ndef plot_overscan(overscan, img, TITLE, OUT_DIR):\n \"\"\" plot overscan in 9x2 plots with 16 channels \"\"\"\n fig = plt.figure(figsize=(20, 20))\n gs0 = gridspec.GridSpec(3, 3)\n\n for i, f in enumerate(img):\n x = f.dev_index % 3\n\n gs = gridspec.GridSpecFromSubplotSpec(\n 1, 2, wspace=0, subplot_spec=gs0[f.dev_index])\n ax2 = plt.subplot(gs[0, 0])\n for j in range(9, 17):\n plt.plot(overscan[i, j - 1] + 500 *\n (j - 8), label='seg' + str(j + 1))\n plt.legend(fontsize=6, loc='upper center', ncol=4)\n if x != 0:\n ax2.set_yticklabels([])\n\n plt.grid()\n plt.xlim(0, 2100)\n plt.ylim(0, 4500)\n ax2.set_title(f.dev_name + ' (seg 10-17)')\n\n ax1 = plt.subplot(gs[0, 1])\n for j in range(1, 9):\n plt.plot(overscan[i, j - 1] + 500 * j, label='seg' + str(j - 1))\n plt.legend(fontsize=6, loc='upper center', ncol=4)\n if x != 2:\n ax1.set_yticklabels([])\n if x == 2:\n ax1.yaxis.tick_right()\n plt.grid()\n plt.xlim(0, 2100)\n plt.ylim(0, 4500)\n ax1.set_title(f.dev_name + ' (seg 0-7)')\n\n fig.suptitle('Overscan ' + TITLE, y=0.94, size=20)\n plt.subplots_adjust(wspace=0.05)\n plt.savefig(OUT_DIR + TITLE + '_spatial.png')\n plt.close(fig)\n\n\ndef plot_overscan_diff(overscan, img, TITLE, OUT_DIR):\n \"\"\" plot overscan with subtracted 7th / 17th channel \"\"\"\n fig = plt.figure(figsize=(20, 20))\n gs0 = gridspec.GridSpec(3, 3)\n\n for i, f in enumerate(img):\n x = f.dev_index % 3\n\n gs = gridspec.GridSpecFromSubplotSpec(\n 1, 2, wspace=0, subplot_spec=gs0[f.dev_index])\n ax2 = plt.subplot(gs[0, 0])\n for j in range(9, 17):\n plt.plot(overscan[i, j - 1] - overscan[i, 15] +\n 500 * (j - 8), label='seg' + str(j + 1))\n plt.legend(fontsize=6, loc='upper center', ncol=4)\n if(x != 0):\n ax2.set_yticklabels([])\n\n plt.grid()\n plt.xlim(0, 2100)\n plt.ylim(0, 4500)\n ax2.set_title(f.dev_name + ' (seg 10-17)')\n\n ax1 = plt.subplot(gs[0, 1])\n for j in range(1, 9):\n plt.plot(overscan[i, j - 1] - overscan[i, 7] +\n 500 * j, label='seg' + str(j - 1))\n plt.legend(fontsize=6, loc='upper center', ncol=4)\n if(x != 2):\n ax1.set_yticklabels([])\n if(x == 2):\n ax1.yaxis.tick_right()\n plt.grid()\n plt.xlim(0, 2100)\n plt.ylim(0, 4500)\n ax1.set_title(f.dev_name + ' (seg 0-7)')\n #\tax1.set_title('S-'+f[7:9]+' (seg 0-7)')\n\n fig.suptitle('Overscan (diff) ' + TITLE, y=0.94, size=20)\n plt.subplots_adjust(wspace=0.05)\n plt.savefig(OUT_DIR + TITLE + '_diff_spatial.png')\n plt.close(fig)\n\n\ndef plot_mean_std_stddelta(m, n, nd, img, TITLE, OUT_DIR):\n \"\"\" plot std vs. mean vs. std_delta (comparison) \"\"\"\n fig = plt.figure(figsize=(15, 10))\n\n for i, f in enumerate(img):\n\n ax1 = plt.subplot(3, 3, f.dev_index + 1)\n lns1 = ax1.plot(m[i], 'o', color='green', label='offset')\n ax1.set_ylabel('mean')\n ax1.set_xlabel('segment num')\n\n ax2 = ax1.twinx()\n lns2 = ax2.plot(n[i], '^', color='blue', label='noise')\n ax2.set_ylabel('stdev')\n lns3 = ax2.plot(nd[i], 'v', color='red', label='dnoise')\n\n lns = lns1 + lns2 + lns3\n labs = [l.get_label() for l in lns]\n ax1.legend(lns, labs, bbox_to_anchor=(0., 1.07, 1., .102),\n fontsize='small', ncol=3, numpoints=1, loc=9)\n\n plt.grid()\n plt.title(' ' + f.dev_name, y=1.15)\n\n fig.suptitle('Offset, noise, dnoise comparison ' + TITLE, y=0.99, size=20)\n plt.subplots_adjust(wspace=0.5, hspace=0.6)\n plt.savefig(OUT_DIR + TITLE + '_std_vs_mean.png')\n plt.close(fig)\n\n\ndef plot_histogram_mean(m, TITLE, OUT_DIR):\n fig = plt.figure(figsize=(15, 15))\n m_all = m.ravel()\n\n for bin_num in np.arange(10, 100, 10):\n plt.subplot(3, 3, bin_num / 10)\n plt.hist(m_all, bin_num, facecolor='green')\n plt.title('Bins = ' + str(bin_num))\n\n plt.subplots_adjust(wspace=0.2, hspace=0.2)\n fig.suptitle('offset histogram ' + TITLE, y=0.92, size=20)\n plt.savefig(OUT_DIR + TITLE + '_mean_histo.png')\n plt.close(fig)\n\n\ndef plot_histogram_std(n, TITLE, OUT_DIR):\n fig = plt.figure(figsize=(15, 15))\n n_all = n.ravel()\n\n for bin_num in np.arange(10, 100, 10):\n plt.subplot(3, 3, bin_num / 10)\n plt.hist(n_all, bin_num, facecolor='green')\n plt.title('Bins = ' + str(bin_num))\n\n fig.suptitle('noise histogram ' + TITLE, y=0.92, size=20)\n plt.subplots_adjust(wspace=0.2, hspace=0.2)\n plt.savefig(OUT_DIR + TITLE + '_std_histo.png')\n plt.close(fig)\n\n\ndef plot_histogram_std_dev(nd, TITLE, OUT_DIR):\n fig = plt.figure(figsize=(15, 15))\n nd_all = nd.ravel()\n\n for bin_num in np.arange(10, 100, 10):\n plt.subplot(3, 3, bin_num / 10)\n plt.hist(nd_all, bin_num, facecolor='green')\n plt.title('Bins = ' + str(bin_num))\n\n fig.suptitle('dnoise histogram ' + TITLE, y=0.92, size=20)\n plt.subplots_adjust(wspace=0.2, hspace=0.2)\n plt.savefig(OUT_DIR + TITLE + '_stddelta_histo.png')\n plt.close(fig)\n\n\ndef plot_histogram_all(m, n, nd, TITLE, OUT_DIR):\n plot_histogram_mean(m, TITLE, OUT_DIR)\n plot_histogram_std(n, TITLE, OUT_DIR)\n plot_histogram_std_dev(nd, TITLE, OUT_DIR)\n\n\ndef plot_histogram_all_one_binning(m, n, nd, TITLE, OUT_DIR, bin_num=45,\n num_ccd=9, omit_REBs=[], read_REBs=set([0, 1, 2])):\n from matplotlib.patches import Rectangle\n\n if num_ccd != len(read_REBs) * 3:\n print \"ERROR! num_ccd = %i while number of REBs being read is %i.\" % (\n num_ccd, len(read_REBs)\n )\n return \"\\n\"\n\n fig = plt.figure(figsize=(15, 6))\n m_all = m.ravel()\n m_all = m_all[0:16 * num_ccd]\n n_all = n.ravel()\n n_all = n_all[0:16 * num_ccd]\n nd_all = nd.ravel()\n nd_all = nd_all[0:16 * num_ccd]\n\n # detect dead channels, DEF: noise <= 5\n dead = []\n for i in range(16 * num_ccd):\n if n_all[i] <= 5:\n dead.append(i)\n\n # not count not-clocking REBs for statistics\n # data stored in order 22, 21, 20 (REB 2), 12, 11, 10 (REB 1),...\n omit_REBs = set(omit_REBs)\n for REB in omit_REBs:\n if REB not in [0, 1, 2]:\n print \"WARNING! Wrong configuration of REBs to omit %s - unrecognized REBs.\\nContinuing with all REBs.\" % str(omit_REBs)\n break\n else:\n if omit_REBs:\n print \"Omiting REBs %s\" % omit_REBs\n i = -1\n for REB in read_REBs:\n i += 1\n if REB not in omit_REBs:\n continue\n pos = len(read_REBs) - i - 1\n omit = np.arange(pos * 48, pos * 48 + 48)\n dead = np.append(dead, omit)\n\n m_no_dead = np.delete(m_all, dead)\n n_no_dead = np.delete(n_all, dead)\n\n # get rid of subtracted channels for dnoise\n sub = np.arange(7, 16 * num_ccd, 8)\n dead = np.append(dead, sub)\n\n nd_no_dead = np.delete(nd_all, dead)\n nd_all = np.delete(nd_all, sub)\n\n # summary statstics computed only with live channels\n if len(n_no_dead):\n n_mean, n_median, n_std = np.mean(\n n_no_dead), np.median(n_no_dead), np.std(n_no_dead)\n else:\n n_mean, n_median, n_std = 0, 0, 0\n if len(m_no_dead):\n m_mean, m_median, m_std = np.mean(\n m_no_dead), np.median(m_no_dead), np.std(m_no_dead)\n else:\n m_mean, m_median, m_std = 0, 0, 0\n if len(nd_no_dead):\n nd_mean, nd_median, nd_std = np.mean(\n nd_no_dead), np.median(nd_no_dead), np.std(nd_no_dead)\n else:\n nd_mean, nd_median, nd_std = 0, 0, 0\n\n bin_num_lin = 4 * bin_num / 5\n bin_num_log = 1 * bin_num / 5\n bins_lin = np.linspace(0, 30, bin_num_lin)\n val_max = max(max(n_all), max(nd_all))\n if val_max <= 30:\n val_max = 50\n bins_log = np.logspace(np.log10(30), np.log10(val_max), bin_num_log)\n\n ax1 = fig.add_subplot(1, 2, 1)\n plt.hist(m_all, bin_num, facecolor='green')\n plt.title('Offset')\n\n textstr1 = '$\\mu=%.0f$\\n$\\mathrm{median}=%.0f$\\n$\\sigma=%.0f$' % (\n m_mean, m_median, m_std)\n props1 = dict(boxstyle='round', facecolor='green', alpha=0.4)\n ax1.text(0.76, 0.97, textstr1, transform=ax1.transAxes, fontsize=10,\n verticalalignment='top', bbox=props1)\n\n ax2 = fig.add_subplot(1, 2, 2)\n plt.hist(n_all, bins_lin, facecolor='blue', alpha=0.5, label='noise')\n plt.hist(nd_all, bins_lin, facecolor='red', alpha=0.5, label='dnoise')\n plt.title('Noises')\n plt.legend(loc='upper left')\n ax2.axvspan(0, 5, hatch='x', fill=False)\n ax2.set_xscale('linear')\n ax2.set_xlim((0, 30))\n ax2.set_xlim(left=0)\n ax2.spines['right'].set_visible(False)\n ax2.yaxis.set_ticks_position('left')\n plt.setp(ax2.get_xticklabels(), visible=True)\n\n divider = make_axes_locatable(ax2)\n axLin = divider.append_axes(\"right\", size=1.4, pad=0, sharey=ax2)\n axLin.set_xscale('log')\n axLin.hist(n_all, bins_log, facecolor='blue', alpha=0.5, label='noise')\n axLin.hist(nd_all, bins_log, facecolor='red', alpha=0.5, label='dnoise')\n axLin.autoscale()\n axLin.set_xlim(left=30)\n axLin.spines['left'].set_visible(False)\n axLin.yaxis.set_visible(False)\n axLin.yaxis.set_ticks_position('left')\n\n textstr2 = '$\\mu=%.1f$\\n$\\mathrm{median}=%.1f$\\n$\\sigma=%.1f$' % (\n n_mean, n_median, n_std)\n props2 = dict(boxstyle='round', facecolor='blue', alpha=0.4)\n plt.text(1.98, 0.97, textstr2, transform=ax1.transAxes, fontsize=10,\n verticalalignment='top', bbox=props2)\n\n textstr3 = '$\\mu=%.1f$\\n$\\mathrm{median}=%.1f$\\n$\\sigma=%.1f$' % (\n nd_mean, nd_median, nd_std)\n props3 = dict(boxstyle='round', facecolor='red', alpha=0.4)\n plt.text(1.98, 0.80, textstr3, transform=ax1.transAxes, fontsize=10,\n verticalalignment='top', bbox=props3)\n\n fig.suptitle(TITLE, y=0.98, size=20)\n#\tplt.subplots_adjust(wspace=0.2, hspace=0.2)\n plt.savefig(OUT_DIR + TITLE + '_histo.png')\n plt.close(fig)\n string_info = \"\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\n\" % (\n m_mean, m_median, m_std, n_mean, n_median, n_std, nd_mean, nd_median, nd_std)\n return string_info\n\n\ndef plot_summary(data, run, OUT_DIR, SUPTITLE=\"Runs comparison\"):\n cols = len(data)\n fig = plt.figure(figsize=(25, 9))\n x = range(cols)\n\n ax1 = plt.subplot(3, 1, 1)\n ax1.plot(x, data[:, 0], 'o', color='darkgreen', label='mean')\n ax1.errorbar(x, data[:, 0], marker='o',\n color='darkgreen', yerr=data[x, 2], linestyle='None')\n ax1.plot(x, data[:, 1], 'o', color='greenyellow', label='median')\n ax1.set_ylabel('Offset', color='green')\n ax1.legend(numpoints=1)\n\n ax2 = plt.subplot(3, 1, 2)\n ax2.plot(x, data[:, 3], 'o', color='darkblue', label='mean')\n ax2.errorbar(x, data[:, 3], marker='o', color='darkblue',\n yerr=data[x, 5], linestyle='None')\n ax2.plot(x, data[:, 4], 'o', color='lightskyblue', label='median')\n ax2.set_ylabel('Noise', color='blue')\n ax2.set_ylim([0, 20])\n# ax2.set_ylim(bottom=0)\n ax2.legend(numpoints=1)\n\n ax3 = plt.subplot(3, 1, 3)\n ax3.plot(x, data[:, 6], 'o', color='darkred', label='mean')\n ax3.errorbar(x, data[:, 6], marker='o', color='darkred',\n yerr=data[x, 8], linestyle='None')\n ax3.plot(x, data[:, 7], 'o', color='salmon', label='median')\n ax3.set_ylabel('DNoise', color='red')\n ax3.set_ylim([0, 20])\n# ax3.set_ylim(bottom=0)\n ax3.legend(numpoints=1)\n\n plt.xticks(x, run, rotation=45, ha='right', fontsize=7)\n fig.suptitle(SUPTITLE, y=0.96, size=20)\n plt.subplots_adjust(hspace=0.0, bottom=0.20, left=0.05)\n\n plt.savefig(OUT_DIR + 'Runs_summary.png')\n plt.close(fig)\n\n\ndef plot_one_run_summary(f, OUT_DIR, SUPTITLE=\"Run summary\"):\n data = np.loadtxt(f, usecols=range(1, 10))\n run = np.loadtxt(f, usecols=[0], dtype=str)\n if data.size == 9:\n print \"WARNING! Only one row in '%s'. Summary is not plotting.\\n\" % f\n return\n plot_summary(data, run, OUT_DIR, SUPTITLE)\n\n\ndef plot_cor_ccd(a, img, TITLE, OUT_DIR, vmin=0, vmax=0.2):\n fig = plt.figure(figsize=(15, 15))\n seg = [0, 7, 8, 15]\n lab = [\"0\", \"7\", \"10\", \"17\"]\n for i, f in enumerate(img):\n ax1 = plt.subplot(3, 3, f.dev_index + 1)\n\n i_min = 16 * i\n i_max = i_min + 16\n aa = a[i_min:i_max, i_min:i_max]\n im = plt.imshow(aa, interpolation='nearest', cmap='jet', vmin=vmin, vmax=vmax)\n ax1.set_title(f.dev_name)\n ax1.set_xlim(15.5, -0.5)\n ax1.set_ylim(-0.5, 15.5)\n ax1.set_xticks(seg)\n ax1.set_xticklabels(lab)\n ax1.set_yticks(seg)\n ax1.set_yticklabels(lab)\n fig.subplots_adjust(right=0.8)\n cbar_ax = fig.add_axes([0.85, 0.137, 0.05, 0.73])\n fig.colorbar(im, cax=cbar_ax)\n fig.suptitle(\"Inter CCD correlations \" + TITLE, y=0.93, size=20)\n plt.savefig(OUT_DIR + TITLE + '_cor_ccd.png')\n plt.close(fig)\n\n\ndef plot_cor_all(a, img, TITLE, OUT_DIR, vmin=0, vmax=0.2):\n fig = plt.figure(figsize=(15, 15))\n im = plt.imshow(a, interpolation='nearest', cmap='jet', vmin=vmin, vmax=vmax)\n seg = np.arange(0, len(a), 16)\n r = img.ccd_num / 9.0\n plt.xticks(seg)\n plt.yticks(seg)\n\n for i, f in enumerate(img):\n plt.text(-10 * r, 8 + 16 * i, f.dev_name,\n size=15, verticalalignment='center')\n\n widthB = 54 / img.ccd_num\n widthB = str(widthB)\n\n for i in np.arange(0, img.ccd_num, 3):\n REB = 'REB' + img[i].dev_name[1:2]\n plt.annotate(REB, xy=(-11 * r, 24 + i * 16), xytext=(-18 * r, 24 + i * 16), xycoords='data',\n fontsize=20, annotation_clip=False, ha='center', va='center',\n arrowprops=dict(arrowstyle='-[, widthB=%s, lengthB=1.5' % widthB, lw=2.0))\n\n fig.subplots_adjust(right=0.82)\n cbar_ax = fig.add_axes([0.85, 0.155, 0.05, 0.695])\n fig.colorbar(im, cax=cbar_ax)\n fig.suptitle(\"Overall correlations \" + TITLE, y=0.91, size=20)\n plt.savefig(OUT_DIR + TITLE + '_cor_all.png')\n plt.close(fig)\n\ndef plot_cor_ccd_mean(a, img, TITLE, OUT_DIR, vmin=-1, vmax=1):\n fig = plt.figure(figsize=(15, 15))\n im = plt.imshow(a, interpolation='nearest', cmap='jet', vmin=vmin, vmax=vmax)\n\n loc = range(img.ccd_num)\n labels = []\n for fli in img:\n labels.append(fli.dev_name)\n\n plt.xticks(loc, labels)\n plt.yticks(loc, labels)\n\n fig.subplots_adjust(right=0.82)\n cbar_ax = fig.add_axes([0.85, 0.155, 0.05, 0.695])\n fig.colorbar(im, cax=cbar_ax)\n fig.suptitle(\"Correlations of means of CCDs \" + TITLE, y=0.91, size=20)\n plt.savefig(OUT_DIR + TITLE + '_cor_ccd_mean.png')\n plt.close(fig)\n\ndef plot_gains(gains, gain_ref, TITLES, OUT_DIR):\n \"\"\" plot gains with respect to the reference gain,\n whre reference gain is number => gains[gain_ref]\"\"\"\n\n# print 'directory: %s' % OUT_DIR\n# print 'TITLES:%s', TITLES\n\n gain_ref_np = np.array(gains[gain_ref].gain)\n ratios = []\n for gain in gains:\n gain_np = np.array(gain.gain)\n dim = (min(gain_ref_np.shape[0], gain_np.shape[0]),\n min(gain_ref_np.shape[1], gain_np.shape[1])\n )\n# print 'dim = ', dim\n ratios.append(gain_np[0:dim[0], 0:dim[1]] / gain_ref_np[0:dim[0], 0:dim[1]])\n\n# print 'Ratios = ', ratios\n\n rows = 2*((len(ratios) -1) / 6 + 1)\n cmap = plt.get_cmap('gnuplot')\n colors = [cmap(i) for i in np.linspace(0, 1, len(ratios))]\n fig, axes = plt.subplots(nrows=rows, ncols=6)\n fig.set_size_inches(20,20)\n axfl = axes.flatten()\n for i, ratio in enumerate(ratios):\n# print 'Plotting %s', TITLES[i]\n\tj = (i / 6)*12 + i % 6\n ax = axfl[j]\n ax2 = axfl[j+6]\n ax.hist(np.reshape(ratio, -1), 20, range=(0.9, 1.1), facecolor=colors[i])\n ax.set_title(TITLES[i], size=20)\n ax2.hist(np.reshape(ratio, -1), 50, range=(0., 2.), facecolor=colors[i])\n\n fig.suptitle(\"Gains with ref gain '%s'\" % TITLES[gain_ref], y=0.95, size=25)\n # fig.tight_layout()\n plt.savefig(OUT_DIR + 'gain.png')\n plt.close(fig)\n\ndef plot_raft_map(data, img, TITLE, OUTDIR, vmin=None, vmax=None):\n \"\"\" create a raft map 6x24 for data in CCDsx16 array \"\"\"\n\n map = np.zeros((6, 24))\n for i, fli in enumerate(img):\n x = (fli.dev_index / 3) * 2 # [0, 2, 4]\n y = (fli.dev_index % 3) * 8 # [0, 8, 16]\n for j in range(16):\n xx = x + j / 8 # [0, 1,..., 5]\n yy = y + j % 8 # [0, 1,..., 23]\n map[xx, yy] = data[i, j]\n\n yseg = range(6)\n ylab = [\"00-07\", \"10-17\", \"00-07\", \"10-17\", \"00-07\", \"10-17\"]\n xseg = range(0, 24, 4)\n xlab = [\"0\", \"4\", \"0\", \"4\", \"0\", \"4\"]\n\n fig = plt.figure(figsize=(10, 10))\n ax1 = fig.add_subplot(111)\n im = ax1.imshow(map, interpolation='nearest', cmap='jet', aspect=4, vmin=vmin, vmax=vmax)\n plt.yticks(yseg, ylab)\n plt.xticks(xseg, xlab)\n plt.annotate('S22', xy=(0, 0), xytext=(4, -0.8), fontsize=15, ha='center', va='center')\n plt.annotate('S12', xy=(0, 0), xytext=(12, -0.8), fontsize=15, ha='center', va='center')\n plt.annotate('S02', xy=(0, 0), xytext=(20, -0.8), fontsize=15, ha='center', va='center')\n plt.annotate('S02', xy=(0, 0), xytext=(24., 0.5), fontsize=15, ha='left', va='center')\n plt.annotate('S01', xy=(0, 0), xytext=(24., 2.5), fontsize=15, ha='left', va='center')\n plt.annotate('S00', xy=(0, 0), xytext=(24., 4.5), fontsize=15, ha='left', va='center')\n ax1.vlines(7.5, -0.5, 5.5)\n ax1.vlines(15.5, -0.5, 5.5)\n ax1.hlines(1.5, -0.5, 23.5)\n ax1.hlines(3.5, -0.5, 23.5)\n plt.subplots_adjust(left=0.07, bottom=0.05, right=0.8, top=0.95, wspace=0, hspace=0)\n #cbar_ax = fig.add_axes([0.15, 0.03, 0.7, 0.05])\n #fig.colorbar(im, cax=cbar_ax, orientation=\"horizontal\")\n cbar_ax = fig.add_axes([0.87, 0.15, 0.05, 0.7])\n fig.colorbar(im, cax=cbar_ax)\n fig.suptitle(TITLE, y=0.98, size=19)\n plt.savefig(OUTDIR + TITLE + '.png')\n plt.show()\n plt.close(fig)\n\ndef plot_voltage_all(x, data, imgs, title, out_dir, suptitle=''):\n if suptitle == '':\n suptitle = title\n fig = plt.figure(figsize=(20, 24))\n\n cmap = plt.get_cmap('gist_ncar')\n colors = [cmap(i) for i in np.linspace(0, 1, 16)]\n\n for k in range(9):\n ax1 = plt.subplot(3, 3, imgs[0][k].dev_index + 1)\n ax1.set_title(imgs[0][k].dev_name)\n for j in range(16):\n y = []\n for i in range(len(x)):\n y.append(data[i][k][j])\n plt.plot(x, y, label='Segment %i' % j, color=colors[j])\n\n fig.suptitle(suptitle + '; all segments', y=0.99, size=20)\n plt.legend(loc='lower left', bbox_to_anchor=(0.87, 1.1), ncol=4)\n plt.subplots_adjust(bottom=0.04, left=0.04, top=0.88, right=0.96, wspace=0.1, hspace=0.1)\n plt.savefig(out_dir + title + '_all.png')\n plt.close(fig)\n\ndef plot_voltage_ccd(x, data, imgs, title, out_dir, suptitle=''):\n if suptitle == '':\n suptitle = title\n fig = plt.figure(figsize=(15, 15))\n for k in range(9):\n ax1 = plt.subplot(3, 3, imgs[0][k].dev_index + 1) \n ax1.set_title(imgs[0][k].dev_name)\n y = []\n for i in range(len(x)):\n y.append(np.mean(data[i][k]))\n \n plt.plot(x, y)\n \n fig.suptitle(suptitle + '; mean of segments, per CCD', y=0.94, size=20)\n plt.savefig(out_dir + title + '_CCD.png')\n plt.close(fig)\n\ndef plot_voltage_raft(x, data, imgs, title, out_dir, suptitle=''):\n if suptitle == '':\n suptitle = title\n fig = plt.figure(figsize=(7, 7))\n y = []\n for i in range(len(x)):\n y.append(np.mean(data[i]))\n plt.plot(x, y)\n\n fig.suptitle(suptitle + '; mean of all segments', y=0.96, size=20)\n plt.savefig(out_dir + title + '_raft.png')\n plt.close(fig)\n\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
# -*- coding: utf-8 -*-
import os
import sys
import base64
import cdutil
import json
import os
from array import array
from uuid import uuid4
import cdms2
import numpy as np
import matplotlib as mpl
mpl.rcParams['mathtext.default'] = 'regular'
mpl.use('qt4agg')
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from __init__ import WebSocketNode, NodeSlot, startNode, TEMP_DIR
userdata = {}
class StreamWorker(WebSocketNode):
def nodeFileName(self):
return 'streamworker'
@NodeSlot
def loadData(self, filename, var, userkey):
if userkey not in userdata:
userdata[userkey] = {}
f = cdms2.open(filename, 'r')
userdata[userkey]['var'] = cdmsVar = f[var]
userdata[userkey]['latCoords'] = cdmsVar.getLatitude().getValue()
userdata[userkey]['lonCoords'] = cdmsVar.getLongitude().getValue()
userdata[userkey]['clevs'] = range(-1, 100, 10) # TODO: user defined
return None
@NodeSlot
def region(self, latBounds, lonBounds, i, userkey):
cdmsVar = userdata[userkey]['var']
latCoords = userdata[userkey]['latCoords']
lonCoords = userdata[userkey]['lonCoords']
clevs = userdata[userkey]['clevs']
#self.debug("get data for only this region")
# need to expand bounds by one due to the difference in how
# basemap and cdms work with bounds
t = len(latCoords) - 1
n = len(lonCoords) - 1
a, b, c, d = latBounds[0], latBounds[1], lonBounds[0], lonBounds[1]
regiondata = cdmsVar[:, (a - 1 if a > 0 else a):(b + 1 if b < t else b), (c - 1 if c > 0 else c):(d + 1 if d < n else d)]
#self.debug("perform time average on data")
cdutil.setTimeBoundsMonthly(regiondata)
avg = cdutil.averager(regiondata, axis='t')
# setup figure to have no borders
fig = plt.figure(figsize=((d - c) * 0.15, (b - a) * 0.1), frameon=False)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
#self.debug("plot using basemap")
lons, lats = avg.getLongitude()[:], avg.getLatitude()[:]
m = Basemap(projection='cyl', resolution='c',
llcrnrlon=lonCoords[lonBounds[0]],
llcrnrlat=latCoords[latBounds[0]],
urcrnrlon=lonCoords[lonBounds[1]],
urcrnrlat=latCoords[latBounds[1]], fix_aspect=False)
x, y = m(*np.meshgrid(lons, lats))
try:
m.contourf(x, y, avg.asma(), clevs, cmap=plt.cm.RdBu_r, extend='both')
except Exception, err:
import traceback
tb = traceback.format_exc()
self.debug(tb)
self.debug("Region lat(%d,%d) lon(%d,%d) faled" % (latBounds[0], latBounds[1], lonBounds[0], lonBounds[1]))
m.drawcoastlines()
#self.debug("save to temp file")
temp_image_file = os.path.join(TEMP_DIR, '%s.png' % str(uuid4()))
fig.savefig(temp_image_file, dpi=100)
#self.debug("convert image data to base64")
with open(temp_image_file, "rb") as temp_image:
base64png = base64.b64encode(temp_image.read())
self.signal('streammaster', 'region', base64png, i, userkey)
# cleanup
plt.clf()
os.remove(temp_image_file)
return None
if __name__ == '__main__':
startNode(StreamWorker)
|
normal
|
{
"blob_id": "ff9376ab4d6a88849167fb6e180fd9c4f9ab4dad",
"index": 8283,
"step-1": " # -*- coding: utf-8 -*-\nimport os\nimport sys\n\nimport base64\nimport cdutil\nimport json\nimport os\nfrom array import array\nfrom uuid import uuid4\n\nimport cdms2\nimport numpy as np\nimport matplotlib as mpl\nmpl.rcParams['mathtext.default'] = 'regular'\nmpl.use('qt4agg')\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.basemap import Basemap\n\nfrom __init__ import WebSocketNode, NodeSlot, startNode, TEMP_DIR\n\nuserdata = {}\n\nclass StreamWorker(WebSocketNode):\n\n def nodeFileName(self):\n return 'streamworker'\n\n @NodeSlot\n def loadData(self, filename, var, userkey):\n if userkey not in userdata:\n userdata[userkey] = {}\n f = cdms2.open(filename, 'r')\n userdata[userkey]['var'] = cdmsVar = f[var]\n userdata[userkey]['latCoords'] = cdmsVar.getLatitude().getValue()\n userdata[userkey]['lonCoords'] = cdmsVar.getLongitude().getValue()\n userdata[userkey]['clevs'] = range(-1, 100, 10) # TODO: user defined\n return None\n\n @NodeSlot\n def region(self, latBounds, lonBounds, i, userkey):\n\n cdmsVar = userdata[userkey]['var']\n latCoords = userdata[userkey]['latCoords']\n lonCoords = userdata[userkey]['lonCoords']\n clevs = userdata[userkey]['clevs']\n\n #self.debug(\"get data for only this region\")\n # need to expand bounds by one due to the difference in how\n # basemap and cdms work with bounds\n t = len(latCoords) - 1\n n = len(lonCoords) - 1\n a, b, c, d = latBounds[0], latBounds[1], lonBounds[0], lonBounds[1]\n regiondata = cdmsVar[:, (a - 1 if a > 0 else a):(b + 1 if b < t else b), (c - 1 if c > 0 else c):(d + 1 if d < n else d)]\n\n #self.debug(\"perform time average on data\")\n cdutil.setTimeBoundsMonthly(regiondata)\n avg = cdutil.averager(regiondata, axis='t')\n\n # setup figure to have no borders\n fig = plt.figure(figsize=((d - c) * 0.15, (b - a) * 0.1), frameon=False)\n ax = plt.Axes(fig, [0., 0., 1., 1.])\n ax.set_axis_off()\n fig.add_axes(ax)\n\n #self.debug(\"plot using basemap\")\n lons, lats = avg.getLongitude()[:], avg.getLatitude()[:]\n m = Basemap(projection='cyl', resolution='c',\n llcrnrlon=lonCoords[lonBounds[0]],\n llcrnrlat=latCoords[latBounds[0]],\n urcrnrlon=lonCoords[lonBounds[1]],\n urcrnrlat=latCoords[latBounds[1]], fix_aspect=False)\n x, y = m(*np.meshgrid(lons, lats))\n\n try:\n m.contourf(x, y, avg.asma(), clevs, cmap=plt.cm.RdBu_r, extend='both')\n except Exception, err:\n import traceback\n tb = traceback.format_exc()\n self.debug(tb)\n self.debug(\"Region lat(%d,%d) lon(%d,%d) faled\" % (latBounds[0], latBounds[1], lonBounds[0], lonBounds[1]))\n\n m.drawcoastlines()\n\n #self.debug(\"save to temp file\")\n temp_image_file = os.path.join(TEMP_DIR, '%s.png' % str(uuid4()))\n fig.savefig(temp_image_file, dpi=100)\n\n #self.debug(\"convert image data to base64\")\n with open(temp_image_file, \"rb\") as temp_image:\n base64png = base64.b64encode(temp_image.read())\n\n self.signal('streammaster', 'region', base64png, i, userkey)\n\n # cleanup\n plt.clf()\n os.remove(temp_image_file)\n\n return None\n\nif __name__ == '__main__':\n startNode(StreamWorker)\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|>
if __name__ == '__main__':
counter1 = Hmm(3)
input_counts = open('gene_NoClass.counts', 'r')
dev_file = open('gene.dev', 'r+')
output_file2 = open('gene_dev.NoClass.out.p2', 'w')
print('dev_file read')
print('start training viterbi')
counter1.train_viterbi(input_counts, dev_file, output_file2)
print('finished training in viterbi')
dev_file.close()
output_file2.close()
input_counts.close()
print('gene_dev.p2.out file created')
"""
if len(sys.argv)!=3:
usage()
sys.exit(1)
gs_iterator = corpus_iterator(open(sys.argv[1]))
pred_iterator = corpus_iterator(open(sys.argv[4]), with_logprob = False)
evaluator = Evaluator()
evaluator.compare(gs_iterator, pred_iterator)
evaluator.print_scores()
"""
<|reserved_special_token_1|>
from count_freqs import *
from eval_gene_tagger import *
<|reserved_special_token_0|>
if __name__ == '__main__':
counter1 = Hmm(3)
input_counts = open('gene_NoClass.counts', 'r')
dev_file = open('gene.dev', 'r+')
output_file2 = open('gene_dev.NoClass.out.p2', 'w')
print('dev_file read')
print('start training viterbi')
counter1.train_viterbi(input_counts, dev_file, output_file2)
print('finished training in viterbi')
dev_file.close()
output_file2.close()
input_counts.close()
print('gene_dev.p2.out file created')
"""
if len(sys.argv)!=3:
usage()
sys.exit(1)
gs_iterator = corpus_iterator(open(sys.argv[1]))
pred_iterator = corpus_iterator(open(sys.argv[4]), with_logprob = False)
evaluator = Evaluator()
evaluator.compare(gs_iterator, pred_iterator)
evaluator.print_scores()
"""
<|reserved_special_token_1|>
from count_freqs import *
from eval_gene_tagger import *
'''
Using gene.train gene.counts prediction file to evaluate the performance
Usage: python viterbi.py gene.counts gene.dev gene_dev.p1.out
'''
if __name__ == "__main__":
#if len(sys.argv)!=2: # Expect exactly one argument: the training data file
# usage()
# sys.exit(2)
#try:
# input_counts = open(sys.argv[1],"r")
# dev_file = open(sys.argv[2],"r+")
# output_file2 = open(sys.argv[3],"w")
#except IOError:
# sys.stderr.write("ERROR: Cannot read inputfile %s.\n" % arg)
# sys.exit(1)
########### Read gene.counts and write prediction into 'gene_dev.p1.out' #########
counter1 = Hmm(3)
input_counts = open('gene_NoClass.counts','r')
dev_file = open('gene.dev',"r+")
output_file2 = open('gene_dev.NoClass.out.p2',"w")
print('dev_file read')
print('start training viterbi')
counter1.train_viterbi( input_counts, dev_file, output_file2)
print('finished training in viterbi')
dev_file.close()
output_file2.close()
input_counts.close()
print("gene_dev.p2.out file created")
######### Evaluate the result ############
'''
if len(sys.argv)!=3:
usage()
sys.exit(1)
gs_iterator = corpus_iterator(open(sys.argv[1]))
pred_iterator = corpus_iterator(open(sys.argv[4]), with_logprob = False)
evaluator = Evaluator()
evaluator.compare(gs_iterator, pred_iterator)
evaluator.print_scores()
'''
|
flexible
|
{
"blob_id": "6dda23cc5d0083e72520b0664b6550ccb48e4b4f",
"index": 7288,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif __name__ == '__main__':\n counter1 = Hmm(3)\n input_counts = open('gene_NoClass.counts', 'r')\n dev_file = open('gene.dev', 'r+')\n output_file2 = open('gene_dev.NoClass.out.p2', 'w')\n print('dev_file read')\n print('start training viterbi')\n counter1.train_viterbi(input_counts, dev_file, output_file2)\n print('finished training in viterbi')\n dev_file.close()\n output_file2.close()\n input_counts.close()\n print('gene_dev.p2.out file created')\n \"\"\"\n if len(sys.argv)!=3:\n usage()\n sys.exit(1)\n gs_iterator = corpus_iterator(open(sys.argv[1]))\n pred_iterator = corpus_iterator(open(sys.argv[4]), with_logprob = False)\n evaluator = Evaluator()\n evaluator.compare(gs_iterator, pred_iterator)\n evaluator.print_scores()\n\n \"\"\"\n",
"step-3": "from count_freqs import *\nfrom eval_gene_tagger import *\n<mask token>\nif __name__ == '__main__':\n counter1 = Hmm(3)\n input_counts = open('gene_NoClass.counts', 'r')\n dev_file = open('gene.dev', 'r+')\n output_file2 = open('gene_dev.NoClass.out.p2', 'w')\n print('dev_file read')\n print('start training viterbi')\n counter1.train_viterbi(input_counts, dev_file, output_file2)\n print('finished training in viterbi')\n dev_file.close()\n output_file2.close()\n input_counts.close()\n print('gene_dev.p2.out file created')\n \"\"\"\n if len(sys.argv)!=3:\n usage()\n sys.exit(1)\n gs_iterator = corpus_iterator(open(sys.argv[1]))\n pred_iterator = corpus_iterator(open(sys.argv[4]), with_logprob = False)\n evaluator = Evaluator()\n evaluator.compare(gs_iterator, pred_iterator)\n evaluator.print_scores()\n\n \"\"\"\n",
"step-4": "from count_freqs import *\nfrom eval_gene_tagger import *\n'''\nUsing gene.train gene.counts prediction file to evaluate the performance\n\nUsage: python viterbi.py gene.counts gene.dev gene_dev.p1.out \n'''\n\nif __name__ == \"__main__\":\n\n #if len(sys.argv)!=2: # Expect exactly one argument: the training data file\n # usage()\n # sys.exit(2)\n\n #try:\n # input_counts = open(sys.argv[1],\"r\")\n # dev_file = open(sys.argv[2],\"r+\")\n # output_file2 = open(sys.argv[3],\"w\")\n #except IOError:\n # sys.stderr.write(\"ERROR: Cannot read inputfile %s.\\n\" % arg)\n # sys.exit(1)\n\n \n \n\n\n ########### Read gene.counts and write prediction into 'gene_dev.p1.out' #########\n\n counter1 = Hmm(3)\n input_counts = open('gene_NoClass.counts','r')\n dev_file = open('gene.dev',\"r+\")\n output_file2 = open('gene_dev.NoClass.out.p2',\"w\")\n print('dev_file read')\n print('start training viterbi')\n\n\n counter1.train_viterbi( input_counts, dev_file, output_file2)\n print('finished training in viterbi')\n dev_file.close()\n output_file2.close()\n input_counts.close()\n print(\"gene_dev.p2.out file created\")\n\n\n\n\n\n\n\n ######### Evaluate the result ############\n\n\n '''\n if len(sys.argv)!=3:\n usage()\n sys.exit(1)\n gs_iterator = corpus_iterator(open(sys.argv[1]))\n pred_iterator = corpus_iterator(open(sys.argv[4]), with_logprob = False)\n evaluator = Evaluator()\n evaluator.compare(gs_iterator, pred_iterator)\n evaluator.print_scores()\n\n '''",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
class TeacherGUI:
<|reserved_special_token_0|>
@classmethod
def setup(cls, ui_mainwindow):
cls.__ui_mainwindow = ui_mainwindow
@classmethod
def display_all_active_school_classes(cls, school_classes):
cls.__ui_mainwindow.tableWidget_14.clear()
row = 0
col = 0
for school_class_id, in school_classes:
school_class_text = 'Class ' + str(school_class_id)
school_class_item = QTableWidgetItem(school_class_text)
cls.__ui_mainwindow.tableWidget_14.setItem(row, col,
school_class_item)
if col >= 4:
col = 0
row += 1
else:
col += 1
<|reserved_special_token_0|>
@classmethod
def display_not_completed_exams(cls, not_completed_exams):
cls.__ui_mainwindow.tableWidget_16.clear()
row = 0
col = 0
for exam_id, in not_completed_exams:
exam_text = 'Exam ' + str(exam_id)
exam_item = QTableWidgetItem(exam_text)
cls.__ui_mainwindow.tableWidget_16.setItem(row, col, exam_item)
if col >= 6:
col = 0
row += 1
else:
col += 1
@classmethod
def display_ready_to_be_marked_exams(cls, ready_to_be_marked_exams):
cls.__ui_mainwindow.tableWidget_17.clear()
row = 0
col = 0
for exam_id, in ready_to_be_marked_exams:
exam_text = 'Exam ' + str(exam_id)
exam_item = QTableWidgetItem(exam_text)
cls.__ui_mainwindow.tableWidget_17.setItem(row, col, exam_item)
if col >= 3:
col = 0
row += 1
else:
col += 1
<|reserved_special_token_0|>
@classmethod
def display_multiple_answers_question_dialog_preview(cls):
question_body = cls.__ui_mainwindow.textEdit_14.toPlainText()
option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText()
option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText()
option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText()
option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText()
option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText()
cls.__dialog = QtWidgets.QDialog()
cls.__ui_dialog = Ui_MultipleAnswersQuestionDialog()
cls.__ui_dialog.setupUi(cls.__dialog)
cls.__ui_dialog.label.setText(question_body)
cls.__ui_dialog.label_3.setText(option_A_text)
cls.__ui_dialog.label_4.setText(option_B_text)
cls.__ui_dialog.label_5.setText(option_C_text)
cls.__ui_dialog.label_6.setText(option_D_text)
cls.__ui_dialog.label_7.setText(option_E_text)
cls.__dialog.show()
cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)
@classmethod
def display_essay_question_dialog_preview(cls):
question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()
cls.__dialog = QtWidgets.QDialog()
cls.__ui_dialog = Ui_EssayQuestionDialog()
cls.__ui_dialog.setupUi(cls.__dialog)
if question_body == '':
cls.__ui_dialog.label.setText('Question Body')
else:
cls.__ui_dialog.label.setText(question_body)
cls.__dialog.show()
cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)
@classmethod
def close_dialog(cls):
cls.__dialog.close()
@classmethod
def get_single_answer_question_details(cls):
question_body = cls.__ui_mainwindow.textEdit.toPlainText()
if question_body == '':
return None
option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()
if option_A_text == '':
return None
option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()
if option_B_text == '':
return None
option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()
if option_C_text == '':
return None
option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()
if option_D_text == '':
return None
option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()
if option_E_text == '':
return None
year_level_text = cls.__ui_mainwindow.lineEdit_3.text()
if year_level_text == '':
return None
try:
year_level = int(year_level_text)
except:
return None
phrase_tag_text = cls.__ui_mainwindow.lineEdit_4.text()
if phrase_tag_text == '':
return None
correct_answers_list = []
if cls.__ui_mainwindow.radioButton.isChecked():
correct_answers_list.append('A')
if cls.__ui_mainwindow.radioButton_2.isChecked():
correct_answers_list.append('B')
if cls.__ui_mainwindow.radioButton_5.isChecked():
correct_answers_list.append('C')
if cls.__ui_mainwindow.radioButton_3.isChecked():
correct_answers_list.append('D')
if cls.__ui_mainwindow.radioButton_4.isChecked():
correct_answers_list.append('E')
if correct_answers_list == []:
return None
if len(correct_answers_list) > 1:
return None
return (question_body, option_A_text, option_B_text, option_C_text,
option_D_text, option_E_text, year_level, phrase_tag_text,
correct_answers_list)
<|reserved_special_token_0|>
@classmethod
def get_essay_question_details(cls):
question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()
if question_body == '':
return None
year_level_text = cls.__ui_mainwindow.lineEdit_26.text()
if year_level_text == '':
return None
try:
year_level = int(year_level_text)
except:
return None
phrase_tag_text = cls.__ui_mainwindow.lineEdit_27.text()
if phrase_tag_text == '':
return None
return question_body, year_level, phrase_tag_text
@classmethod
def display_all_active_questions(cls, active_questions_tuple):
row = 0
col = 0
for question_pk_tuple in active_questions_tuple:
question_pk = question_pk_tuple[0]
question_text = 'Question ' + str(question_pk)
question_item = QTableWidgetItem(question_text)
cls.__ui_mainwindow.tableWidget.setItem(row, col, question_item)
if col >= 7:
col = 0
row += 1
else:
col += 1
<|reserved_special_token_0|>
@classmethod
def display_invalid_single_answer_question_creation_message(cls):
cls.__ui_mainwindow.label_4.setText(
'Invalid Single Answer Question Creation')
@classmethod
def display_create_multiple_answers_question_success(cls):
cls.__ui_mainwindow.label_11.setText(
'Create Multiple Answers Question Success')
@classmethod
def display_invalid_multiple_answers_question_creation_message(cls):
cls.__ui_mainwindow.label_11.setText(
'Invalid Multiple Answers Question Creation')
@classmethod
def display_invalid_essay_question_creation_message(cls):
cls.__ui_mainwindow.label_42.setText('Invalid Essay Question Creation')
@classmethod
def display_create_essay_question_success(cls):
cls.__ui_mainwindow.label_42.setText('Create Essay Question Success')
@classmethod
def display_invalid_modification_message(cls):
cls.__ui_mainwindow.label_57.setText('Invalid Modification')
@classmethod
def refresh_create_single_answer_question_page(cls):
cls.__ui_mainwindow.textEdit.clear()
cls.__ui_mainwindow.textEdit_2.clear()
cls.__ui_mainwindow.textEdit_3.clear()
cls.__ui_mainwindow.textEdit_4.clear()
cls.__ui_mainwindow.textEdit_5.clear()
cls.__ui_mainwindow.textEdit_6.clear()
cls.__ui_mainwindow.lineEdit_3.clear()
cls.__ui_mainwindow.lineEdit_4.clear()
cls.__ui_mainwindow.radioButton.setChecked(False)
cls.__ui_mainwindow.radioButton_2.setChecked(False)
cls.__ui_mainwindow.radioButton_3.setChecked(False)
cls.__ui_mainwindow.radioButton_4.setChecked(False)
cls.__ui_mainwindow.radioButton_5.setChecked(False)
<|reserved_special_token_0|>
@classmethod
def refresh_view_or_modify_question_page(cls):
cls.__ui_mainwindow.lineEdit_5.clear()
cls.__ui_mainwindow.label_45.setText('Question ID: ')
cls.__ui_mainwindow.label_47.setText('Question Type: ')
cls.__ui_mainwindow.label_57.clear()
cls.__ui_mainwindow.label_12.clear()
cls.__ui_mainwindow.textEdit_7.clear()
cls.__ui_mainwindow.textEdit_8.clear()
cls.__ui_mainwindow.textEdit_9.clear()
cls.__ui_mainwindow.textEdit_10.clear()
cls.__ui_mainwindow.textEdit_11.clear()
cls.__ui_mainwindow.textEdit_20.clear()
cls.__ui_mainwindow.lineEdit_6.clear()
cls.__ui_mainwindow.lineEdit_8.clear()
cls.__ui_mainwindow.lineEdit_28.clear()
cls.__ui_mainwindow.radioButton_6.setDisabled(False)
cls.__ui_mainwindow.radioButton_7.setDisabled(False)
cls.__ui_mainwindow.radioButton_8.setDisabled(False)
cls.__ui_mainwindow.radioButton_9.setDisabled(False)
cls.__ui_mainwindow.radioButton_10.setDisabled(False)
cls.__ui_mainwindow.textEdit_8.setDisabled(False)
cls.__ui_mainwindow.textEdit_9.setDisabled(False)
cls.__ui_mainwindow.textEdit_10.setDisabled(False)
cls.__ui_mainwindow.textEdit_11.setDisabled(False)
cls.__ui_mainwindow.textEdit_20.setDisabled(False)
cls.__ui_mainwindow.radioButton_6.setAutoExclusive(False)
cls.__ui_mainwindow.radioButton_6.setChecked(False)
cls.__ui_mainwindow.radioButton_7.setAutoExclusive(False)
cls.__ui_mainwindow.radioButton_7.setChecked(False)
cls.__ui_mainwindow.radioButton_8.setAutoExclusive(False)
cls.__ui_mainwindow.radioButton_8.setChecked(False)
cls.__ui_mainwindow.radioButton_9.setAutoExclusive(False)
cls.__ui_mainwindow.radioButton_9.setChecked(False)
cls.__ui_mainwindow.radioButton_10.setAutoExclusive(False)
cls.__ui_mainwindow.radioButton_10.setChecked(False)
@classmethod
def refresh_create_essay_question_page(cls):
cls.__ui_mainwindow.textEdit_19.clear()
cls.__ui_mainwindow.lineEdit_26.clear()
cls.__ui_mainwindow.lineEdit_27.clear()
@classmethod
def refresh_create_exam_page(cls):
cls.__ui_mainwindow.tableWidget_3.clear()
cls.__ui_mainwindow.tableWidget_4.clear()
cls.__ui_mainwindow.lineEdit_10.clear()
cls.__ui_mainwindow.lineEdit_11.clear()
cls.__ui_mainwindow.lineEdit_12.clear()
cls.__ui_mainwindow.lineEdit_13.clear()
@classmethod
def get_question_id_to_load(cls):
question_id_text = cls.__ui_mainwindow.lineEdit_5.text()
try:
question_id = int(question_id_text)
return question_id
except:
return None
@classmethod
def load_single_answer_question_details(cls, question_details):
question_id = question_details[0]
question_type = question_details[1]
points = question_details[2]
year_level = question_details[3]
question_tag = question_details[4]
question_body = question_details[5]
option_A_text = question_details[6]
option_B_text = question_details[7]
option_C_text = question_details[8]
option_D_text = question_details[9]
option_E_text = question_details[10]
correct_answer = question_details[11]
cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)
)
cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(
question_type))
cls.__ui_mainwindow.textEdit_7.setText(question_body)
cls.__ui_mainwindow.textEdit_8.setText(option_A_text)
cls.__ui_mainwindow.textEdit_9.setText(option_B_text)
cls.__ui_mainwindow.textEdit_10.setText(option_C_text)
cls.__ui_mainwindow.textEdit_11.setText(option_D_text)
cls.__ui_mainwindow.textEdit_20.setText(option_E_text)
cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))
cls.__ui_mainwindow.lineEdit_8.setText(question_tag)
cls.__ui_mainwindow.lineEdit_28.setText(str(points))
if correct_answer == 'A':
cls.__ui_mainwindow.radioButton_6.setChecked(True)
elif correct_answer == 'B':
cls.__ui_mainwindow.radioButton_7.setChecked(True)
elif correct_answer == 'C':
cls.__ui_mainwindow.radioButton_8.setChecked(True)
elif correct_answer == 'D':
cls.__ui_mainwindow.radioButton_9.setChecked(True)
elif correct_answer == 'E':
cls.__ui_mainwindow.radioButton_10.setChecked(True)
@classmethod
def load_multiple_answers_question_details(cls, question_details):
question_id = question_details[0]
question_type = question_details[1]
points = question_details[2]
year_level = question_details[3]
question_tag = question_details[4]
question_body = question_details[5]
option_A_text = question_details[6]
option_B_text = question_details[7]
option_C_text = question_details[8]
option_D_text = question_details[9]
option_E_text = question_details[10]
correct_answers = question_details[11]
cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)
)
cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(
question_type))
cls.__ui_mainwindow.textEdit_7.setText(question_body)
cls.__ui_mainwindow.textEdit_8.setText(option_A_text)
cls.__ui_mainwindow.textEdit_9.setText(option_B_text)
cls.__ui_mainwindow.textEdit_10.setText(option_C_text)
cls.__ui_mainwindow.textEdit_11.setText(option_D_text)
cls.__ui_mainwindow.textEdit_20.setText(option_E_text)
cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))
cls.__ui_mainwindow.lineEdit_8.setText(question_tag)
cls.__ui_mainwindow.lineEdit_28.setText(str(points))
if correct_answers.count('A') == 1:
cls.__ui_mainwindow.radioButton_6.setChecked(True)
if correct_answers.count('B') == 1:
cls.__ui_mainwindow.radioButton_7.setChecked(True)
if correct_answers.count('C') == 1:
cls.__ui_mainwindow.radioButton_8.setChecked(True)
if correct_answers.count('D') == 1:
cls.__ui_mainwindow.radioButton_9.setChecked(True)
if correct_answers.count('E') == 1:
cls.__ui_mainwindow.radioButton_10.setChecked(True)
@classmethod
def load_essay_question_details(cls, question_details):
question_id = question_details[0]
question_type = question_details[1]
points = question_details[2]
year_level = question_details[3]
question_tag = question_details[4]
question_body = question_details[5]
cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)
)
cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(
question_type))
cls.__ui_mainwindow.textEdit_7.setText(question_body)
cls.__ui_mainwindow.radioButton_6.setDisabled(True)
cls.__ui_mainwindow.radioButton_7.setDisabled(True)
cls.__ui_mainwindow.radioButton_8.setDisabled(True)
cls.__ui_mainwindow.radioButton_9.setDisabled(True)
cls.__ui_mainwindow.radioButton_10.setDisabled(True)
cls.__ui_mainwindow.textEdit_8.setDisabled(True)
cls.__ui_mainwindow.textEdit_9.setDisabled(True)
cls.__ui_mainwindow.textEdit_10.setDisabled(True)
cls.__ui_mainwindow.textEdit_11.setDisabled(True)
cls.__ui_mainwindow.textEdit_20.setDisabled(True)
cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))
cls.__ui_mainwindow.lineEdit_8.setText(question_tag)
cls.__ui_mainwindow.lineEdit_28.setText(str(points))
@classmethod
def display_question_id_invalid_to_load_message(cls):
cls.__ui_mainwindow.label_12.setText('Invalid Question ID To Load')
@classmethod
def display_modification_success_message(cls):
cls.__ui_mainwindow.label_57.setText('Modification Success')
@classmethod
def display_invalid_school_class_id_message(cls):
cls.__ui_mainwindow.label_14.setText('Invalid School Class ID')
cls.__ui_mainwindow.tableWidget_15.clear()
@classmethod
def get_question_type_to_modify(cls):
question_type_text = cls.__ui_mainwindow.label_47.text()
if question_type_text == 'Question Type: Single Answer':
return 'Single Answer'
elif question_type_text == 'Question Type: Multiple Answers':
return 'Multiple Answers'
elif question_type_text == 'Question Type: Essay':
return 'Essay'
@classmethod
def get_single_answer_question_details_to_modify(cls):
question_pk = cls.get_question_id_to_modify()
question_type = cls.get_question_type_to_modify()
points = int(cls.__ui_mainwindow.lineEdit_28.text())
year_level = int(cls.__ui_mainwindow.lineEdit_6.text())
question_tag = cls.__ui_mainwindow.lineEdit_8.text()
question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()
option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()
option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()
option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()
option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()
option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()
correct_answer = cls.get_single_correct_answer_to_modify()
if correct_answer == None:
return None
return (question_pk, question_type, points, year_level,
question_tag, question_body, option_A_text, option_B_text,
option_C_text, option_D_text, option_E_text, correct_answer)
@classmethod
def get_multiple_answers_question_details_to_modify(cls):
question_pk = cls.get_question_id_to_modify()
question_type = cls.get_question_type_to_modify()
points = int(cls.__ui_mainwindow.lineEdit_28.text())
year_level = int(cls.__ui_mainwindow.lineEdit_6.text())
question_tag = cls.__ui_mainwindow.lineEdit_8.text()
question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()
option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()
option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()
option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()
option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()
option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()
correct_answers = cls.get_multiple_correct_answers_to_modify()
if correct_answers == None:
return None
return (question_pk, question_type, points, year_level,
question_tag, question_body, option_A_text, option_B_text,
option_C_text, option_D_text, option_E_text, correct_answers)
@classmethod
def get_essay_question_details_to_modify(cls):
question_pk = cls.get_question_id_to_modify()
question_type = cls.get_question_type_to_modify()
try:
points = int(cls.__ui_mainwindow.lineEdit_28.text())
except:
return None
try:
year_level = int(cls.__ui_mainwindow.lineEdit_6.text())
except:
return None
question_tag = cls.__ui_mainwindow.lineEdit_8.text()
if question_tag == '':
return None
question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()
if question_body == '':
return None
return (question_pk, question_type, points, year_level,
question_tag, question_body)
@classmethod
def get_question_id_to_modify(cls):
question_id_text = cls.__ui_mainwindow.label_45.text()
question_id_text_split = question_id_text.split()
question_id = int(question_id_text_split.pop())
return question_id
<|reserved_special_token_0|>
@classmethod
def get_multiple_correct_answers_to_modify(cls):
correct_answers = ''
if cls.__ui_mainwindow.radioButton_6.isChecked():
correct_answers = correct_answers + 'A'
if cls.__ui_mainwindow.radioButton_7.isChecked():
correct_answers = correct_answers + 'B'
if cls.__ui_mainwindow.radioButton_8.isChecked():
correct_answers = correct_answers + 'C'
if cls.__ui_mainwindow.radioButton_9.isChecked():
correct_answers = correct_answers + 'D'
if cls.__ui_mainwindow.radioButton_10.isChecked():
correct_answers = correct_answers + 'E'
if len(correct_answers) == 0:
return None
if len(correct_answers) > 4:
return None
return correct_answers
@classmethod
def get_school_class_id_to_view_students(cls):
school_class_id_text = cls.__ui_mainwindow.lineEdit_9.text()
try:
school_class_id = int(school_class_id_text)
return school_class_id
except:
return None
@classmethod
def display_school_class_details(cls, school_class_details):
cls.__ui_mainwindow.tableWidget_15.clear()
row = 0
col = 0
for student, in school_class_details:
student_item = QTableWidgetItem(student)
cls.__ui_mainwindow.tableWidget_15.setItem(row, col, student_item)
if col >= 1:
col = 0
row += 1
else:
col += 1
@classmethod
def refresh_view_school_class_details_page(cls):
cls.__ui_mainwindow.label_14.clear()
<|reserved_special_token_0|>
@classmethod
def get_number_of_school_classes_in_current_exam(cls):
number_of_school_classes = 0
row = 0
col = 0
for counter in range(5):
if cls.__ui_mainwindow.tableWidget_4.item(row, col) != None:
number_of_school_classes += 1
row += 1
return number_of_school_classes
@classmethod
def display_number_of_questions_full_in_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText(
'Questions Are Full In Current Exam')
@classmethod
def display_number_of_school_classes_full_in_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText(
'School Classes Are Full In Current Exam')
@classmethod
def display_no_question_in_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText('No Question In Current Exam')
@classmethod
def display_no_school_class_in_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText('No School Class In Current Exam')
<|reserved_special_token_0|>
@classmethod
def display_school_class_id_already_added_to_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText(
'School Class ID Already Added To Current Exam')
@classmethod
def display_question_id_invalid_message(cls):
cls.__ui_mainwindow.label_17.setText('Question ID Invalid')
@classmethod
def display_school_class_id_invalid_message(cls):
cls.__ui_mainwindow.label_17.setText('School CLass ID Invalid')
@classmethod
def display_question_id_not_already_in_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText(
'Question ID Not Aleady In Current Exam')
<|reserved_special_token_0|>
@classmethod
def display_create_exam_success_message(cls):
cls.__ui_mainwindow.label_17.setText('Create Exam Success')
@classmethod
def refresh_mark_exam_drop_box(cls):
cls.__ui_mainwindow.tableWidget_19.clear()
@classmethod
def get_question_id_to_add_to_exam(cls):
question_id_text = cls.__ui_mainwindow.lineEdit_10.text()
try:
question_id = int(question_id_text)
return question_id
except:
return None
<|reserved_special_token_0|>
<|reserved_special_token_0|>
@classmethod
def get_school_class_id_to_remove_from_exam(cls):
school_class_id_text = cls.__ui_mainwindow.lineEdit_13.text()
try:
school_class_id = int(school_class_id_text)
return school_class_id
except:
return None
@classmethod
def add_question_id_to_current_exam(cls, question_id):
row = 0
col = 0
for counter in range(10):
if cls.__ui_mainwindow.tableWidget_3.item(row, col) == None:
question_text = 'Question ' + str(question_id)
question_item = QTableWidgetItem(question_text)
cls.__ui_mainwindow.tableWidget_3.setItem(row, col,
question_item)
cls.__ui_mainwindow.lineEdit_10.clear()
cls.__ui_mainwindow.label_17.clear()
return
row += 1
@classmethod
def add_school_class_id_to_current_exam(cls, school_class_id):
row = 0
col = 0
for counter in range(10):
if cls.__ui_mainwindow.tableWidget_4.item(row, col) == None:
school_class_text = 'CLass ' + str(school_class_id)
school_class_item = QTableWidgetItem(school_class_text)
cls.__ui_mainwindow.tableWidget_4.setItem(row, col,
school_class_item)
cls.__ui_mainwindow.lineEdit_11.clear()
cls.__ui_mainwindow.label_17.clear()
return
row += 1
@classmethod
def remove_question_id_from_current_exam(cls, question_id):
col = 0
for row in range(10):
question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)
if question_item != None:
question_text = question_item.text()
question_text_split = question_text.split(' ')
question_id_in_exam = int(question_text_split.pop())
if question_id_in_exam == question_id:
cls.__ui_mainwindow.tableWidget_3.takeItem(row, col)
cls.__ui_mainwindow.lineEdit_12.clear()
cls.__ui_mainwindow.label_17.clear()
return
@classmethod
def remove_school_class_id_from_current_exam(cls, school_class_id):
col = 0
for row in range(5):
school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col
)
if school_class_item != None:
school_class_text = school_class_item.text()
school_class_text_split = school_class_text.split(' ')
school_class_id_in_exam = int(school_class_text_split.pop())
if school_class_id_in_exam == school_class_id:
cls.__ui_mainwindow.tableWidget_4.takeItem(row, col)
cls.__ui_mainwindow.lineEdit_13.clear()
cls.__ui_mainwindow.label_17.clear()
return
<|reserved_special_token_0|>
@classmethod
def is_school_class_id_already_added_to_current_exam(cls, school_class_id):
string_of_school_classes_ids_in_current_exam = (cls.
get_string_of_school_classes_ids_in_current_exam())
list_of_school_classes_ids = (
string_of_school_classes_ids_in_current_exam.split(' '))
return list_of_school_classes_ids.count(str(school_class_id)) == 1
@classmethod
def get_string_of_question_ids_in_current_exam(cls):
string_of_question_ids = ''
col = 0
for row in range(10):
question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)
if question_item != None:
question_text = question_item.text()
question_text_split = question_text.split(' ')
question_id = question_text_split.pop()
string_of_question_ids = (string_of_question_ids +
question_id + ' ')
return string_of_question_ids.rstrip()
@classmethod
def get_string_of_school_classes_ids_in_current_exam(cls):
string_of_school_classes_ids = ''
col = 0
for row in range(10):
school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col
)
if school_class_item != None:
school_class_text = school_class_item.text()
school_class_text_split = school_class_text.split(' ')
school_class_id = school_class_text_split.pop()
string_of_school_classes_ids = (
string_of_school_classes_ids + school_class_id + ' ')
return string_of_school_classes_ids.rstrip()
@classmethod
def get_exam_id_to_mark(cls):
exam_item = cls.__ui_mainwindow.tableWidget_20.item(0, 0)
exam_text = exam_item.text()
exam_text_split = exam_text.split(' ')
exam_id_text = exam_text_split.pop()
return int(exam_id_text)
<|reserved_special_token_0|>
@classmethod
def display_students_full_names_with_questions_ready_to_be_marked(cls,
students_names_list):
cls.__ui_mainwindow.tableWidget_6.clear()
row = 0
col = 0
for student_name in students_names_list:
student_item = QTableWidgetItem(student_name)
cls.__ui_mainwindow.tableWidget_6.setItem(row, col, student_item)
if col >= 4:
row += 1
col = 0
else:
col += 1
@classmethod
def get_student_name_to_mark_answers(cls):
student_item = cls.__ui_mainwindow.tableWidget_19.item(0, 0)
student_name = student_item.text()
return student_name
@classmethod
def get_exam_id_to_mark_student_answers(cls):
exam_id_text = cls.__ui_mainwindow.label_49.text()
exam_id_text_split = exam_id_text.split(' ')
exam_id = exam_id_text_split.pop()
return int(exam_id)
<|reserved_special_token_0|>
@classmethod
def display_student_id_on_mark_student_answers_page(cls, student_id):
student_id_text = 'Student ID: ' + str(student_id)
cls.__ui_mainwindow.label_63.setText(student_id_text)
@classmethod
def display_student_name_on_mark_student_answers_page(cls, student_name):
student_name_text = 'Student Name: ' + str(student_name)
cls.__ui_mainwindow.label_50.setText(student_name_text)
@classmethod
def display_questions_ready_to_be_marked(cls, questions_ids_tuple):
cls.__ui_mainwindow.tableWidget_25.clear()
row = 0
col = 0
for question_id, in questions_ids_tuple:
question_text = 'Question ' + str(question_id)
question_item = QTableWidgetItem(question_text)
cls.__ui_mainwindow.tableWidget_25.setItem(row, col, question_item)
row += 1
<|reserved_special_token_0|>
@classmethod
def get_exam_id_on_marking_question_page(cls):
exam_id_text = cls.__ui_mainwindow.label_62.text()
exam_id_text_list = exam_id_text.split(' ')
exam_id = exam_id_text_list.pop()
return int(exam_id)
@classmethod
def get_student_id_on_marking_question_page(cls):
student_id_text = cls.__ui_mainwindow.label_63.text()
student_id_text_list = student_id_text.split(' ')
student_id = student_id_text_list.pop()
return int(student_id)
<|reserved_special_token_0|>
@classmethod
def get_essay_question_marked_points(cls):
points_text = cls.__ui_dialog.lineEdit.text()
return int(points_text)
@classmethod
def refresh_drop_question_to_mark_box(cls):
cls.__ui_mainwindow.tableWidget_26.clear()
@classmethod
def refresh_mark_student_questions_answers_page(cls):
cls.__ui_mainwindow.label_62.clear()
cls.__ui_mainwindow.label_63.clear()
cls.__ui_mainwindow.label_50.clear()
@classmethod
def display_no_more_questions_to_mark_message(cls):
cls.__ui_mainwindow.label_66.setText('No More Questions To Mark')
@classmethod
def display_marked_exams(cls, marked_exams_ids):
cls.__ui_mainwindow.tableWidget_18.clear()
row = 0
col = 0
for exam_id, in marked_exams_ids:
exam_text = 'Exam ' + str(exam_id)
exam_item = QTableWidgetItem(exam_text)
cls.__ui_mainwindow.tableWidget_18.setItem(row, col, exam_item)
if col >= 4:
row += 1
col = 0
else:
col += 1
@classmethod
def display_no_question_selected_to_mark_message(cls):
cls.__ui_mainwindow.label_66.setText('No Question Selected To Mark')
<|reserved_special_token_0|>
@classmethod
def get_exam_id_to_release_result(cls):
exam_item = cls.__ui_mainwindow.tableWidget_21.item(0, 0)
if exam_item == None:
return None
exam_id_text = exam_item.text()
exam_id_text_list = exam_id_text.split(' ')
exam_id = exam_id_text_list.pop()
return int(exam_id)
@classmethod
def display_result_released_exams(cls, result_released_exams_ids):
cls.__ui_mainwindow.tableWidget_11.clear()
row = 0
col = 0
for exam_id, in result_released_exams_ids:
exam_text = 'Exam ' + str(exam_id) + ' Result'
exam_item = QTableWidgetItem(exam_text)
cls.__ui_mainwindow.tableWidget_11.setItem(row, col, exam_item)
if col >= 9:
row += 1
col = 0
else:
col += 1
@classmethod
def refresh_drop_exam_to_release_result_box(cls):
cls.__ui_mainwindow.tableWidget_21.clear()
<|reserved_special_token_0|>
@classmethod
def get_exam_result_id_to_load_details(cls):
exam_result_id_text = cls.__ui_mainwindow.lineEdit_22.text()
return int(exam_result_id_text)
<|reserved_special_token_0|>
<|reserved_special_token_0|>
@classmethod
def get_school_class_id_to_view_exam_result(cls):
school_class_id_text = cls.__ui_mainwindow.lineEdit_23.text()
try:
school_class_id = int(school_class_id_text)
except:
return None
return school_class_id
@classmethod
def display_students_full_names_to_view_exam_result(cls,
students_full_names):
cls.__ui_mainwindow.tableWidget_13.clear()
row = 0
col = 0
for student_full_name, in students_full_names:
student_item = QTableWidgetItem(student_full_name)
cls.__ui_mainwindow.tableWidget_13.setItem(row, col, student_item)
row += 1
<|reserved_special_token_0|>
@classmethod
def get_exam_result_id_on_view_exam_result_page(cls):
exam_result_id_text = cls.__ui_mainwindow.label_33.text()
exam_result_id_text_list = exam_result_id_text.split(' ')
exam_result_id = exam_result_id_text_list.pop()
try:
exam_result_id_int = int(exam_result_id)
return exam_result_id_int
except:
return None
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
@classmethod
def display_questions_on_view_exam_details_page(cls, questions_ids):
cls.__ui_mainwindow.tableWidget_7.clear()
questions_ids_list = cls.make_string_to_list(questions_ids)
row = 0
col = 0
for question_id in questions_ids_list:
question_text = 'Question ' + str(question_id)
question_item = QTableWidgetItem(question_text)
cls.__ui_mainwindow.tableWidget_7.setItem(row, col, question_item)
row += 1
@classmethod
def display_first_school_class_details_on_view_exam_details_page(cls,
school_class_id, students_full_names):
cls.display_first_school_class_id_on_view_exam_details_page(
school_class_id)
cls.__ui_mainwindow.tableWidget_27.clear()
row = 0
col = 0
for student_name, in students_full_names:
student_item = QTableWidgetItem(student_name)
cls.__ui_mainwindow.tableWidget_27.setItem(row, col, student_item)
row += 1
@classmethod
def display_first_school_class_id_on_view_exam_details_page(cls,
school_class_id):
cls.__ui_mainwindow.label_67.setText('CLass ' + str(school_class_id))
@classmethod
def display_second_school_class_details_on_view_exam_details_page(cls,
school_class_id, students_full_names):
cls.display_second_school_class_id_on_view_exam_details_page(
school_class_id)
cls.__ui_mainwindow.tableWidget_28.clear()
row = 0
col = 0
for student_name, in students_full_names:
student_item = QTableWidgetItem(student_name)
cls.__ui_mainwindow.tableWidget_28.setItem(row, col, student_item)
row += 1
<|reserved_special_token_0|>
<|reserved_special_token_0|>
@classmethod
def display_third_school_class_id_on_view_exam_details_page(cls,
school_class_id):
cls.__ui_mainwindow.label_69.setText('CLass ' + str(school_class_id))
@classmethod
def display_fourth_school_class_details_on_view_exam_details_page(cls,
school_class_id, students_full_names):
cls.display_fourth_school_class_id_on_view_exam_details_page(
school_class_id)
cls.__ui_mainwindow.tableWidget_30.clear()
row = 0
col = 0
for student_name, in students_full_names:
student_item = QTableWidgetItem(student_name)
cls.__ui_mainwindow.tableWidget_30.setItem(row, col, student_item)
row += 1
@classmethod
def display_fourth_school_class_id_on_view_exam_details_page(cls,
school_class_id):
cls.__ui_mainwindow.label_70.setText('CLass ' + str(school_class_id))
@classmethod
def display_fifth_school_class_details_on_view_exam_details_page(cls,
school_class_id, students_full_names):
cls.display_fifth_school_class_id_on_view_exam_details_page(
school_class_id)
cls.__ui_mainwindow.tableWidget_31.clear()
row = 0
col = 0
for student_name, in students_full_names:
student_item = QTableWidgetItem(student_name)
cls.__ui_mainwindow.tableWidget_31.setItem(row, col, student_item)
row += 1
@classmethod
def display_fifth_school_class_id_on_view_exam_details_page(cls,
school_class_id):
cls.__ui_mainwindow.label_71.setText('CLass ' + str(school_class_id))
@classmethod
def make_string_to_list(cls, any_string):
any_string = str(any_string)
any_list = any_string.split(' ')
return any_list
@classmethod
def refresh_drop_student_to_view_exam_result_details_box(cls):
cls.__ui_mainwindow.tableWidget_22.clear()
@classmethod
def display_exam_result_id_invalid_message(cls):
cls.__ui_mainwindow.label_32.setText('Exam Result ID Invalid')
@classmethod
def refresh_load_exam_result_details_page(cls):
cls.__ui_mainwindow.label_33.clear()
cls.__ui_mainwindow.tableWidget_12.clear()
cls.__ui_mainwindow.lineEdit_23.clear()
cls.__ui_mainwindow.tableWidget_13.clear()
cls.__ui_mainwindow.tableWidget_22.clear()
cls.__ui_mainwindow.label_58.clear()
cls.__ui_mainwindow.label_72.clear()
cls.__ui_mainwindow.label_75.clear()
cls.__ui_mainwindow.label_76.clear()
cls.__ui_mainwindow.label_77.clear()
cls.__ui_mainwindow.label_78.clear()
cls.__ui_mainwindow.label_79.clear()
cls.__ui_mainwindow.label_80.clear()
@classmethod
def refresh_exam_result_id_validity_error_message(cls):
cls.__ui_mainwindow.label_32.clear()
@classmethod
def display_school_class_id_invalid_to_view_result_message(cls):
cls.__ui_mainwindow.label_81.setText('School Class ID Invalid To View')
@classmethod
def refresh_school_class_details_table_on_view_exam_result_page(cls):
cls.__ui_mainwindow.tableWidget_13.clear()
@classmethod
def refresh_school_class_id_invalid_to_view_exam_result_error_label(cls):
cls.__ui_mainwindow.label_81.clear()
<|reserved_special_token_0|>
@classmethod
def display_no_exam_result_id_selected_message(cls):
cls.__ui_mainwindow.label_81.setText('No Exam Result ID Selected')
@classmethod
def refresh_school_class_id_input_box_on_view_exam_result_details_page(cls
):
cls.__ui_mainwindow.lineEdit_23.clear()
@classmethod
def refresh_view_exam_details_by_id_page(cls):
cls.__ui_mainwindow.label_18.setText('Exam ID : ')
cls.__ui_mainwindow.tableWidget_7.clear()
cls.__ui_mainwindow.label_67.clear()
cls.__ui_mainwindow.label_68.clear()
cls.__ui_mainwindow.label_69.clear()
cls.__ui_mainwindow.label_70.clear()
cls.__ui_mainwindow.label_71.clear()
cls.__ui_mainwindow.tableWidget_27.clear()
cls.__ui_mainwindow.tableWidget_28.clear()
cls.__ui_mainwindow.tableWidget_29.clear()
cls.__ui_mainwindow.tableWidget_30.clear()
cls.__ui_mainwindow.tableWidget_31.clear()
@classmethod
def refresh_students_table_on_view_exam_result_details_page(cls):
cls.__ui_mainwindow.tableWidget_13.clear()
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class TeacherGUI:
<|reserved_special_token_0|>
@classmethod
def setup(cls, ui_mainwindow):
cls.__ui_mainwindow = ui_mainwindow
@classmethod
def display_all_active_school_classes(cls, school_classes):
cls.__ui_mainwindow.tableWidget_14.clear()
row = 0
col = 0
for school_class_id, in school_classes:
school_class_text = 'Class ' + str(school_class_id)
school_class_item = QTableWidgetItem(school_class_text)
cls.__ui_mainwindow.tableWidget_14.setItem(row, col,
school_class_item)
if col >= 4:
col = 0
row += 1
else:
col += 1
<|reserved_special_token_0|>
@classmethod
def display_not_completed_exams(cls, not_completed_exams):
cls.__ui_mainwindow.tableWidget_16.clear()
row = 0
col = 0
for exam_id, in not_completed_exams:
exam_text = 'Exam ' + str(exam_id)
exam_item = QTableWidgetItem(exam_text)
cls.__ui_mainwindow.tableWidget_16.setItem(row, col, exam_item)
if col >= 6:
col = 0
row += 1
else:
col += 1
@classmethod
def display_ready_to_be_marked_exams(cls, ready_to_be_marked_exams):
cls.__ui_mainwindow.tableWidget_17.clear()
row = 0
col = 0
for exam_id, in ready_to_be_marked_exams:
exam_text = 'Exam ' + str(exam_id)
exam_item = QTableWidgetItem(exam_text)
cls.__ui_mainwindow.tableWidget_17.setItem(row, col, exam_item)
if col >= 3:
col = 0
row += 1
else:
col += 1
<|reserved_special_token_0|>
@classmethod
def display_multiple_answers_question_dialog_preview(cls):
question_body = cls.__ui_mainwindow.textEdit_14.toPlainText()
option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText()
option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText()
option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText()
option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText()
option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText()
cls.__dialog = QtWidgets.QDialog()
cls.__ui_dialog = Ui_MultipleAnswersQuestionDialog()
cls.__ui_dialog.setupUi(cls.__dialog)
cls.__ui_dialog.label.setText(question_body)
cls.__ui_dialog.label_3.setText(option_A_text)
cls.__ui_dialog.label_4.setText(option_B_text)
cls.__ui_dialog.label_5.setText(option_C_text)
cls.__ui_dialog.label_6.setText(option_D_text)
cls.__ui_dialog.label_7.setText(option_E_text)
cls.__dialog.show()
cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)
@classmethod
def display_essay_question_dialog_preview(cls):
question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()
cls.__dialog = QtWidgets.QDialog()
cls.__ui_dialog = Ui_EssayQuestionDialog()
cls.__ui_dialog.setupUi(cls.__dialog)
if question_body == '':
cls.__ui_dialog.label.setText('Question Body')
else:
cls.__ui_dialog.label.setText(question_body)
cls.__dialog.show()
cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)
@classmethod
def close_dialog(cls):
cls.__dialog.close()
@classmethod
def get_single_answer_question_details(cls):
question_body = cls.__ui_mainwindow.textEdit.toPlainText()
if question_body == '':
return None
option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()
if option_A_text == '':
return None
option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()
if option_B_text == '':
return None
option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()
if option_C_text == '':
return None
option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()
if option_D_text == '':
return None
option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()
if option_E_text == '':
return None
year_level_text = cls.__ui_mainwindow.lineEdit_3.text()
if year_level_text == '':
return None
try:
year_level = int(year_level_text)
except:
return None
phrase_tag_text = cls.__ui_mainwindow.lineEdit_4.text()
if phrase_tag_text == '':
return None
correct_answers_list = []
if cls.__ui_mainwindow.radioButton.isChecked():
correct_answers_list.append('A')
if cls.__ui_mainwindow.radioButton_2.isChecked():
correct_answers_list.append('B')
if cls.__ui_mainwindow.radioButton_5.isChecked():
correct_answers_list.append('C')
if cls.__ui_mainwindow.radioButton_3.isChecked():
correct_answers_list.append('D')
if cls.__ui_mainwindow.radioButton_4.isChecked():
correct_answers_list.append('E')
if correct_answers_list == []:
return None
if len(correct_answers_list) > 1:
return None
return (question_body, option_A_text, option_B_text, option_C_text,
option_D_text, option_E_text, year_level, phrase_tag_text,
correct_answers_list)
<|reserved_special_token_0|>
@classmethod
def get_essay_question_details(cls):
question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()
if question_body == '':
return None
year_level_text = cls.__ui_mainwindow.lineEdit_26.text()
if year_level_text == '':
return None
try:
year_level = int(year_level_text)
except:
return None
phrase_tag_text = cls.__ui_mainwindow.lineEdit_27.text()
if phrase_tag_text == '':
return None
return question_body, year_level, phrase_tag_text
@classmethod
def display_all_active_questions(cls, active_questions_tuple):
row = 0
col = 0
for question_pk_tuple in active_questions_tuple:
question_pk = question_pk_tuple[0]
question_text = 'Question ' + str(question_pk)
question_item = QTableWidgetItem(question_text)
cls.__ui_mainwindow.tableWidget.setItem(row, col, question_item)
if col >= 7:
col = 0
row += 1
else:
col += 1
<|reserved_special_token_0|>
@classmethod
def display_invalid_single_answer_question_creation_message(cls):
cls.__ui_mainwindow.label_4.setText(
'Invalid Single Answer Question Creation')
@classmethod
def display_create_multiple_answers_question_success(cls):
cls.__ui_mainwindow.label_11.setText(
'Create Multiple Answers Question Success')
@classmethod
def display_invalid_multiple_answers_question_creation_message(cls):
cls.__ui_mainwindow.label_11.setText(
'Invalid Multiple Answers Question Creation')
@classmethod
def display_invalid_essay_question_creation_message(cls):
cls.__ui_mainwindow.label_42.setText('Invalid Essay Question Creation')
@classmethod
def display_create_essay_question_success(cls):
cls.__ui_mainwindow.label_42.setText('Create Essay Question Success')
@classmethod
def display_invalid_modification_message(cls):
cls.__ui_mainwindow.label_57.setText('Invalid Modification')
@classmethod
def refresh_create_single_answer_question_page(cls):
cls.__ui_mainwindow.textEdit.clear()
cls.__ui_mainwindow.textEdit_2.clear()
cls.__ui_mainwindow.textEdit_3.clear()
cls.__ui_mainwindow.textEdit_4.clear()
cls.__ui_mainwindow.textEdit_5.clear()
cls.__ui_mainwindow.textEdit_6.clear()
cls.__ui_mainwindow.lineEdit_3.clear()
cls.__ui_mainwindow.lineEdit_4.clear()
cls.__ui_mainwindow.radioButton.setChecked(False)
cls.__ui_mainwindow.radioButton_2.setChecked(False)
cls.__ui_mainwindow.radioButton_3.setChecked(False)
cls.__ui_mainwindow.radioButton_4.setChecked(False)
cls.__ui_mainwindow.radioButton_5.setChecked(False)
<|reserved_special_token_0|>
@classmethod
def refresh_view_or_modify_question_page(cls):
cls.__ui_mainwindow.lineEdit_5.clear()
cls.__ui_mainwindow.label_45.setText('Question ID: ')
cls.__ui_mainwindow.label_47.setText('Question Type: ')
cls.__ui_mainwindow.label_57.clear()
cls.__ui_mainwindow.label_12.clear()
cls.__ui_mainwindow.textEdit_7.clear()
cls.__ui_mainwindow.textEdit_8.clear()
cls.__ui_mainwindow.textEdit_9.clear()
cls.__ui_mainwindow.textEdit_10.clear()
cls.__ui_mainwindow.textEdit_11.clear()
cls.__ui_mainwindow.textEdit_20.clear()
cls.__ui_mainwindow.lineEdit_6.clear()
cls.__ui_mainwindow.lineEdit_8.clear()
cls.__ui_mainwindow.lineEdit_28.clear()
cls.__ui_mainwindow.radioButton_6.setDisabled(False)
cls.__ui_mainwindow.radioButton_7.setDisabled(False)
cls.__ui_mainwindow.radioButton_8.setDisabled(False)
cls.__ui_mainwindow.radioButton_9.setDisabled(False)
cls.__ui_mainwindow.radioButton_10.setDisabled(False)
cls.__ui_mainwindow.textEdit_8.setDisabled(False)
cls.__ui_mainwindow.textEdit_9.setDisabled(False)
cls.__ui_mainwindow.textEdit_10.setDisabled(False)
cls.__ui_mainwindow.textEdit_11.setDisabled(False)
cls.__ui_mainwindow.textEdit_20.setDisabled(False)
cls.__ui_mainwindow.radioButton_6.setAutoExclusive(False)
cls.__ui_mainwindow.radioButton_6.setChecked(False)
cls.__ui_mainwindow.radioButton_7.setAutoExclusive(False)
cls.__ui_mainwindow.radioButton_7.setChecked(False)
cls.__ui_mainwindow.radioButton_8.setAutoExclusive(False)
cls.__ui_mainwindow.radioButton_8.setChecked(False)
cls.__ui_mainwindow.radioButton_9.setAutoExclusive(False)
cls.__ui_mainwindow.radioButton_9.setChecked(False)
cls.__ui_mainwindow.radioButton_10.setAutoExclusive(False)
cls.__ui_mainwindow.radioButton_10.setChecked(False)
@classmethod
def refresh_create_essay_question_page(cls):
cls.__ui_mainwindow.textEdit_19.clear()
cls.__ui_mainwindow.lineEdit_26.clear()
cls.__ui_mainwindow.lineEdit_27.clear()
@classmethod
def refresh_create_exam_page(cls):
cls.__ui_mainwindow.tableWidget_3.clear()
cls.__ui_mainwindow.tableWidget_4.clear()
cls.__ui_mainwindow.lineEdit_10.clear()
cls.__ui_mainwindow.lineEdit_11.clear()
cls.__ui_mainwindow.lineEdit_12.clear()
cls.__ui_mainwindow.lineEdit_13.clear()
@classmethod
def get_question_id_to_load(cls):
question_id_text = cls.__ui_mainwindow.lineEdit_5.text()
try:
question_id = int(question_id_text)
return question_id
except:
return None
@classmethod
def load_single_answer_question_details(cls, question_details):
question_id = question_details[0]
question_type = question_details[1]
points = question_details[2]
year_level = question_details[3]
question_tag = question_details[4]
question_body = question_details[5]
option_A_text = question_details[6]
option_B_text = question_details[7]
option_C_text = question_details[8]
option_D_text = question_details[9]
option_E_text = question_details[10]
correct_answer = question_details[11]
cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)
)
cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(
question_type))
cls.__ui_mainwindow.textEdit_7.setText(question_body)
cls.__ui_mainwindow.textEdit_8.setText(option_A_text)
cls.__ui_mainwindow.textEdit_9.setText(option_B_text)
cls.__ui_mainwindow.textEdit_10.setText(option_C_text)
cls.__ui_mainwindow.textEdit_11.setText(option_D_text)
cls.__ui_mainwindow.textEdit_20.setText(option_E_text)
cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))
cls.__ui_mainwindow.lineEdit_8.setText(question_tag)
cls.__ui_mainwindow.lineEdit_28.setText(str(points))
if correct_answer == 'A':
cls.__ui_mainwindow.radioButton_6.setChecked(True)
elif correct_answer == 'B':
cls.__ui_mainwindow.radioButton_7.setChecked(True)
elif correct_answer == 'C':
cls.__ui_mainwindow.radioButton_8.setChecked(True)
elif correct_answer == 'D':
cls.__ui_mainwindow.radioButton_9.setChecked(True)
elif correct_answer == 'E':
cls.__ui_mainwindow.radioButton_10.setChecked(True)
@classmethod
def load_multiple_answers_question_details(cls, question_details):
question_id = question_details[0]
question_type = question_details[1]
points = question_details[2]
year_level = question_details[3]
question_tag = question_details[4]
question_body = question_details[5]
option_A_text = question_details[6]
option_B_text = question_details[7]
option_C_text = question_details[8]
option_D_text = question_details[9]
option_E_text = question_details[10]
correct_answers = question_details[11]
cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)
)
cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(
question_type))
cls.__ui_mainwindow.textEdit_7.setText(question_body)
cls.__ui_mainwindow.textEdit_8.setText(option_A_text)
cls.__ui_mainwindow.textEdit_9.setText(option_B_text)
cls.__ui_mainwindow.textEdit_10.setText(option_C_text)
cls.__ui_mainwindow.textEdit_11.setText(option_D_text)
cls.__ui_mainwindow.textEdit_20.setText(option_E_text)
cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))
cls.__ui_mainwindow.lineEdit_8.setText(question_tag)
cls.__ui_mainwindow.lineEdit_28.setText(str(points))
if correct_answers.count('A') == 1:
cls.__ui_mainwindow.radioButton_6.setChecked(True)
if correct_answers.count('B') == 1:
cls.__ui_mainwindow.radioButton_7.setChecked(True)
if correct_answers.count('C') == 1:
cls.__ui_mainwindow.radioButton_8.setChecked(True)
if correct_answers.count('D') == 1:
cls.__ui_mainwindow.radioButton_9.setChecked(True)
if correct_answers.count('E') == 1:
cls.__ui_mainwindow.radioButton_10.setChecked(True)
@classmethod
def load_essay_question_details(cls, question_details):
question_id = question_details[0]
question_type = question_details[1]
points = question_details[2]
year_level = question_details[3]
question_tag = question_details[4]
question_body = question_details[5]
cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)
)
cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(
question_type))
cls.__ui_mainwindow.textEdit_7.setText(question_body)
cls.__ui_mainwindow.radioButton_6.setDisabled(True)
cls.__ui_mainwindow.radioButton_7.setDisabled(True)
cls.__ui_mainwindow.radioButton_8.setDisabled(True)
cls.__ui_mainwindow.radioButton_9.setDisabled(True)
cls.__ui_mainwindow.radioButton_10.setDisabled(True)
cls.__ui_mainwindow.textEdit_8.setDisabled(True)
cls.__ui_mainwindow.textEdit_9.setDisabled(True)
cls.__ui_mainwindow.textEdit_10.setDisabled(True)
cls.__ui_mainwindow.textEdit_11.setDisabled(True)
cls.__ui_mainwindow.textEdit_20.setDisabled(True)
cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))
cls.__ui_mainwindow.lineEdit_8.setText(question_tag)
cls.__ui_mainwindow.lineEdit_28.setText(str(points))
@classmethod
def display_question_id_invalid_to_load_message(cls):
cls.__ui_mainwindow.label_12.setText('Invalid Question ID To Load')
@classmethod
def display_modification_success_message(cls):
cls.__ui_mainwindow.label_57.setText('Modification Success')
@classmethod
def display_invalid_school_class_id_message(cls):
cls.__ui_mainwindow.label_14.setText('Invalid School Class ID')
cls.__ui_mainwindow.tableWidget_15.clear()
@classmethod
def get_question_type_to_modify(cls):
question_type_text = cls.__ui_mainwindow.label_47.text()
if question_type_text == 'Question Type: Single Answer':
return 'Single Answer'
elif question_type_text == 'Question Type: Multiple Answers':
return 'Multiple Answers'
elif question_type_text == 'Question Type: Essay':
return 'Essay'
@classmethod
def get_single_answer_question_details_to_modify(cls):
question_pk = cls.get_question_id_to_modify()
question_type = cls.get_question_type_to_modify()
points = int(cls.__ui_mainwindow.lineEdit_28.text())
year_level = int(cls.__ui_mainwindow.lineEdit_6.text())
question_tag = cls.__ui_mainwindow.lineEdit_8.text()
question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()
option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()
option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()
option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()
option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()
option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()
correct_answer = cls.get_single_correct_answer_to_modify()
if correct_answer == None:
return None
return (question_pk, question_type, points, year_level,
question_tag, question_body, option_A_text, option_B_text,
option_C_text, option_D_text, option_E_text, correct_answer)
@classmethod
def get_multiple_answers_question_details_to_modify(cls):
question_pk = cls.get_question_id_to_modify()
question_type = cls.get_question_type_to_modify()
points = int(cls.__ui_mainwindow.lineEdit_28.text())
year_level = int(cls.__ui_mainwindow.lineEdit_6.text())
question_tag = cls.__ui_mainwindow.lineEdit_8.text()
question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()
option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()
option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()
option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()
option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()
option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()
correct_answers = cls.get_multiple_correct_answers_to_modify()
if correct_answers == None:
return None
return (question_pk, question_type, points, year_level,
question_tag, question_body, option_A_text, option_B_text,
option_C_text, option_D_text, option_E_text, correct_answers)
@classmethod
def get_essay_question_details_to_modify(cls):
question_pk = cls.get_question_id_to_modify()
question_type = cls.get_question_type_to_modify()
try:
points = int(cls.__ui_mainwindow.lineEdit_28.text())
except:
return None
try:
year_level = int(cls.__ui_mainwindow.lineEdit_6.text())
except:
return None
question_tag = cls.__ui_mainwindow.lineEdit_8.text()
if question_tag == '':
return None
question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()
if question_body == '':
return None
return (question_pk, question_type, points, year_level,
question_tag, question_body)
@classmethod
def get_question_id_to_modify(cls):
question_id_text = cls.__ui_mainwindow.label_45.text()
question_id_text_split = question_id_text.split()
question_id = int(question_id_text_split.pop())
return question_id
<|reserved_special_token_0|>
@classmethod
def get_multiple_correct_answers_to_modify(cls):
correct_answers = ''
if cls.__ui_mainwindow.radioButton_6.isChecked():
correct_answers = correct_answers + 'A'
if cls.__ui_mainwindow.radioButton_7.isChecked():
correct_answers = correct_answers + 'B'
if cls.__ui_mainwindow.radioButton_8.isChecked():
correct_answers = correct_answers + 'C'
if cls.__ui_mainwindow.radioButton_9.isChecked():
correct_answers = correct_answers + 'D'
if cls.__ui_mainwindow.radioButton_10.isChecked():
correct_answers = correct_answers + 'E'
if len(correct_answers) == 0:
return None
if len(correct_answers) > 4:
return None
return correct_answers
@classmethod
def get_school_class_id_to_view_students(cls):
school_class_id_text = cls.__ui_mainwindow.lineEdit_9.text()
try:
school_class_id = int(school_class_id_text)
return school_class_id
except:
return None
@classmethod
def display_school_class_details(cls, school_class_details):
cls.__ui_mainwindow.tableWidget_15.clear()
row = 0
col = 0
for student, in school_class_details:
student_item = QTableWidgetItem(student)
cls.__ui_mainwindow.tableWidget_15.setItem(row, col, student_item)
if col >= 1:
col = 0
row += 1
else:
col += 1
@classmethod
def refresh_view_school_class_details_page(cls):
cls.__ui_mainwindow.label_14.clear()
<|reserved_special_token_0|>
@classmethod
def get_number_of_school_classes_in_current_exam(cls):
number_of_school_classes = 0
row = 0
col = 0
for counter in range(5):
if cls.__ui_mainwindow.tableWidget_4.item(row, col) != None:
number_of_school_classes += 1
row += 1
return number_of_school_classes
@classmethod
def display_number_of_questions_full_in_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText(
'Questions Are Full In Current Exam')
@classmethod
def display_number_of_school_classes_full_in_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText(
'School Classes Are Full In Current Exam')
@classmethod
def display_no_question_in_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText('No Question In Current Exam')
@classmethod
def display_no_school_class_in_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText('No School Class In Current Exam')
<|reserved_special_token_0|>
@classmethod
def display_school_class_id_already_added_to_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText(
'School Class ID Already Added To Current Exam')
@classmethod
def display_question_id_invalid_message(cls):
cls.__ui_mainwindow.label_17.setText('Question ID Invalid')
@classmethod
def display_school_class_id_invalid_message(cls):
cls.__ui_mainwindow.label_17.setText('School CLass ID Invalid')
@classmethod
def display_question_id_not_already_in_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText(
'Question ID Not Aleady In Current Exam')
<|reserved_special_token_0|>
@classmethod
def display_create_exam_success_message(cls):
cls.__ui_mainwindow.label_17.setText('Create Exam Success')
@classmethod
def refresh_mark_exam_drop_box(cls):
cls.__ui_mainwindow.tableWidget_19.clear()
@classmethod
def get_question_id_to_add_to_exam(cls):
question_id_text = cls.__ui_mainwindow.lineEdit_10.text()
try:
question_id = int(question_id_text)
return question_id
except:
return None
@classmethod
def get_school_class_id_to_add_to_exam(cls):
school_class_id_text = cls.__ui_mainwindow.lineEdit_11.text()
try:
school_class_id = int(school_class_id_text)
return school_class_id
except:
return None
<|reserved_special_token_0|>
@classmethod
def get_school_class_id_to_remove_from_exam(cls):
school_class_id_text = cls.__ui_mainwindow.lineEdit_13.text()
try:
school_class_id = int(school_class_id_text)
return school_class_id
except:
return None
@classmethod
def add_question_id_to_current_exam(cls, question_id):
row = 0
col = 0
for counter in range(10):
if cls.__ui_mainwindow.tableWidget_3.item(row, col) == None:
question_text = 'Question ' + str(question_id)
question_item = QTableWidgetItem(question_text)
cls.__ui_mainwindow.tableWidget_3.setItem(row, col,
question_item)
cls.__ui_mainwindow.lineEdit_10.clear()
cls.__ui_mainwindow.label_17.clear()
return
row += 1
@classmethod
def add_school_class_id_to_current_exam(cls, school_class_id):
row = 0
col = 0
for counter in range(10):
if cls.__ui_mainwindow.tableWidget_4.item(row, col) == None:
school_class_text = 'CLass ' + str(school_class_id)
school_class_item = QTableWidgetItem(school_class_text)
cls.__ui_mainwindow.tableWidget_4.setItem(row, col,
school_class_item)
cls.__ui_mainwindow.lineEdit_11.clear()
cls.__ui_mainwindow.label_17.clear()
return
row += 1
@classmethod
def remove_question_id_from_current_exam(cls, question_id):
col = 0
for row in range(10):
question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)
if question_item != None:
question_text = question_item.text()
question_text_split = question_text.split(' ')
question_id_in_exam = int(question_text_split.pop())
if question_id_in_exam == question_id:
cls.__ui_mainwindow.tableWidget_3.takeItem(row, col)
cls.__ui_mainwindow.lineEdit_12.clear()
cls.__ui_mainwindow.label_17.clear()
return
@classmethod
def remove_school_class_id_from_current_exam(cls, school_class_id):
col = 0
for row in range(5):
school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col
)
if school_class_item != None:
school_class_text = school_class_item.text()
school_class_text_split = school_class_text.split(' ')
school_class_id_in_exam = int(school_class_text_split.pop())
if school_class_id_in_exam == school_class_id:
cls.__ui_mainwindow.tableWidget_4.takeItem(row, col)
cls.__ui_mainwindow.lineEdit_13.clear()
cls.__ui_mainwindow.label_17.clear()
return
<|reserved_special_token_0|>
@classmethod
def is_school_class_id_already_added_to_current_exam(cls, school_class_id):
string_of_school_classes_ids_in_current_exam = (cls.
get_string_of_school_classes_ids_in_current_exam())
list_of_school_classes_ids = (
string_of_school_classes_ids_in_current_exam.split(' '))
return list_of_school_classes_ids.count(str(school_class_id)) == 1
@classmethod
def get_string_of_question_ids_in_current_exam(cls):
string_of_question_ids = ''
col = 0
for row in range(10):
question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)
if question_item != None:
question_text = question_item.text()
question_text_split = question_text.split(' ')
question_id = question_text_split.pop()
string_of_question_ids = (string_of_question_ids +
question_id + ' ')
return string_of_question_ids.rstrip()
@classmethod
def get_string_of_school_classes_ids_in_current_exam(cls):
string_of_school_classes_ids = ''
col = 0
for row in range(10):
school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col
)
if school_class_item != None:
school_class_text = school_class_item.text()
school_class_text_split = school_class_text.split(' ')
school_class_id = school_class_text_split.pop()
string_of_school_classes_ids = (
string_of_school_classes_ids + school_class_id + ' ')
return string_of_school_classes_ids.rstrip()
@classmethod
def get_exam_id_to_mark(cls):
exam_item = cls.__ui_mainwindow.tableWidget_20.item(0, 0)
exam_text = exam_item.text()
exam_text_split = exam_text.split(' ')
exam_id_text = exam_text_split.pop()
return int(exam_id_text)
<|reserved_special_token_0|>
@classmethod
def display_students_full_names_with_questions_ready_to_be_marked(cls,
students_names_list):
cls.__ui_mainwindow.tableWidget_6.clear()
row = 0
col = 0
for student_name in students_names_list:
student_item = QTableWidgetItem(student_name)
cls.__ui_mainwindow.tableWidget_6.setItem(row, col, student_item)
if col >= 4:
row += 1
col = 0
else:
col += 1
@classmethod
def get_student_name_to_mark_answers(cls):
student_item = cls.__ui_mainwindow.tableWidget_19.item(0, 0)
student_name = student_item.text()
return student_name
@classmethod
def get_exam_id_to_mark_student_answers(cls):
exam_id_text = cls.__ui_mainwindow.label_49.text()
exam_id_text_split = exam_id_text.split(' ')
exam_id = exam_id_text_split.pop()
return int(exam_id)
<|reserved_special_token_0|>
@classmethod
def display_student_id_on_mark_student_answers_page(cls, student_id):
student_id_text = 'Student ID: ' + str(student_id)
cls.__ui_mainwindow.label_63.setText(student_id_text)
@classmethod
def display_student_name_on_mark_student_answers_page(cls, student_name):
student_name_text = 'Student Name: ' + str(student_name)
cls.__ui_mainwindow.label_50.setText(student_name_text)
@classmethod
def display_questions_ready_to_be_marked(cls, questions_ids_tuple):
cls.__ui_mainwindow.tableWidget_25.clear()
row = 0
col = 0
for question_id, in questions_ids_tuple:
question_text = 'Question ' + str(question_id)
question_item = QTableWidgetItem(question_text)
cls.__ui_mainwindow.tableWidget_25.setItem(row, col, question_item)
row += 1
<|reserved_special_token_0|>
@classmethod
def get_exam_id_on_marking_question_page(cls):
exam_id_text = cls.__ui_mainwindow.label_62.text()
exam_id_text_list = exam_id_text.split(' ')
exam_id = exam_id_text_list.pop()
return int(exam_id)
@classmethod
def get_student_id_on_marking_question_page(cls):
student_id_text = cls.__ui_mainwindow.label_63.text()
student_id_text_list = student_id_text.split(' ')
student_id = student_id_text_list.pop()
return int(student_id)
<|reserved_special_token_0|>
@classmethod
def get_essay_question_marked_points(cls):
points_text = cls.__ui_dialog.lineEdit.text()
return int(points_text)
@classmethod
def refresh_drop_question_to_mark_box(cls):
cls.__ui_mainwindow.tableWidget_26.clear()
@classmethod
def refresh_mark_student_questions_answers_page(cls):
cls.__ui_mainwindow.label_62.clear()
cls.__ui_mainwindow.label_63.clear()
cls.__ui_mainwindow.label_50.clear()
@classmethod
def display_no_more_questions_to_mark_message(cls):
cls.__ui_mainwindow.label_66.setText('No More Questions To Mark')
@classmethod
def display_marked_exams(cls, marked_exams_ids):
cls.__ui_mainwindow.tableWidget_18.clear()
row = 0
col = 0
for exam_id, in marked_exams_ids:
exam_text = 'Exam ' + str(exam_id)
exam_item = QTableWidgetItem(exam_text)
cls.__ui_mainwindow.tableWidget_18.setItem(row, col, exam_item)
if col >= 4:
row += 1
col = 0
else:
col += 1
@classmethod
def display_no_question_selected_to_mark_message(cls):
cls.__ui_mainwindow.label_66.setText('No Question Selected To Mark')
<|reserved_special_token_0|>
@classmethod
def get_exam_id_to_release_result(cls):
exam_item = cls.__ui_mainwindow.tableWidget_21.item(0, 0)
if exam_item == None:
return None
exam_id_text = exam_item.text()
exam_id_text_list = exam_id_text.split(' ')
exam_id = exam_id_text_list.pop()
return int(exam_id)
@classmethod
def display_result_released_exams(cls, result_released_exams_ids):
cls.__ui_mainwindow.tableWidget_11.clear()
row = 0
col = 0
for exam_id, in result_released_exams_ids:
exam_text = 'Exam ' + str(exam_id) + ' Result'
exam_item = QTableWidgetItem(exam_text)
cls.__ui_mainwindow.tableWidget_11.setItem(row, col, exam_item)
if col >= 9:
row += 1
col = 0
else:
col += 1
@classmethod
def refresh_drop_exam_to_release_result_box(cls):
cls.__ui_mainwindow.tableWidget_21.clear()
<|reserved_special_token_0|>
@classmethod
def get_exam_result_id_to_load_details(cls):
exam_result_id_text = cls.__ui_mainwindow.lineEdit_22.text()
return int(exam_result_id_text)
<|reserved_special_token_0|>
@classmethod
def display_exam_result_id_on_view_exam_result_details_page(cls,
exam_result_id):
cls.__ui_mainwindow.label_33.setText('Exam Result ID: ' + str(
exam_result_id))
@classmethod
def get_school_class_id_to_view_exam_result(cls):
school_class_id_text = cls.__ui_mainwindow.lineEdit_23.text()
try:
school_class_id = int(school_class_id_text)
except:
return None
return school_class_id
@classmethod
def display_students_full_names_to_view_exam_result(cls,
students_full_names):
cls.__ui_mainwindow.tableWidget_13.clear()
row = 0
col = 0
for student_full_name, in students_full_names:
student_item = QTableWidgetItem(student_full_name)
cls.__ui_mainwindow.tableWidget_13.setItem(row, col, student_item)
row += 1
<|reserved_special_token_0|>
@classmethod
def get_exam_result_id_on_view_exam_result_page(cls):
exam_result_id_text = cls.__ui_mainwindow.label_33.text()
exam_result_id_text_list = exam_result_id_text.split(' ')
exam_result_id = exam_result_id_text_list.pop()
try:
exam_result_id_int = int(exam_result_id)
return exam_result_id_int
except:
return None
@classmethod
def display_student_exam_result_details(cls, exam_result_details):
student_id = exam_result_details[0]
student_full_name = exam_result_details[1]
date_of_birth = exam_result_details[2]
school_class_id = exam_result_details[3]
exam_id = exam_result_details[4]
total_available_points = exam_result_details[5]
total_points_gained = exam_result_details[6]
average_percentage_mark = exam_result_details[7]
cls.__ui_mainwindow.label_58.setText(str(student_id))
cls.__ui_mainwindow.label_72.setText(str(student_full_name))
cls.__ui_mainwindow.label_75.setText(str(date_of_birth))
cls.__ui_mainwindow.label_76.setText(str(school_class_id))
cls.__ui_mainwindow.label_77.setText(str(exam_id))
cls.__ui_mainwindow.label_78.setText(str(total_available_points))
cls.__ui_mainwindow.label_79.setText(str(total_points_gained))
cls.__ui_mainwindow.label_80.setText(str(average_percentage_mark) +
' %')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
@classmethod
def display_questions_on_view_exam_details_page(cls, questions_ids):
cls.__ui_mainwindow.tableWidget_7.clear()
questions_ids_list = cls.make_string_to_list(questions_ids)
row = 0
col = 0
for question_id in questions_ids_list:
question_text = 'Question ' + str(question_id)
question_item = QTableWidgetItem(question_text)
cls.__ui_mainwindow.tableWidget_7.setItem(row, col, question_item)
row += 1
@classmethod
def display_first_school_class_details_on_view_exam_details_page(cls,
school_class_id, students_full_names):
cls.display_first_school_class_id_on_view_exam_details_page(
school_class_id)
cls.__ui_mainwindow.tableWidget_27.clear()
row = 0
col = 0
for student_name, in students_full_names:
student_item = QTableWidgetItem(student_name)
cls.__ui_mainwindow.tableWidget_27.setItem(row, col, student_item)
row += 1
@classmethod
def display_first_school_class_id_on_view_exam_details_page(cls,
school_class_id):
cls.__ui_mainwindow.label_67.setText('CLass ' + str(school_class_id))
@classmethod
def display_second_school_class_details_on_view_exam_details_page(cls,
school_class_id, students_full_names):
cls.display_second_school_class_id_on_view_exam_details_page(
school_class_id)
cls.__ui_mainwindow.tableWidget_28.clear()
row = 0
col = 0
for student_name, in students_full_names:
student_item = QTableWidgetItem(student_name)
cls.__ui_mainwindow.tableWidget_28.setItem(row, col, student_item)
row += 1
<|reserved_special_token_0|>
<|reserved_special_token_0|>
@classmethod
def display_third_school_class_id_on_view_exam_details_page(cls,
school_class_id):
cls.__ui_mainwindow.label_69.setText('CLass ' + str(school_class_id))
@classmethod
def display_fourth_school_class_details_on_view_exam_details_page(cls,
school_class_id, students_full_names):
cls.display_fourth_school_class_id_on_view_exam_details_page(
school_class_id)
cls.__ui_mainwindow.tableWidget_30.clear()
row = 0
col = 0
for student_name, in students_full_names:
student_item = QTableWidgetItem(student_name)
cls.__ui_mainwindow.tableWidget_30.setItem(row, col, student_item)
row += 1
@classmethod
def display_fourth_school_class_id_on_view_exam_details_page(cls,
school_class_id):
cls.__ui_mainwindow.label_70.setText('CLass ' + str(school_class_id))
@classmethod
def display_fifth_school_class_details_on_view_exam_details_page(cls,
school_class_id, students_full_names):
cls.display_fifth_school_class_id_on_view_exam_details_page(
school_class_id)
cls.__ui_mainwindow.tableWidget_31.clear()
row = 0
col = 0
for student_name, in students_full_names:
student_item = QTableWidgetItem(student_name)
cls.__ui_mainwindow.tableWidget_31.setItem(row, col, student_item)
row += 1
@classmethod
def display_fifth_school_class_id_on_view_exam_details_page(cls,
school_class_id):
cls.__ui_mainwindow.label_71.setText('CLass ' + str(school_class_id))
@classmethod
def make_string_to_list(cls, any_string):
any_string = str(any_string)
any_list = any_string.split(' ')
return any_list
@classmethod
def refresh_drop_student_to_view_exam_result_details_box(cls):
cls.__ui_mainwindow.tableWidget_22.clear()
@classmethod
def display_exam_result_id_invalid_message(cls):
cls.__ui_mainwindow.label_32.setText('Exam Result ID Invalid')
@classmethod
def refresh_load_exam_result_details_page(cls):
cls.__ui_mainwindow.label_33.clear()
cls.__ui_mainwindow.tableWidget_12.clear()
cls.__ui_mainwindow.lineEdit_23.clear()
cls.__ui_mainwindow.tableWidget_13.clear()
cls.__ui_mainwindow.tableWidget_22.clear()
cls.__ui_mainwindow.label_58.clear()
cls.__ui_mainwindow.label_72.clear()
cls.__ui_mainwindow.label_75.clear()
cls.__ui_mainwindow.label_76.clear()
cls.__ui_mainwindow.label_77.clear()
cls.__ui_mainwindow.label_78.clear()
cls.__ui_mainwindow.label_79.clear()
cls.__ui_mainwindow.label_80.clear()
@classmethod
def refresh_exam_result_id_validity_error_message(cls):
cls.__ui_mainwindow.label_32.clear()
@classmethod
def display_school_class_id_invalid_to_view_result_message(cls):
cls.__ui_mainwindow.label_81.setText('School Class ID Invalid To View')
@classmethod
def refresh_school_class_details_table_on_view_exam_result_page(cls):
cls.__ui_mainwindow.tableWidget_13.clear()
@classmethod
def refresh_school_class_id_invalid_to_view_exam_result_error_label(cls):
cls.__ui_mainwindow.label_81.clear()
<|reserved_special_token_0|>
@classmethod
def display_no_exam_result_id_selected_message(cls):
cls.__ui_mainwindow.label_81.setText('No Exam Result ID Selected')
@classmethod
def refresh_school_class_id_input_box_on_view_exam_result_details_page(cls
):
cls.__ui_mainwindow.lineEdit_23.clear()
@classmethod
def refresh_view_exam_details_by_id_page(cls):
cls.__ui_mainwindow.label_18.setText('Exam ID : ')
cls.__ui_mainwindow.tableWidget_7.clear()
cls.__ui_mainwindow.label_67.clear()
cls.__ui_mainwindow.label_68.clear()
cls.__ui_mainwindow.label_69.clear()
cls.__ui_mainwindow.label_70.clear()
cls.__ui_mainwindow.label_71.clear()
cls.__ui_mainwindow.tableWidget_27.clear()
cls.__ui_mainwindow.tableWidget_28.clear()
cls.__ui_mainwindow.tableWidget_29.clear()
cls.__ui_mainwindow.tableWidget_30.clear()
cls.__ui_mainwindow.tableWidget_31.clear()
@classmethod
def refresh_students_table_on_view_exam_result_details_page(cls):
cls.__ui_mainwindow.tableWidget_13.clear()
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class TeacherGUI:
def __init__(self):
pass
@classmethod
def setup(cls, ui_mainwindow):
cls.__ui_mainwindow = ui_mainwindow
@classmethod
def display_all_active_school_classes(cls, school_classes):
cls.__ui_mainwindow.tableWidget_14.clear()
row = 0
col = 0
for school_class_id, in school_classes:
school_class_text = 'Class ' + str(school_class_id)
school_class_item = QTableWidgetItem(school_class_text)
cls.__ui_mainwindow.tableWidget_14.setItem(row, col,
school_class_item)
if col >= 4:
col = 0
row += 1
else:
col += 1
@classmethod
def display_all_exams(cls, all_exams):
cls.__ui_mainwindow.tableWidget_5.clear()
row = 0
col = 0
for exam_id, in all_exams:
exam_text = 'Exam ' + str(exam_id)
exam_item = QTableWidgetItem(exam_text)
cls.__ui_mainwindow.tableWidget_5.setItem(row, col, exam_item)
if col >= 9:
col = 0
row += 1
else:
col += 1
@classmethod
def display_not_completed_exams(cls, not_completed_exams):
cls.__ui_mainwindow.tableWidget_16.clear()
row = 0
col = 0
for exam_id, in not_completed_exams:
exam_text = 'Exam ' + str(exam_id)
exam_item = QTableWidgetItem(exam_text)
cls.__ui_mainwindow.tableWidget_16.setItem(row, col, exam_item)
if col >= 6:
col = 0
row += 1
else:
col += 1
@classmethod
def display_ready_to_be_marked_exams(cls, ready_to_be_marked_exams):
cls.__ui_mainwindow.tableWidget_17.clear()
row = 0
col = 0
for exam_id, in ready_to_be_marked_exams:
exam_text = 'Exam ' + str(exam_id)
exam_item = QTableWidgetItem(exam_text)
cls.__ui_mainwindow.tableWidget_17.setItem(row, col, exam_item)
if col >= 3:
col = 0
row += 1
else:
col += 1
@classmethod
def display_single_answer_question_dialog_preview(cls):
question_body = cls.__ui_mainwindow.textEdit.toPlainText()
option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()
option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()
option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()
option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()
option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()
cls.__dialog = QtWidgets.QDialog()
cls.__ui_dialog = Ui_SingleAnswerQuestionDialog()
cls.__ui_dialog.setupUi(cls.__dialog)
cls.__ui_dialog.label.setText(question_body)
cls.__ui_dialog.label_3.setText('A ' + option_A_text)
cls.__ui_dialog.label_4.setText('B ' + option_B_text)
cls.__ui_dialog.label_5.setText('C ' + option_C_text)
cls.__ui_dialog.label_6.setText('D ' + option_D_text)
cls.__ui_dialog.label_7.setText('E ' + option_E_text)
cls.__dialog.show()
cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)
@classmethod
def display_multiple_answers_question_dialog_preview(cls):
question_body = cls.__ui_mainwindow.textEdit_14.toPlainText()
option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText()
option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText()
option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText()
option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText()
option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText()
cls.__dialog = QtWidgets.QDialog()
cls.__ui_dialog = Ui_MultipleAnswersQuestionDialog()
cls.__ui_dialog.setupUi(cls.__dialog)
cls.__ui_dialog.label.setText(question_body)
cls.__ui_dialog.label_3.setText(option_A_text)
cls.__ui_dialog.label_4.setText(option_B_text)
cls.__ui_dialog.label_5.setText(option_C_text)
cls.__ui_dialog.label_6.setText(option_D_text)
cls.__ui_dialog.label_7.setText(option_E_text)
cls.__dialog.show()
cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)
@classmethod
def display_essay_question_dialog_preview(cls):
question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()
cls.__dialog = QtWidgets.QDialog()
cls.__ui_dialog = Ui_EssayQuestionDialog()
cls.__ui_dialog.setupUi(cls.__dialog)
if question_body == '':
cls.__ui_dialog.label.setText('Question Body')
else:
cls.__ui_dialog.label.setText(question_body)
cls.__dialog.show()
cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)
@classmethod
def close_dialog(cls):
cls.__dialog.close()
@classmethod
def get_single_answer_question_details(cls):
question_body = cls.__ui_mainwindow.textEdit.toPlainText()
if question_body == '':
return None
option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()
if option_A_text == '':
return None
option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()
if option_B_text == '':
return None
option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()
if option_C_text == '':
return None
option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()
if option_D_text == '':
return None
option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()
if option_E_text == '':
return None
year_level_text = cls.__ui_mainwindow.lineEdit_3.text()
if year_level_text == '':
return None
try:
year_level = int(year_level_text)
except:
return None
phrase_tag_text = cls.__ui_mainwindow.lineEdit_4.text()
if phrase_tag_text == '':
return None
correct_answers_list = []
if cls.__ui_mainwindow.radioButton.isChecked():
correct_answers_list.append('A')
if cls.__ui_mainwindow.radioButton_2.isChecked():
correct_answers_list.append('B')
if cls.__ui_mainwindow.radioButton_5.isChecked():
correct_answers_list.append('C')
if cls.__ui_mainwindow.radioButton_3.isChecked():
correct_answers_list.append('D')
if cls.__ui_mainwindow.radioButton_4.isChecked():
correct_answers_list.append('E')
if correct_answers_list == []:
return None
if len(correct_answers_list) > 1:
return None
return (question_body, option_A_text, option_B_text, option_C_text,
option_D_text, option_E_text, year_level, phrase_tag_text,
correct_answers_list)
<|reserved_special_token_0|>
@classmethod
def get_essay_question_details(cls):
question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()
if question_body == '':
return None
year_level_text = cls.__ui_mainwindow.lineEdit_26.text()
if year_level_text == '':
return None
try:
year_level = int(year_level_text)
except:
return None
phrase_tag_text = cls.__ui_mainwindow.lineEdit_27.text()
if phrase_tag_text == '':
return None
return question_body, year_level, phrase_tag_text
@classmethod
def display_all_active_questions(cls, active_questions_tuple):
row = 0
col = 0
for question_pk_tuple in active_questions_tuple:
question_pk = question_pk_tuple[0]
question_text = 'Question ' + str(question_pk)
question_item = QTableWidgetItem(question_text)
cls.__ui_mainwindow.tableWidget.setItem(row, col, question_item)
if col >= 7:
col = 0
row += 1
else:
col += 1
@classmethod
def display_create_single_answer_question_success(cls):
cls.__ui_mainwindow.label_4.setText(
'Create Single Answer Question Success')
@classmethod
def display_invalid_single_answer_question_creation_message(cls):
cls.__ui_mainwindow.label_4.setText(
'Invalid Single Answer Question Creation')
@classmethod
def display_create_multiple_answers_question_success(cls):
cls.__ui_mainwindow.label_11.setText(
'Create Multiple Answers Question Success')
@classmethod
def display_invalid_multiple_answers_question_creation_message(cls):
cls.__ui_mainwindow.label_11.setText(
'Invalid Multiple Answers Question Creation')
@classmethod
def display_invalid_essay_question_creation_message(cls):
cls.__ui_mainwindow.label_42.setText('Invalid Essay Question Creation')
@classmethod
def display_create_essay_question_success(cls):
cls.__ui_mainwindow.label_42.setText('Create Essay Question Success')
@classmethod
def display_invalid_modification_message(cls):
cls.__ui_mainwindow.label_57.setText('Invalid Modification')
@classmethod
def refresh_create_single_answer_question_page(cls):
cls.__ui_mainwindow.textEdit.clear()
cls.__ui_mainwindow.textEdit_2.clear()
cls.__ui_mainwindow.textEdit_3.clear()
cls.__ui_mainwindow.textEdit_4.clear()
cls.__ui_mainwindow.textEdit_5.clear()
cls.__ui_mainwindow.textEdit_6.clear()
cls.__ui_mainwindow.lineEdit_3.clear()
cls.__ui_mainwindow.lineEdit_4.clear()
cls.__ui_mainwindow.radioButton.setChecked(False)
cls.__ui_mainwindow.radioButton_2.setChecked(False)
cls.__ui_mainwindow.radioButton_3.setChecked(False)
cls.__ui_mainwindow.radioButton_4.setChecked(False)
cls.__ui_mainwindow.radioButton_5.setChecked(False)
<|reserved_special_token_0|>
@classmethod
def refresh_view_or_modify_question_page(cls):
cls.__ui_mainwindow.lineEdit_5.clear()
cls.__ui_mainwindow.label_45.setText('Question ID: ')
cls.__ui_mainwindow.label_47.setText('Question Type: ')
cls.__ui_mainwindow.label_57.clear()
cls.__ui_mainwindow.label_12.clear()
cls.__ui_mainwindow.textEdit_7.clear()
cls.__ui_mainwindow.textEdit_8.clear()
cls.__ui_mainwindow.textEdit_9.clear()
cls.__ui_mainwindow.textEdit_10.clear()
cls.__ui_mainwindow.textEdit_11.clear()
cls.__ui_mainwindow.textEdit_20.clear()
cls.__ui_mainwindow.lineEdit_6.clear()
cls.__ui_mainwindow.lineEdit_8.clear()
cls.__ui_mainwindow.lineEdit_28.clear()
cls.__ui_mainwindow.radioButton_6.setDisabled(False)
cls.__ui_mainwindow.radioButton_7.setDisabled(False)
cls.__ui_mainwindow.radioButton_8.setDisabled(False)
cls.__ui_mainwindow.radioButton_9.setDisabled(False)
cls.__ui_mainwindow.radioButton_10.setDisabled(False)
cls.__ui_mainwindow.textEdit_8.setDisabled(False)
cls.__ui_mainwindow.textEdit_9.setDisabled(False)
cls.__ui_mainwindow.textEdit_10.setDisabled(False)
cls.__ui_mainwindow.textEdit_11.setDisabled(False)
cls.__ui_mainwindow.textEdit_20.setDisabled(False)
cls.__ui_mainwindow.radioButton_6.setAutoExclusive(False)
cls.__ui_mainwindow.radioButton_6.setChecked(False)
cls.__ui_mainwindow.radioButton_7.setAutoExclusive(False)
cls.__ui_mainwindow.radioButton_7.setChecked(False)
cls.__ui_mainwindow.radioButton_8.setAutoExclusive(False)
cls.__ui_mainwindow.radioButton_8.setChecked(False)
cls.__ui_mainwindow.radioButton_9.setAutoExclusive(False)
cls.__ui_mainwindow.radioButton_9.setChecked(False)
cls.__ui_mainwindow.radioButton_10.setAutoExclusive(False)
cls.__ui_mainwindow.radioButton_10.setChecked(False)
@classmethod
def refresh_create_essay_question_page(cls):
cls.__ui_mainwindow.textEdit_19.clear()
cls.__ui_mainwindow.lineEdit_26.clear()
cls.__ui_mainwindow.lineEdit_27.clear()
@classmethod
def refresh_create_exam_page(cls):
cls.__ui_mainwindow.tableWidget_3.clear()
cls.__ui_mainwindow.tableWidget_4.clear()
cls.__ui_mainwindow.lineEdit_10.clear()
cls.__ui_mainwindow.lineEdit_11.clear()
cls.__ui_mainwindow.lineEdit_12.clear()
cls.__ui_mainwindow.lineEdit_13.clear()
@classmethod
def get_question_id_to_load(cls):
question_id_text = cls.__ui_mainwindow.lineEdit_5.text()
try:
question_id = int(question_id_text)
return question_id
except:
return None
@classmethod
def load_single_answer_question_details(cls, question_details):
question_id = question_details[0]
question_type = question_details[1]
points = question_details[2]
year_level = question_details[3]
question_tag = question_details[4]
question_body = question_details[5]
option_A_text = question_details[6]
option_B_text = question_details[7]
option_C_text = question_details[8]
option_D_text = question_details[9]
option_E_text = question_details[10]
correct_answer = question_details[11]
cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)
)
cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(
question_type))
cls.__ui_mainwindow.textEdit_7.setText(question_body)
cls.__ui_mainwindow.textEdit_8.setText(option_A_text)
cls.__ui_mainwindow.textEdit_9.setText(option_B_text)
cls.__ui_mainwindow.textEdit_10.setText(option_C_text)
cls.__ui_mainwindow.textEdit_11.setText(option_D_text)
cls.__ui_mainwindow.textEdit_20.setText(option_E_text)
cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))
cls.__ui_mainwindow.lineEdit_8.setText(question_tag)
cls.__ui_mainwindow.lineEdit_28.setText(str(points))
if correct_answer == 'A':
cls.__ui_mainwindow.radioButton_6.setChecked(True)
elif correct_answer == 'B':
cls.__ui_mainwindow.radioButton_7.setChecked(True)
elif correct_answer == 'C':
cls.__ui_mainwindow.radioButton_8.setChecked(True)
elif correct_answer == 'D':
cls.__ui_mainwindow.radioButton_9.setChecked(True)
elif correct_answer == 'E':
cls.__ui_mainwindow.radioButton_10.setChecked(True)
@classmethod
def load_multiple_answers_question_details(cls, question_details):
question_id = question_details[0]
question_type = question_details[1]
points = question_details[2]
year_level = question_details[3]
question_tag = question_details[4]
question_body = question_details[5]
option_A_text = question_details[6]
option_B_text = question_details[7]
option_C_text = question_details[8]
option_D_text = question_details[9]
option_E_text = question_details[10]
correct_answers = question_details[11]
cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)
)
cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(
question_type))
cls.__ui_mainwindow.textEdit_7.setText(question_body)
cls.__ui_mainwindow.textEdit_8.setText(option_A_text)
cls.__ui_mainwindow.textEdit_9.setText(option_B_text)
cls.__ui_mainwindow.textEdit_10.setText(option_C_text)
cls.__ui_mainwindow.textEdit_11.setText(option_D_text)
cls.__ui_mainwindow.textEdit_20.setText(option_E_text)
cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))
cls.__ui_mainwindow.lineEdit_8.setText(question_tag)
cls.__ui_mainwindow.lineEdit_28.setText(str(points))
if correct_answers.count('A') == 1:
cls.__ui_mainwindow.radioButton_6.setChecked(True)
if correct_answers.count('B') == 1:
cls.__ui_mainwindow.radioButton_7.setChecked(True)
if correct_answers.count('C') == 1:
cls.__ui_mainwindow.radioButton_8.setChecked(True)
if correct_answers.count('D') == 1:
cls.__ui_mainwindow.radioButton_9.setChecked(True)
if correct_answers.count('E') == 1:
cls.__ui_mainwindow.radioButton_10.setChecked(True)
@classmethod
def load_essay_question_details(cls, question_details):
question_id = question_details[0]
question_type = question_details[1]
points = question_details[2]
year_level = question_details[3]
question_tag = question_details[4]
question_body = question_details[5]
cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)
)
cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(
question_type))
cls.__ui_mainwindow.textEdit_7.setText(question_body)
cls.__ui_mainwindow.radioButton_6.setDisabled(True)
cls.__ui_mainwindow.radioButton_7.setDisabled(True)
cls.__ui_mainwindow.radioButton_8.setDisabled(True)
cls.__ui_mainwindow.radioButton_9.setDisabled(True)
cls.__ui_mainwindow.radioButton_10.setDisabled(True)
cls.__ui_mainwindow.textEdit_8.setDisabled(True)
cls.__ui_mainwindow.textEdit_9.setDisabled(True)
cls.__ui_mainwindow.textEdit_10.setDisabled(True)
cls.__ui_mainwindow.textEdit_11.setDisabled(True)
cls.__ui_mainwindow.textEdit_20.setDisabled(True)
cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))
cls.__ui_mainwindow.lineEdit_8.setText(question_tag)
cls.__ui_mainwindow.lineEdit_28.setText(str(points))
@classmethod
def display_question_id_invalid_to_load_message(cls):
cls.__ui_mainwindow.label_12.setText('Invalid Question ID To Load')
@classmethod
def display_modification_success_message(cls):
cls.__ui_mainwindow.label_57.setText('Modification Success')
@classmethod
def display_invalid_school_class_id_message(cls):
cls.__ui_mainwindow.label_14.setText('Invalid School Class ID')
cls.__ui_mainwindow.tableWidget_15.clear()
@classmethod
def get_question_type_to_modify(cls):
question_type_text = cls.__ui_mainwindow.label_47.text()
if question_type_text == 'Question Type: Single Answer':
return 'Single Answer'
elif question_type_text == 'Question Type: Multiple Answers':
return 'Multiple Answers'
elif question_type_text == 'Question Type: Essay':
return 'Essay'
@classmethod
def get_single_answer_question_details_to_modify(cls):
question_pk = cls.get_question_id_to_modify()
question_type = cls.get_question_type_to_modify()
points = int(cls.__ui_mainwindow.lineEdit_28.text())
year_level = int(cls.__ui_mainwindow.lineEdit_6.text())
question_tag = cls.__ui_mainwindow.lineEdit_8.text()
question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()
option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()
option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()
option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()
option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()
option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()
correct_answer = cls.get_single_correct_answer_to_modify()
if correct_answer == None:
return None
return (question_pk, question_type, points, year_level,
question_tag, question_body, option_A_text, option_B_text,
option_C_text, option_D_text, option_E_text, correct_answer)
@classmethod
def get_multiple_answers_question_details_to_modify(cls):
question_pk = cls.get_question_id_to_modify()
question_type = cls.get_question_type_to_modify()
points = int(cls.__ui_mainwindow.lineEdit_28.text())
year_level = int(cls.__ui_mainwindow.lineEdit_6.text())
question_tag = cls.__ui_mainwindow.lineEdit_8.text()
question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()
option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()
option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()
option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()
option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()
option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()
correct_answers = cls.get_multiple_correct_answers_to_modify()
if correct_answers == None:
return None
return (question_pk, question_type, points, year_level,
question_tag, question_body, option_A_text, option_B_text,
option_C_text, option_D_text, option_E_text, correct_answers)
@classmethod
def get_essay_question_details_to_modify(cls):
question_pk = cls.get_question_id_to_modify()
question_type = cls.get_question_type_to_modify()
try:
points = int(cls.__ui_mainwindow.lineEdit_28.text())
except:
return None
try:
year_level = int(cls.__ui_mainwindow.lineEdit_6.text())
except:
return None
question_tag = cls.__ui_mainwindow.lineEdit_8.text()
if question_tag == '':
return None
question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()
if question_body == '':
return None
return (question_pk, question_type, points, year_level,
question_tag, question_body)
@classmethod
def get_question_id_to_modify(cls):
question_id_text = cls.__ui_mainwindow.label_45.text()
question_id_text_split = question_id_text.split()
question_id = int(question_id_text_split.pop())
return question_id
<|reserved_special_token_0|>
@classmethod
def get_multiple_correct_answers_to_modify(cls):
correct_answers = ''
if cls.__ui_mainwindow.radioButton_6.isChecked():
correct_answers = correct_answers + 'A'
if cls.__ui_mainwindow.radioButton_7.isChecked():
correct_answers = correct_answers + 'B'
if cls.__ui_mainwindow.radioButton_8.isChecked():
correct_answers = correct_answers + 'C'
if cls.__ui_mainwindow.radioButton_9.isChecked():
correct_answers = correct_answers + 'D'
if cls.__ui_mainwindow.radioButton_10.isChecked():
correct_answers = correct_answers + 'E'
if len(correct_answers) == 0:
return None
if len(correct_answers) > 4:
return None
return correct_answers
@classmethod
def get_school_class_id_to_view_students(cls):
school_class_id_text = cls.__ui_mainwindow.lineEdit_9.text()
try:
school_class_id = int(school_class_id_text)
return school_class_id
except:
return None
@classmethod
def display_school_class_details(cls, school_class_details):
cls.__ui_mainwindow.tableWidget_15.clear()
row = 0
col = 0
for student, in school_class_details:
student_item = QTableWidgetItem(student)
cls.__ui_mainwindow.tableWidget_15.setItem(row, col, student_item)
if col >= 1:
col = 0
row += 1
else:
col += 1
@classmethod
def refresh_view_school_class_details_page(cls):
cls.__ui_mainwindow.label_14.clear()
<|reserved_special_token_0|>
@classmethod
def get_number_of_school_classes_in_current_exam(cls):
number_of_school_classes = 0
row = 0
col = 0
for counter in range(5):
if cls.__ui_mainwindow.tableWidget_4.item(row, col) != None:
number_of_school_classes += 1
row += 1
return number_of_school_classes
@classmethod
def display_number_of_questions_full_in_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText(
'Questions Are Full In Current Exam')
@classmethod
def display_number_of_school_classes_full_in_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText(
'School Classes Are Full In Current Exam')
@classmethod
def display_no_question_in_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText('No Question In Current Exam')
@classmethod
def display_no_school_class_in_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText('No School Class In Current Exam')
<|reserved_special_token_0|>
@classmethod
def display_school_class_id_already_added_to_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText(
'School Class ID Already Added To Current Exam')
@classmethod
def display_question_id_invalid_message(cls):
cls.__ui_mainwindow.label_17.setText('Question ID Invalid')
@classmethod
def display_school_class_id_invalid_message(cls):
cls.__ui_mainwindow.label_17.setText('School CLass ID Invalid')
@classmethod
def display_question_id_not_already_in_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText(
'Question ID Not Aleady In Current Exam')
@classmethod
def display_school_class_id_not_already_in_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText(
'School Class ID Not Aleady In Current Exam')
@classmethod
def display_create_exam_success_message(cls):
cls.__ui_mainwindow.label_17.setText('Create Exam Success')
@classmethod
def refresh_mark_exam_drop_box(cls):
cls.__ui_mainwindow.tableWidget_19.clear()
@classmethod
def get_question_id_to_add_to_exam(cls):
question_id_text = cls.__ui_mainwindow.lineEdit_10.text()
try:
question_id = int(question_id_text)
return question_id
except:
return None
@classmethod
def get_school_class_id_to_add_to_exam(cls):
school_class_id_text = cls.__ui_mainwindow.lineEdit_11.text()
try:
school_class_id = int(school_class_id_text)
return school_class_id
except:
return None
@classmethod
def get_question_id_to_remove_from_exam(cls):
question_id_text = cls.__ui_mainwindow.lineEdit_12.text()
try:
question_id = int(question_id_text)
return question_id
except:
return None
@classmethod
def get_school_class_id_to_remove_from_exam(cls):
school_class_id_text = cls.__ui_mainwindow.lineEdit_13.text()
try:
school_class_id = int(school_class_id_text)
return school_class_id
except:
return None
@classmethod
def add_question_id_to_current_exam(cls, question_id):
row = 0
col = 0
for counter in range(10):
if cls.__ui_mainwindow.tableWidget_3.item(row, col) == None:
question_text = 'Question ' + str(question_id)
question_item = QTableWidgetItem(question_text)
cls.__ui_mainwindow.tableWidget_3.setItem(row, col,
question_item)
cls.__ui_mainwindow.lineEdit_10.clear()
cls.__ui_mainwindow.label_17.clear()
return
row += 1
@classmethod
def add_school_class_id_to_current_exam(cls, school_class_id):
row = 0
col = 0
for counter in range(10):
if cls.__ui_mainwindow.tableWidget_4.item(row, col) == None:
school_class_text = 'CLass ' + str(school_class_id)
school_class_item = QTableWidgetItem(school_class_text)
cls.__ui_mainwindow.tableWidget_4.setItem(row, col,
school_class_item)
cls.__ui_mainwindow.lineEdit_11.clear()
cls.__ui_mainwindow.label_17.clear()
return
row += 1
@classmethod
def remove_question_id_from_current_exam(cls, question_id):
col = 0
for row in range(10):
question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)
if question_item != None:
question_text = question_item.text()
question_text_split = question_text.split(' ')
question_id_in_exam = int(question_text_split.pop())
if question_id_in_exam == question_id:
cls.__ui_mainwindow.tableWidget_3.takeItem(row, col)
cls.__ui_mainwindow.lineEdit_12.clear()
cls.__ui_mainwindow.label_17.clear()
return
@classmethod
def remove_school_class_id_from_current_exam(cls, school_class_id):
col = 0
for row in range(5):
school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col
)
if school_class_item != None:
school_class_text = school_class_item.text()
school_class_text_split = school_class_text.split(' ')
school_class_id_in_exam = int(school_class_text_split.pop())
if school_class_id_in_exam == school_class_id:
cls.__ui_mainwindow.tableWidget_4.takeItem(row, col)
cls.__ui_mainwindow.lineEdit_13.clear()
cls.__ui_mainwindow.label_17.clear()
return
<|reserved_special_token_0|>
@classmethod
def is_school_class_id_already_added_to_current_exam(cls, school_class_id):
string_of_school_classes_ids_in_current_exam = (cls.
get_string_of_school_classes_ids_in_current_exam())
list_of_school_classes_ids = (
string_of_school_classes_ids_in_current_exam.split(' '))
return list_of_school_classes_ids.count(str(school_class_id)) == 1
@classmethod
def get_string_of_question_ids_in_current_exam(cls):
string_of_question_ids = ''
col = 0
for row in range(10):
question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)
if question_item != None:
question_text = question_item.text()
question_text_split = question_text.split(' ')
question_id = question_text_split.pop()
string_of_question_ids = (string_of_question_ids +
question_id + ' ')
return string_of_question_ids.rstrip()
@classmethod
def get_string_of_school_classes_ids_in_current_exam(cls):
string_of_school_classes_ids = ''
col = 0
for row in range(10):
school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col
)
if school_class_item != None:
school_class_text = school_class_item.text()
school_class_text_split = school_class_text.split(' ')
school_class_id = school_class_text_split.pop()
string_of_school_classes_ids = (
string_of_school_classes_ids + school_class_id + ' ')
return string_of_school_classes_ids.rstrip()
@classmethod
def get_exam_id_to_mark(cls):
exam_item = cls.__ui_mainwindow.tableWidget_20.item(0, 0)
exam_text = exam_item.text()
exam_text_split = exam_text.split(' ')
exam_id_text = exam_text_split.pop()
return int(exam_id_text)
<|reserved_special_token_0|>
@classmethod
def display_students_full_names_with_questions_ready_to_be_marked(cls,
students_names_list):
cls.__ui_mainwindow.tableWidget_6.clear()
row = 0
col = 0
for student_name in students_names_list:
student_item = QTableWidgetItem(student_name)
cls.__ui_mainwindow.tableWidget_6.setItem(row, col, student_item)
if col >= 4:
row += 1
col = 0
else:
col += 1
@classmethod
def get_student_name_to_mark_answers(cls):
student_item = cls.__ui_mainwindow.tableWidget_19.item(0, 0)
student_name = student_item.text()
return student_name
@classmethod
def get_exam_id_to_mark_student_answers(cls):
exam_id_text = cls.__ui_mainwindow.label_49.text()
exam_id_text_split = exam_id_text.split(' ')
exam_id = exam_id_text_split.pop()
return int(exam_id)
<|reserved_special_token_0|>
@classmethod
def display_student_id_on_mark_student_answers_page(cls, student_id):
student_id_text = 'Student ID: ' + str(student_id)
cls.__ui_mainwindow.label_63.setText(student_id_text)
@classmethod
def display_student_name_on_mark_student_answers_page(cls, student_name):
student_name_text = 'Student Name: ' + str(student_name)
cls.__ui_mainwindow.label_50.setText(student_name_text)
@classmethod
def display_questions_ready_to_be_marked(cls, questions_ids_tuple):
cls.__ui_mainwindow.tableWidget_25.clear()
row = 0
col = 0
for question_id, in questions_ids_tuple:
question_text = 'Question ' + str(question_id)
question_item = QTableWidgetItem(question_text)
cls.__ui_mainwindow.tableWidget_25.setItem(row, col, question_item)
row += 1
<|reserved_special_token_0|>
@classmethod
def get_exam_id_on_marking_question_page(cls):
exam_id_text = cls.__ui_mainwindow.label_62.text()
exam_id_text_list = exam_id_text.split(' ')
exam_id = exam_id_text_list.pop()
return int(exam_id)
@classmethod
def get_student_id_on_marking_question_page(cls):
student_id_text = cls.__ui_mainwindow.label_63.text()
student_id_text_list = student_id_text.split(' ')
student_id = student_id_text_list.pop()
return int(student_id)
<|reserved_special_token_0|>
@classmethod
def get_essay_question_marked_points(cls):
points_text = cls.__ui_dialog.lineEdit.text()
return int(points_text)
@classmethod
def refresh_drop_question_to_mark_box(cls):
cls.__ui_mainwindow.tableWidget_26.clear()
@classmethod
def refresh_mark_student_questions_answers_page(cls):
cls.__ui_mainwindow.label_62.clear()
cls.__ui_mainwindow.label_63.clear()
cls.__ui_mainwindow.label_50.clear()
@classmethod
def display_no_more_questions_to_mark_message(cls):
cls.__ui_mainwindow.label_66.setText('No More Questions To Mark')
@classmethod
def display_marked_exams(cls, marked_exams_ids):
cls.__ui_mainwindow.tableWidget_18.clear()
row = 0
col = 0
for exam_id, in marked_exams_ids:
exam_text = 'Exam ' + str(exam_id)
exam_item = QTableWidgetItem(exam_text)
cls.__ui_mainwindow.tableWidget_18.setItem(row, col, exam_item)
if col >= 4:
row += 1
col = 0
else:
col += 1
@classmethod
def display_no_question_selected_to_mark_message(cls):
cls.__ui_mainwindow.label_66.setText('No Question Selected To Mark')
@classmethod
def refresh_drop_student_to_mark_questions_box(cls):
cls.__ui_mainwindow.tableWidget_19.clear()
@classmethod
def get_exam_id_to_release_result(cls):
exam_item = cls.__ui_mainwindow.tableWidget_21.item(0, 0)
if exam_item == None:
return None
exam_id_text = exam_item.text()
exam_id_text_list = exam_id_text.split(' ')
exam_id = exam_id_text_list.pop()
return int(exam_id)
@classmethod
def display_result_released_exams(cls, result_released_exams_ids):
cls.__ui_mainwindow.tableWidget_11.clear()
row = 0
col = 0
for exam_id, in result_released_exams_ids:
exam_text = 'Exam ' + str(exam_id) + ' Result'
exam_item = QTableWidgetItem(exam_text)
cls.__ui_mainwindow.tableWidget_11.setItem(row, col, exam_item)
if col >= 9:
row += 1
col = 0
else:
col += 1
@classmethod
def refresh_drop_exam_to_release_result_box(cls):
cls.__ui_mainwindow.tableWidget_21.clear()
@classmethod
def display_exam_results(cls, exam_results_ids):
cls.__ui_mainwindow.tableWidget_11.clear()
row = 0
col = 0
for exam_result_id, in exam_results_ids:
exam_result_text = 'Exam ' + str(exam_result_id) + ' Result'
exam_result_item = QTableWidgetItem(exam_result_text)
cls.__ui_mainwindow.tableWidget_11.setItem(row, col,
exam_result_item)
if col >= 9:
row += 1
col = 0
else:
col += 1
@classmethod
def get_exam_result_id_to_load_details(cls):
exam_result_id_text = cls.__ui_mainwindow.lineEdit_22.text()
return int(exam_result_id_text)
<|reserved_special_token_0|>
@classmethod
def display_exam_result_id_on_view_exam_result_details_page(cls,
exam_result_id):
cls.__ui_mainwindow.label_33.setText('Exam Result ID: ' + str(
exam_result_id))
@classmethod
def get_school_class_id_to_view_exam_result(cls):
school_class_id_text = cls.__ui_mainwindow.lineEdit_23.text()
try:
school_class_id = int(school_class_id_text)
except:
return None
return school_class_id
@classmethod
def display_students_full_names_to_view_exam_result(cls,
students_full_names):
cls.__ui_mainwindow.tableWidget_13.clear()
row = 0
col = 0
for student_full_name, in students_full_names:
student_item = QTableWidgetItem(student_full_name)
cls.__ui_mainwindow.tableWidget_13.setItem(row, col, student_item)
row += 1
<|reserved_special_token_0|>
@classmethod
def get_exam_result_id_on_view_exam_result_page(cls):
exam_result_id_text = cls.__ui_mainwindow.label_33.text()
exam_result_id_text_list = exam_result_id_text.split(' ')
exam_result_id = exam_result_id_text_list.pop()
try:
exam_result_id_int = int(exam_result_id)
return exam_result_id_int
except:
return None
@classmethod
def display_student_exam_result_details(cls, exam_result_details):
student_id = exam_result_details[0]
student_full_name = exam_result_details[1]
date_of_birth = exam_result_details[2]
school_class_id = exam_result_details[3]
exam_id = exam_result_details[4]
total_available_points = exam_result_details[5]
total_points_gained = exam_result_details[6]
average_percentage_mark = exam_result_details[7]
cls.__ui_mainwindow.label_58.setText(str(student_id))
cls.__ui_mainwindow.label_72.setText(str(student_full_name))
cls.__ui_mainwindow.label_75.setText(str(date_of_birth))
cls.__ui_mainwindow.label_76.setText(str(school_class_id))
cls.__ui_mainwindow.label_77.setText(str(exam_id))
cls.__ui_mainwindow.label_78.setText(str(total_available_points))
cls.__ui_mainwindow.label_79.setText(str(total_points_gained))
cls.__ui_mainwindow.label_80.setText(str(average_percentage_mark) +
' %')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
@classmethod
def display_questions_on_view_exam_details_page(cls, questions_ids):
cls.__ui_mainwindow.tableWidget_7.clear()
questions_ids_list = cls.make_string_to_list(questions_ids)
row = 0
col = 0
for question_id in questions_ids_list:
question_text = 'Question ' + str(question_id)
question_item = QTableWidgetItem(question_text)
cls.__ui_mainwindow.tableWidget_7.setItem(row, col, question_item)
row += 1
@classmethod
def display_first_school_class_details_on_view_exam_details_page(cls,
school_class_id, students_full_names):
cls.display_first_school_class_id_on_view_exam_details_page(
school_class_id)
cls.__ui_mainwindow.tableWidget_27.clear()
row = 0
col = 0
for student_name, in students_full_names:
student_item = QTableWidgetItem(student_name)
cls.__ui_mainwindow.tableWidget_27.setItem(row, col, student_item)
row += 1
@classmethod
def display_first_school_class_id_on_view_exam_details_page(cls,
school_class_id):
cls.__ui_mainwindow.label_67.setText('CLass ' + str(school_class_id))
@classmethod
def display_second_school_class_details_on_view_exam_details_page(cls,
school_class_id, students_full_names):
cls.display_second_school_class_id_on_view_exam_details_page(
school_class_id)
cls.__ui_mainwindow.tableWidget_28.clear()
row = 0
col = 0
for student_name, in students_full_names:
student_item = QTableWidgetItem(student_name)
cls.__ui_mainwindow.tableWidget_28.setItem(row, col, student_item)
row += 1
@classmethod
def display_second_school_class_id_on_view_exam_details_page(cls,
school_class_id):
cls.__ui_mainwindow.label_68.setText('CLass ' + str(school_class_id))
@classmethod
def display_third_school_class_details_on_view_exam_details_page(cls,
school_class_id, students_full_names):
cls.display_third_school_class_id_on_view_exam_details_page(
school_class_id)
cls.__ui_mainwindow.tableWidget_29.clear()
row = 0
col = 0
for student_name, in students_full_names:
student_item = QTableWidgetItem(student_name)
cls.__ui_mainwindow.tableWidget_29.setItem(row, col, student_item)
row += 1
@classmethod
def display_third_school_class_id_on_view_exam_details_page(cls,
school_class_id):
cls.__ui_mainwindow.label_69.setText('CLass ' + str(school_class_id))
@classmethod
def display_fourth_school_class_details_on_view_exam_details_page(cls,
school_class_id, students_full_names):
cls.display_fourth_school_class_id_on_view_exam_details_page(
school_class_id)
cls.__ui_mainwindow.tableWidget_30.clear()
row = 0
col = 0
for student_name, in students_full_names:
student_item = QTableWidgetItem(student_name)
cls.__ui_mainwindow.tableWidget_30.setItem(row, col, student_item)
row += 1
@classmethod
def display_fourth_school_class_id_on_view_exam_details_page(cls,
school_class_id):
cls.__ui_mainwindow.label_70.setText('CLass ' + str(school_class_id))
@classmethod
def display_fifth_school_class_details_on_view_exam_details_page(cls,
school_class_id, students_full_names):
cls.display_fifth_school_class_id_on_view_exam_details_page(
school_class_id)
cls.__ui_mainwindow.tableWidget_31.clear()
row = 0
col = 0
for student_name, in students_full_names:
student_item = QTableWidgetItem(student_name)
cls.__ui_mainwindow.tableWidget_31.setItem(row, col, student_item)
row += 1
@classmethod
def display_fifth_school_class_id_on_view_exam_details_page(cls,
school_class_id):
cls.__ui_mainwindow.label_71.setText('CLass ' + str(school_class_id))
@classmethod
def make_string_to_list(cls, any_string):
any_string = str(any_string)
any_list = any_string.split(' ')
return any_list
@classmethod
def refresh_drop_student_to_view_exam_result_details_box(cls):
cls.__ui_mainwindow.tableWidget_22.clear()
@classmethod
def display_exam_result_id_invalid_message(cls):
cls.__ui_mainwindow.label_32.setText('Exam Result ID Invalid')
@classmethod
def refresh_load_exam_result_details_page(cls):
cls.__ui_mainwindow.label_33.clear()
cls.__ui_mainwindow.tableWidget_12.clear()
cls.__ui_mainwindow.lineEdit_23.clear()
cls.__ui_mainwindow.tableWidget_13.clear()
cls.__ui_mainwindow.tableWidget_22.clear()
cls.__ui_mainwindow.label_58.clear()
cls.__ui_mainwindow.label_72.clear()
cls.__ui_mainwindow.label_75.clear()
cls.__ui_mainwindow.label_76.clear()
cls.__ui_mainwindow.label_77.clear()
cls.__ui_mainwindow.label_78.clear()
cls.__ui_mainwindow.label_79.clear()
cls.__ui_mainwindow.label_80.clear()
@classmethod
def refresh_exam_result_id_validity_error_message(cls):
cls.__ui_mainwindow.label_32.clear()
@classmethod
def display_school_class_id_invalid_to_view_result_message(cls):
cls.__ui_mainwindow.label_81.setText('School Class ID Invalid To View')
@classmethod
def refresh_school_class_details_table_on_view_exam_result_page(cls):
cls.__ui_mainwindow.tableWidget_13.clear()
@classmethod
def refresh_school_class_id_invalid_to_view_exam_result_error_label(cls):
cls.__ui_mainwindow.label_81.clear()
<|reserved_special_token_0|>
@classmethod
def display_no_exam_result_id_selected_message(cls):
cls.__ui_mainwindow.label_81.setText('No Exam Result ID Selected')
@classmethod
def refresh_school_class_id_input_box_on_view_exam_result_details_page(cls
):
cls.__ui_mainwindow.lineEdit_23.clear()
@classmethod
def refresh_view_exam_details_by_id_page(cls):
cls.__ui_mainwindow.label_18.setText('Exam ID : ')
cls.__ui_mainwindow.tableWidget_7.clear()
cls.__ui_mainwindow.label_67.clear()
cls.__ui_mainwindow.label_68.clear()
cls.__ui_mainwindow.label_69.clear()
cls.__ui_mainwindow.label_70.clear()
cls.__ui_mainwindow.label_71.clear()
cls.__ui_mainwindow.tableWidget_27.clear()
cls.__ui_mainwindow.tableWidget_28.clear()
cls.__ui_mainwindow.tableWidget_29.clear()
cls.__ui_mainwindow.tableWidget_30.clear()
cls.__ui_mainwindow.tableWidget_31.clear()
@classmethod
def refresh_students_table_on_view_exam_result_details_page(cls):
cls.__ui_mainwindow.tableWidget_13.clear()
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class TeacherGUI:
def __init__(self):
pass
@classmethod
def setup(cls, ui_mainwindow):
cls.__ui_mainwindow = ui_mainwindow
@classmethod
def display_all_active_school_classes(cls, school_classes):
cls.__ui_mainwindow.tableWidget_14.clear()
row = 0
col = 0
for school_class_id, in school_classes:
school_class_text = 'Class ' + str(school_class_id)
school_class_item = QTableWidgetItem(school_class_text)
cls.__ui_mainwindow.tableWidget_14.setItem(row, col,
school_class_item)
if col >= 4:
col = 0
row += 1
else:
col += 1
@classmethod
def display_all_exams(cls, all_exams):
cls.__ui_mainwindow.tableWidget_5.clear()
row = 0
col = 0
for exam_id, in all_exams:
exam_text = 'Exam ' + str(exam_id)
exam_item = QTableWidgetItem(exam_text)
cls.__ui_mainwindow.tableWidget_5.setItem(row, col, exam_item)
if col >= 9:
col = 0
row += 1
else:
col += 1
@classmethod
def display_not_completed_exams(cls, not_completed_exams):
cls.__ui_mainwindow.tableWidget_16.clear()
row = 0
col = 0
for exam_id, in not_completed_exams:
exam_text = 'Exam ' + str(exam_id)
exam_item = QTableWidgetItem(exam_text)
cls.__ui_mainwindow.tableWidget_16.setItem(row, col, exam_item)
if col >= 6:
col = 0
row += 1
else:
col += 1
@classmethod
def display_ready_to_be_marked_exams(cls, ready_to_be_marked_exams):
cls.__ui_mainwindow.tableWidget_17.clear()
row = 0
col = 0
for exam_id, in ready_to_be_marked_exams:
exam_text = 'Exam ' + str(exam_id)
exam_item = QTableWidgetItem(exam_text)
cls.__ui_mainwindow.tableWidget_17.setItem(row, col, exam_item)
if col >= 3:
col = 0
row += 1
else:
col += 1
@classmethod
def display_single_answer_question_dialog_preview(cls):
question_body = cls.__ui_mainwindow.textEdit.toPlainText()
option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()
option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()
option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()
option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()
option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()
cls.__dialog = QtWidgets.QDialog()
cls.__ui_dialog = Ui_SingleAnswerQuestionDialog()
cls.__ui_dialog.setupUi(cls.__dialog)
cls.__ui_dialog.label.setText(question_body)
cls.__ui_dialog.label_3.setText('A ' + option_A_text)
cls.__ui_dialog.label_4.setText('B ' + option_B_text)
cls.__ui_dialog.label_5.setText('C ' + option_C_text)
cls.__ui_dialog.label_6.setText('D ' + option_D_text)
cls.__ui_dialog.label_7.setText('E ' + option_E_text)
cls.__dialog.show()
cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)
@classmethod
def display_multiple_answers_question_dialog_preview(cls):
question_body = cls.__ui_mainwindow.textEdit_14.toPlainText()
option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText()
option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText()
option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText()
option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText()
option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText()
cls.__dialog = QtWidgets.QDialog()
cls.__ui_dialog = Ui_MultipleAnswersQuestionDialog()
cls.__ui_dialog.setupUi(cls.__dialog)
cls.__ui_dialog.label.setText(question_body)
cls.__ui_dialog.label_3.setText(option_A_text)
cls.__ui_dialog.label_4.setText(option_B_text)
cls.__ui_dialog.label_5.setText(option_C_text)
cls.__ui_dialog.label_6.setText(option_D_text)
cls.__ui_dialog.label_7.setText(option_E_text)
cls.__dialog.show()
cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)
@classmethod
def display_essay_question_dialog_preview(cls):
question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()
cls.__dialog = QtWidgets.QDialog()
cls.__ui_dialog = Ui_EssayQuestionDialog()
cls.__ui_dialog.setupUi(cls.__dialog)
if question_body == '':
cls.__ui_dialog.label.setText('Question Body')
else:
cls.__ui_dialog.label.setText(question_body)
cls.__dialog.show()
cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)
@classmethod
def close_dialog(cls):
cls.__dialog.close()
@classmethod
def get_single_answer_question_details(cls):
question_body = cls.__ui_mainwindow.textEdit.toPlainText()
if question_body == '':
return None
option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()
if option_A_text == '':
return None
option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()
if option_B_text == '':
return None
option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()
if option_C_text == '':
return None
option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()
if option_D_text == '':
return None
option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()
if option_E_text == '':
return None
year_level_text = cls.__ui_mainwindow.lineEdit_3.text()
if year_level_text == '':
return None
try:
year_level = int(year_level_text)
except:
return None
phrase_tag_text = cls.__ui_mainwindow.lineEdit_4.text()
if phrase_tag_text == '':
return None
correct_answers_list = []
if cls.__ui_mainwindow.radioButton.isChecked():
correct_answers_list.append('A')
if cls.__ui_mainwindow.radioButton_2.isChecked():
correct_answers_list.append('B')
if cls.__ui_mainwindow.radioButton_5.isChecked():
correct_answers_list.append('C')
if cls.__ui_mainwindow.radioButton_3.isChecked():
correct_answers_list.append('D')
if cls.__ui_mainwindow.radioButton_4.isChecked():
correct_answers_list.append('E')
if correct_answers_list == []:
return None
if len(correct_answers_list) > 1:
return None
return (question_body, option_A_text, option_B_text, option_C_text,
option_D_text, option_E_text, year_level, phrase_tag_text,
correct_answers_list)
@classmethod
def get_multiple_answers_question_details(cls):
question_body = cls.__ui_mainwindow.textEdit_14.toPlainText()
if question_body == '':
return None
option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText()
if option_A_text == '':
return None
option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText()
if option_B_text == '':
return None
option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText()
if option_C_text == '':
return None
option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText()
if option_D_text == '':
return None
option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText()
if option_E_text == '':
return None
year_level_text = cls.__ui_mainwindow.lineEdit_25.text()
if year_level_text == '':
return None
try:
year_level = int(year_level_text)
except:
return None
phrase_tag_text = cls.__ui_mainwindow.lineEdit_7.text()
if phrase_tag_text == '':
return None
correct_answers_list = []
if cls.__ui_mainwindow.checkBox.isChecked():
correct_answers_list.append('A')
if cls.__ui_mainwindow.checkBox_2.isChecked():
correct_answers_list.append('B')
if cls.__ui_mainwindow.checkBox_3.isChecked():
correct_answers_list.append('C')
if cls.__ui_mainwindow.checkBox_4.isChecked():
correct_answers_list.append('D')
if cls.__ui_mainwindow.checkBox_5.isChecked():
correct_answers_list.append('E')
if correct_answers_list == []:
return None
if len(correct_answers_list) > 4:
return None
return (question_body, option_A_text, option_B_text, option_C_text,
option_D_text, option_E_text, year_level, phrase_tag_text,
correct_answers_list)
@classmethod
def get_essay_question_details(cls):
question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()
if question_body == '':
return None
year_level_text = cls.__ui_mainwindow.lineEdit_26.text()
if year_level_text == '':
return None
try:
year_level = int(year_level_text)
except:
return None
phrase_tag_text = cls.__ui_mainwindow.lineEdit_27.text()
if phrase_tag_text == '':
return None
return question_body, year_level, phrase_tag_text
@classmethod
def display_all_active_questions(cls, active_questions_tuple):
row = 0
col = 0
for question_pk_tuple in active_questions_tuple:
question_pk = question_pk_tuple[0]
question_text = 'Question ' + str(question_pk)
question_item = QTableWidgetItem(question_text)
cls.__ui_mainwindow.tableWidget.setItem(row, col, question_item)
if col >= 7:
col = 0
row += 1
else:
col += 1
@classmethod
def display_create_single_answer_question_success(cls):
cls.__ui_mainwindow.label_4.setText(
'Create Single Answer Question Success')
@classmethod
def display_invalid_single_answer_question_creation_message(cls):
cls.__ui_mainwindow.label_4.setText(
'Invalid Single Answer Question Creation')
@classmethod
def display_create_multiple_answers_question_success(cls):
cls.__ui_mainwindow.label_11.setText(
'Create Multiple Answers Question Success')
@classmethod
def display_invalid_multiple_answers_question_creation_message(cls):
cls.__ui_mainwindow.label_11.setText(
'Invalid Multiple Answers Question Creation')
@classmethod
def display_invalid_essay_question_creation_message(cls):
cls.__ui_mainwindow.label_42.setText('Invalid Essay Question Creation')
@classmethod
def display_create_essay_question_success(cls):
cls.__ui_mainwindow.label_42.setText('Create Essay Question Success')
@classmethod
def display_invalid_modification_message(cls):
cls.__ui_mainwindow.label_57.setText('Invalid Modification')
@classmethod
def refresh_create_single_answer_question_page(cls):
cls.__ui_mainwindow.textEdit.clear()
cls.__ui_mainwindow.textEdit_2.clear()
cls.__ui_mainwindow.textEdit_3.clear()
cls.__ui_mainwindow.textEdit_4.clear()
cls.__ui_mainwindow.textEdit_5.clear()
cls.__ui_mainwindow.textEdit_6.clear()
cls.__ui_mainwindow.lineEdit_3.clear()
cls.__ui_mainwindow.lineEdit_4.clear()
cls.__ui_mainwindow.radioButton.setChecked(False)
cls.__ui_mainwindow.radioButton_2.setChecked(False)
cls.__ui_mainwindow.radioButton_3.setChecked(False)
cls.__ui_mainwindow.radioButton_4.setChecked(False)
cls.__ui_mainwindow.radioButton_5.setChecked(False)
<|reserved_special_token_0|>
@classmethod
def refresh_view_or_modify_question_page(cls):
cls.__ui_mainwindow.lineEdit_5.clear()
cls.__ui_mainwindow.label_45.setText('Question ID: ')
cls.__ui_mainwindow.label_47.setText('Question Type: ')
cls.__ui_mainwindow.label_57.clear()
cls.__ui_mainwindow.label_12.clear()
cls.__ui_mainwindow.textEdit_7.clear()
cls.__ui_mainwindow.textEdit_8.clear()
cls.__ui_mainwindow.textEdit_9.clear()
cls.__ui_mainwindow.textEdit_10.clear()
cls.__ui_mainwindow.textEdit_11.clear()
cls.__ui_mainwindow.textEdit_20.clear()
cls.__ui_mainwindow.lineEdit_6.clear()
cls.__ui_mainwindow.lineEdit_8.clear()
cls.__ui_mainwindow.lineEdit_28.clear()
cls.__ui_mainwindow.radioButton_6.setDisabled(False)
cls.__ui_mainwindow.radioButton_7.setDisabled(False)
cls.__ui_mainwindow.radioButton_8.setDisabled(False)
cls.__ui_mainwindow.radioButton_9.setDisabled(False)
cls.__ui_mainwindow.radioButton_10.setDisabled(False)
cls.__ui_mainwindow.textEdit_8.setDisabled(False)
cls.__ui_mainwindow.textEdit_9.setDisabled(False)
cls.__ui_mainwindow.textEdit_10.setDisabled(False)
cls.__ui_mainwindow.textEdit_11.setDisabled(False)
cls.__ui_mainwindow.textEdit_20.setDisabled(False)
cls.__ui_mainwindow.radioButton_6.setAutoExclusive(False)
cls.__ui_mainwindow.radioButton_6.setChecked(False)
cls.__ui_mainwindow.radioButton_7.setAutoExclusive(False)
cls.__ui_mainwindow.radioButton_7.setChecked(False)
cls.__ui_mainwindow.radioButton_8.setAutoExclusive(False)
cls.__ui_mainwindow.radioButton_8.setChecked(False)
cls.__ui_mainwindow.radioButton_9.setAutoExclusive(False)
cls.__ui_mainwindow.radioButton_9.setChecked(False)
cls.__ui_mainwindow.radioButton_10.setAutoExclusive(False)
cls.__ui_mainwindow.radioButton_10.setChecked(False)
@classmethod
def refresh_create_essay_question_page(cls):
cls.__ui_mainwindow.textEdit_19.clear()
cls.__ui_mainwindow.lineEdit_26.clear()
cls.__ui_mainwindow.lineEdit_27.clear()
@classmethod
def refresh_create_exam_page(cls):
cls.__ui_mainwindow.tableWidget_3.clear()
cls.__ui_mainwindow.tableWidget_4.clear()
cls.__ui_mainwindow.lineEdit_10.clear()
cls.__ui_mainwindow.lineEdit_11.clear()
cls.__ui_mainwindow.lineEdit_12.clear()
cls.__ui_mainwindow.lineEdit_13.clear()
@classmethod
def get_question_id_to_load(cls):
question_id_text = cls.__ui_mainwindow.lineEdit_5.text()
try:
question_id = int(question_id_text)
return question_id
except:
return None
@classmethod
def load_single_answer_question_details(cls, question_details):
question_id = question_details[0]
question_type = question_details[1]
points = question_details[2]
year_level = question_details[3]
question_tag = question_details[4]
question_body = question_details[5]
option_A_text = question_details[6]
option_B_text = question_details[7]
option_C_text = question_details[8]
option_D_text = question_details[9]
option_E_text = question_details[10]
correct_answer = question_details[11]
cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)
)
cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(
question_type))
cls.__ui_mainwindow.textEdit_7.setText(question_body)
cls.__ui_mainwindow.textEdit_8.setText(option_A_text)
cls.__ui_mainwindow.textEdit_9.setText(option_B_text)
cls.__ui_mainwindow.textEdit_10.setText(option_C_text)
cls.__ui_mainwindow.textEdit_11.setText(option_D_text)
cls.__ui_mainwindow.textEdit_20.setText(option_E_text)
cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))
cls.__ui_mainwindow.lineEdit_8.setText(question_tag)
cls.__ui_mainwindow.lineEdit_28.setText(str(points))
if correct_answer == 'A':
cls.__ui_mainwindow.radioButton_6.setChecked(True)
elif correct_answer == 'B':
cls.__ui_mainwindow.radioButton_7.setChecked(True)
elif correct_answer == 'C':
cls.__ui_mainwindow.radioButton_8.setChecked(True)
elif correct_answer == 'D':
cls.__ui_mainwindow.radioButton_9.setChecked(True)
elif correct_answer == 'E':
cls.__ui_mainwindow.radioButton_10.setChecked(True)
@classmethod
def load_multiple_answers_question_details(cls, question_details):
question_id = question_details[0]
question_type = question_details[1]
points = question_details[2]
year_level = question_details[3]
question_tag = question_details[4]
question_body = question_details[5]
option_A_text = question_details[6]
option_B_text = question_details[7]
option_C_text = question_details[8]
option_D_text = question_details[9]
option_E_text = question_details[10]
correct_answers = question_details[11]
cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)
)
cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(
question_type))
cls.__ui_mainwindow.textEdit_7.setText(question_body)
cls.__ui_mainwindow.textEdit_8.setText(option_A_text)
cls.__ui_mainwindow.textEdit_9.setText(option_B_text)
cls.__ui_mainwindow.textEdit_10.setText(option_C_text)
cls.__ui_mainwindow.textEdit_11.setText(option_D_text)
cls.__ui_mainwindow.textEdit_20.setText(option_E_text)
cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))
cls.__ui_mainwindow.lineEdit_8.setText(question_tag)
cls.__ui_mainwindow.lineEdit_28.setText(str(points))
if correct_answers.count('A') == 1:
cls.__ui_mainwindow.radioButton_6.setChecked(True)
if correct_answers.count('B') == 1:
cls.__ui_mainwindow.radioButton_7.setChecked(True)
if correct_answers.count('C') == 1:
cls.__ui_mainwindow.radioButton_8.setChecked(True)
if correct_answers.count('D') == 1:
cls.__ui_mainwindow.radioButton_9.setChecked(True)
if correct_answers.count('E') == 1:
cls.__ui_mainwindow.radioButton_10.setChecked(True)
@classmethod
def load_essay_question_details(cls, question_details):
question_id = question_details[0]
question_type = question_details[1]
points = question_details[2]
year_level = question_details[3]
question_tag = question_details[4]
question_body = question_details[5]
cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)
)
cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(
question_type))
cls.__ui_mainwindow.textEdit_7.setText(question_body)
cls.__ui_mainwindow.radioButton_6.setDisabled(True)
cls.__ui_mainwindow.radioButton_7.setDisabled(True)
cls.__ui_mainwindow.radioButton_8.setDisabled(True)
cls.__ui_mainwindow.radioButton_9.setDisabled(True)
cls.__ui_mainwindow.radioButton_10.setDisabled(True)
cls.__ui_mainwindow.textEdit_8.setDisabled(True)
cls.__ui_mainwindow.textEdit_9.setDisabled(True)
cls.__ui_mainwindow.textEdit_10.setDisabled(True)
cls.__ui_mainwindow.textEdit_11.setDisabled(True)
cls.__ui_mainwindow.textEdit_20.setDisabled(True)
cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))
cls.__ui_mainwindow.lineEdit_8.setText(question_tag)
cls.__ui_mainwindow.lineEdit_28.setText(str(points))
@classmethod
def display_question_id_invalid_to_load_message(cls):
cls.__ui_mainwindow.label_12.setText('Invalid Question ID To Load')
@classmethod
def display_modification_success_message(cls):
cls.__ui_mainwindow.label_57.setText('Modification Success')
@classmethod
def display_invalid_school_class_id_message(cls):
cls.__ui_mainwindow.label_14.setText('Invalid School Class ID')
cls.__ui_mainwindow.tableWidget_15.clear()
@classmethod
def get_question_type_to_modify(cls):
question_type_text = cls.__ui_mainwindow.label_47.text()
if question_type_text == 'Question Type: Single Answer':
return 'Single Answer'
elif question_type_text == 'Question Type: Multiple Answers':
return 'Multiple Answers'
elif question_type_text == 'Question Type: Essay':
return 'Essay'
@classmethod
def get_single_answer_question_details_to_modify(cls):
question_pk = cls.get_question_id_to_modify()
question_type = cls.get_question_type_to_modify()
points = int(cls.__ui_mainwindow.lineEdit_28.text())
year_level = int(cls.__ui_mainwindow.lineEdit_6.text())
question_tag = cls.__ui_mainwindow.lineEdit_8.text()
question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()
option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()
option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()
option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()
option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()
option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()
correct_answer = cls.get_single_correct_answer_to_modify()
if correct_answer == None:
return None
return (question_pk, question_type, points, year_level,
question_tag, question_body, option_A_text, option_B_text,
option_C_text, option_D_text, option_E_text, correct_answer)
@classmethod
def get_multiple_answers_question_details_to_modify(cls):
question_pk = cls.get_question_id_to_modify()
question_type = cls.get_question_type_to_modify()
points = int(cls.__ui_mainwindow.lineEdit_28.text())
year_level = int(cls.__ui_mainwindow.lineEdit_6.text())
question_tag = cls.__ui_mainwindow.lineEdit_8.text()
question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()
option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()
option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()
option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()
option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()
option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()
correct_answers = cls.get_multiple_correct_answers_to_modify()
if correct_answers == None:
return None
return (question_pk, question_type, points, year_level,
question_tag, question_body, option_A_text, option_B_text,
option_C_text, option_D_text, option_E_text, correct_answers)
@classmethod
def get_essay_question_details_to_modify(cls):
question_pk = cls.get_question_id_to_modify()
question_type = cls.get_question_type_to_modify()
try:
points = int(cls.__ui_mainwindow.lineEdit_28.text())
except:
return None
try:
year_level = int(cls.__ui_mainwindow.lineEdit_6.text())
except:
return None
question_tag = cls.__ui_mainwindow.lineEdit_8.text()
if question_tag == '':
return None
question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()
if question_body == '':
return None
return (question_pk, question_type, points, year_level,
question_tag, question_body)
@classmethod
def get_question_id_to_modify(cls):
question_id_text = cls.__ui_mainwindow.label_45.text()
question_id_text_split = question_id_text.split()
question_id = int(question_id_text_split.pop())
return question_id
@classmethod
def get_single_correct_answer_to_modify(cls):
correct_answer = ''
if cls.__ui_mainwindow.radioButton_6.isChecked():
correct_answer = correct_answer + 'A'
if cls.__ui_mainwindow.radioButton_7.isChecked():
correct_answer = correct_answer + 'B'
if cls.__ui_mainwindow.radioButton_8.isChecked():
correct_answer = correct_answer + 'C'
if cls.__ui_mainwindow.radioButton_9.isChecked():
correct_answer = correct_answer + 'D'
if cls.__ui_mainwindow.radioButton_10.isChecked():
correct_answer = correct_answer + 'E'
if len(correct_answer) == 0:
return None
if len(correct_answer) > 1:
return None
return correct_answer
@classmethod
def get_multiple_correct_answers_to_modify(cls):
correct_answers = ''
if cls.__ui_mainwindow.radioButton_6.isChecked():
correct_answers = correct_answers + 'A'
if cls.__ui_mainwindow.radioButton_7.isChecked():
correct_answers = correct_answers + 'B'
if cls.__ui_mainwindow.radioButton_8.isChecked():
correct_answers = correct_answers + 'C'
if cls.__ui_mainwindow.radioButton_9.isChecked():
correct_answers = correct_answers + 'D'
if cls.__ui_mainwindow.radioButton_10.isChecked():
correct_answers = correct_answers + 'E'
if len(correct_answers) == 0:
return None
if len(correct_answers) > 4:
return None
return correct_answers
@classmethod
def get_school_class_id_to_view_students(cls):
school_class_id_text = cls.__ui_mainwindow.lineEdit_9.text()
try:
school_class_id = int(school_class_id_text)
return school_class_id
except:
return None
@classmethod
def display_school_class_details(cls, school_class_details):
cls.__ui_mainwindow.tableWidget_15.clear()
row = 0
col = 0
for student, in school_class_details:
student_item = QTableWidgetItem(student)
cls.__ui_mainwindow.tableWidget_15.setItem(row, col, student_item)
if col >= 1:
col = 0
row += 1
else:
col += 1
@classmethod
def refresh_view_school_class_details_page(cls):
cls.__ui_mainwindow.label_14.clear()
@classmethod
def get_number_of_questions_in_current_exam(cls):
number_of_questions = 0
row = 0
col = 0
for counter in range(10):
if cls.__ui_mainwindow.tableWidget_3.item(row, col) != None:
number_of_questions += 1
row += 1
return number_of_questions
@classmethod
def get_number_of_school_classes_in_current_exam(cls):
number_of_school_classes = 0
row = 0
col = 0
for counter in range(5):
if cls.__ui_mainwindow.tableWidget_4.item(row, col) != None:
number_of_school_classes += 1
row += 1
return number_of_school_classes
@classmethod
def display_number_of_questions_full_in_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText(
'Questions Are Full In Current Exam')
@classmethod
def display_number_of_school_classes_full_in_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText(
'School Classes Are Full In Current Exam')
@classmethod
def display_no_question_in_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText('No Question In Current Exam')
@classmethod
def display_no_school_class_in_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText('No School Class In Current Exam')
<|reserved_special_token_0|>
@classmethod
def display_school_class_id_already_added_to_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText(
'School Class ID Already Added To Current Exam')
@classmethod
def display_question_id_invalid_message(cls):
cls.__ui_mainwindow.label_17.setText('Question ID Invalid')
@classmethod
def display_school_class_id_invalid_message(cls):
cls.__ui_mainwindow.label_17.setText('School CLass ID Invalid')
@classmethod
def display_question_id_not_already_in_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText(
'Question ID Not Aleady In Current Exam')
@classmethod
def display_school_class_id_not_already_in_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText(
'School Class ID Not Aleady In Current Exam')
@classmethod
def display_create_exam_success_message(cls):
cls.__ui_mainwindow.label_17.setText('Create Exam Success')
@classmethod
def refresh_mark_exam_drop_box(cls):
cls.__ui_mainwindow.tableWidget_19.clear()
@classmethod
def get_question_id_to_add_to_exam(cls):
question_id_text = cls.__ui_mainwindow.lineEdit_10.text()
try:
question_id = int(question_id_text)
return question_id
except:
return None
@classmethod
def get_school_class_id_to_add_to_exam(cls):
school_class_id_text = cls.__ui_mainwindow.lineEdit_11.text()
try:
school_class_id = int(school_class_id_text)
return school_class_id
except:
return None
@classmethod
def get_question_id_to_remove_from_exam(cls):
question_id_text = cls.__ui_mainwindow.lineEdit_12.text()
try:
question_id = int(question_id_text)
return question_id
except:
return None
@classmethod
def get_school_class_id_to_remove_from_exam(cls):
school_class_id_text = cls.__ui_mainwindow.lineEdit_13.text()
try:
school_class_id = int(school_class_id_text)
return school_class_id
except:
return None
@classmethod
def add_question_id_to_current_exam(cls, question_id):
row = 0
col = 0
for counter in range(10):
if cls.__ui_mainwindow.tableWidget_3.item(row, col) == None:
question_text = 'Question ' + str(question_id)
question_item = QTableWidgetItem(question_text)
cls.__ui_mainwindow.tableWidget_3.setItem(row, col,
question_item)
cls.__ui_mainwindow.lineEdit_10.clear()
cls.__ui_mainwindow.label_17.clear()
return
row += 1
@classmethod
def add_school_class_id_to_current_exam(cls, school_class_id):
row = 0
col = 0
for counter in range(10):
if cls.__ui_mainwindow.tableWidget_4.item(row, col) == None:
school_class_text = 'CLass ' + str(school_class_id)
school_class_item = QTableWidgetItem(school_class_text)
cls.__ui_mainwindow.tableWidget_4.setItem(row, col,
school_class_item)
cls.__ui_mainwindow.lineEdit_11.clear()
cls.__ui_mainwindow.label_17.clear()
return
row += 1
@classmethod
def remove_question_id_from_current_exam(cls, question_id):
col = 0
for row in range(10):
question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)
if question_item != None:
question_text = question_item.text()
question_text_split = question_text.split(' ')
question_id_in_exam = int(question_text_split.pop())
if question_id_in_exam == question_id:
cls.__ui_mainwindow.tableWidget_3.takeItem(row, col)
cls.__ui_mainwindow.lineEdit_12.clear()
cls.__ui_mainwindow.label_17.clear()
return
@classmethod
def remove_school_class_id_from_current_exam(cls, school_class_id):
col = 0
for row in range(5):
school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col
)
if school_class_item != None:
school_class_text = school_class_item.text()
school_class_text_split = school_class_text.split(' ')
school_class_id_in_exam = int(school_class_text_split.pop())
if school_class_id_in_exam == school_class_id:
cls.__ui_mainwindow.tableWidget_4.takeItem(row, col)
cls.__ui_mainwindow.lineEdit_13.clear()
cls.__ui_mainwindow.label_17.clear()
return
<|reserved_special_token_0|>
@classmethod
def is_school_class_id_already_added_to_current_exam(cls, school_class_id):
string_of_school_classes_ids_in_current_exam = (cls.
get_string_of_school_classes_ids_in_current_exam())
list_of_school_classes_ids = (
string_of_school_classes_ids_in_current_exam.split(' '))
return list_of_school_classes_ids.count(str(school_class_id)) == 1
@classmethod
def get_string_of_question_ids_in_current_exam(cls):
string_of_question_ids = ''
col = 0
for row in range(10):
question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)
if question_item != None:
question_text = question_item.text()
question_text_split = question_text.split(' ')
question_id = question_text_split.pop()
string_of_question_ids = (string_of_question_ids +
question_id + ' ')
return string_of_question_ids.rstrip()
@classmethod
def get_string_of_school_classes_ids_in_current_exam(cls):
string_of_school_classes_ids = ''
col = 0
for row in range(10):
school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col
)
if school_class_item != None:
school_class_text = school_class_item.text()
school_class_text_split = school_class_text.split(' ')
school_class_id = school_class_text_split.pop()
string_of_school_classes_ids = (
string_of_school_classes_ids + school_class_id + ' ')
return string_of_school_classes_ids.rstrip()
@classmethod
def get_exam_id_to_mark(cls):
exam_item = cls.__ui_mainwindow.tableWidget_20.item(0, 0)
exam_text = exam_item.text()
exam_text_split = exam_text.split(' ')
exam_id_text = exam_text_split.pop()
return int(exam_id_text)
@classmethod
def display_exam_id_on_marking_exam_page(cls, exam_id):
cls.__ui_mainwindow.label_49.setText('Exam ID: ' + str(exam_id))
@classmethod
def display_students_full_names_with_questions_ready_to_be_marked(cls,
students_names_list):
cls.__ui_mainwindow.tableWidget_6.clear()
row = 0
col = 0
for student_name in students_names_list:
student_item = QTableWidgetItem(student_name)
cls.__ui_mainwindow.tableWidget_6.setItem(row, col, student_item)
if col >= 4:
row += 1
col = 0
else:
col += 1
@classmethod
def get_student_name_to_mark_answers(cls):
student_item = cls.__ui_mainwindow.tableWidget_19.item(0, 0)
student_name = student_item.text()
return student_name
@classmethod
def get_exam_id_to_mark_student_answers(cls):
exam_id_text = cls.__ui_mainwindow.label_49.text()
exam_id_text_split = exam_id_text.split(' ')
exam_id = exam_id_text_split.pop()
return int(exam_id)
<|reserved_special_token_0|>
@classmethod
def display_student_id_on_mark_student_answers_page(cls, student_id):
student_id_text = 'Student ID: ' + str(student_id)
cls.__ui_mainwindow.label_63.setText(student_id_text)
@classmethod
def display_student_name_on_mark_student_answers_page(cls, student_name):
student_name_text = 'Student Name: ' + str(student_name)
cls.__ui_mainwindow.label_50.setText(student_name_text)
@classmethod
def display_questions_ready_to_be_marked(cls, questions_ids_tuple):
cls.__ui_mainwindow.tableWidget_25.clear()
row = 0
col = 0
for question_id, in questions_ids_tuple:
question_text = 'Question ' + str(question_id)
question_item = QTableWidgetItem(question_text)
cls.__ui_mainwindow.tableWidget_25.setItem(row, col, question_item)
row += 1
@classmethod
def get_question_id_to_mark(cls):
question_item = cls.__ui_mainwindow.tableWidget_26.item(0, 0)
if question_item == None:
return None
question_id_text = question_item.text()
question_id_text_list = question_id_text.split(' ')
question_id = question_id_text_list.pop()
return int(question_id)
@classmethod
def get_exam_id_on_marking_question_page(cls):
exam_id_text = cls.__ui_mainwindow.label_62.text()
exam_id_text_list = exam_id_text.split(' ')
exam_id = exam_id_text_list.pop()
return int(exam_id)
@classmethod
def get_student_id_on_marking_question_page(cls):
student_id_text = cls.__ui_mainwindow.label_63.text()
student_id_text_list = student_id_text.split(' ')
student_id = student_id_text_list.pop()
return int(student_id)
@classmethod
def setup_essay_question_ui_dialog_to_mark(cls, question_details):
question_body = question_details[0]
student_answer = question_details[1]
available_points = question_details[2]
cls.__dialog = QtWidgets.QDialog()
cls.__ui_dialog = Ui_MarkingEssayQuestionDialog()
cls.__ui_dialog.setupUi(cls.__dialog)
cls.__ui_dialog.label_2.setText(question_body)
cls.__ui_dialog.label_3.setText(student_answer)
cls.__ui_dialog.label_4.setText('Total Available Points: ' + str(
available_points))
cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)
cls.__dialog.show()
return cls.__ui_dialog
@classmethod
def get_essay_question_marked_points(cls):
points_text = cls.__ui_dialog.lineEdit.text()
return int(points_text)
@classmethod
def refresh_drop_question_to_mark_box(cls):
cls.__ui_mainwindow.tableWidget_26.clear()
@classmethod
def refresh_mark_student_questions_answers_page(cls):
cls.__ui_mainwindow.label_62.clear()
cls.__ui_mainwindow.label_63.clear()
cls.__ui_mainwindow.label_50.clear()
@classmethod
def display_no_more_questions_to_mark_message(cls):
cls.__ui_mainwindow.label_66.setText('No More Questions To Mark')
@classmethod
def display_marked_exams(cls, marked_exams_ids):
cls.__ui_mainwindow.tableWidget_18.clear()
row = 0
col = 0
for exam_id, in marked_exams_ids:
exam_text = 'Exam ' + str(exam_id)
exam_item = QTableWidgetItem(exam_text)
cls.__ui_mainwindow.tableWidget_18.setItem(row, col, exam_item)
if col >= 4:
row += 1
col = 0
else:
col += 1
@classmethod
def display_no_question_selected_to_mark_message(cls):
cls.__ui_mainwindow.label_66.setText('No Question Selected To Mark')
@classmethod
def refresh_drop_student_to_mark_questions_box(cls):
cls.__ui_mainwindow.tableWidget_19.clear()
@classmethod
def get_exam_id_to_release_result(cls):
exam_item = cls.__ui_mainwindow.tableWidget_21.item(0, 0)
if exam_item == None:
return None
exam_id_text = exam_item.text()
exam_id_text_list = exam_id_text.split(' ')
exam_id = exam_id_text_list.pop()
return int(exam_id)
@classmethod
def display_result_released_exams(cls, result_released_exams_ids):
cls.__ui_mainwindow.tableWidget_11.clear()
row = 0
col = 0
for exam_id, in result_released_exams_ids:
exam_text = 'Exam ' + str(exam_id) + ' Result'
exam_item = QTableWidgetItem(exam_text)
cls.__ui_mainwindow.tableWidget_11.setItem(row, col, exam_item)
if col >= 9:
row += 1
col = 0
else:
col += 1
@classmethod
def refresh_drop_exam_to_release_result_box(cls):
cls.__ui_mainwindow.tableWidget_21.clear()
@classmethod
def display_exam_results(cls, exam_results_ids):
cls.__ui_mainwindow.tableWidget_11.clear()
row = 0
col = 0
for exam_result_id, in exam_results_ids:
exam_result_text = 'Exam ' + str(exam_result_id) + ' Result'
exam_result_item = QTableWidgetItem(exam_result_text)
cls.__ui_mainwindow.tableWidget_11.setItem(row, col,
exam_result_item)
if col >= 9:
row += 1
col = 0
else:
col += 1
@classmethod
def get_exam_result_id_to_load_details(cls):
exam_result_id_text = cls.__ui_mainwindow.lineEdit_22.text()
return int(exam_result_id_text)
<|reserved_special_token_0|>
@classmethod
def display_exam_result_id_on_view_exam_result_details_page(cls,
exam_result_id):
cls.__ui_mainwindow.label_33.setText('Exam Result ID: ' + str(
exam_result_id))
@classmethod
def get_school_class_id_to_view_exam_result(cls):
school_class_id_text = cls.__ui_mainwindow.lineEdit_23.text()
try:
school_class_id = int(school_class_id_text)
except:
return None
return school_class_id
@classmethod
def display_students_full_names_to_view_exam_result(cls,
students_full_names):
cls.__ui_mainwindow.tableWidget_13.clear()
row = 0
col = 0
for student_full_name, in students_full_names:
student_item = QTableWidgetItem(student_full_name)
cls.__ui_mainwindow.tableWidget_13.setItem(row, col, student_item)
row += 1
@classmethod
def get_student_full_name_to_view_exam_result(cls):
student_item = cls.__ui_mainwindow.tableWidget_22.item(0, 0)
student_name_text = student_item.text()
return student_name_text
@classmethod
def get_exam_result_id_on_view_exam_result_page(cls):
exam_result_id_text = cls.__ui_mainwindow.label_33.text()
exam_result_id_text_list = exam_result_id_text.split(' ')
exam_result_id = exam_result_id_text_list.pop()
try:
exam_result_id_int = int(exam_result_id)
return exam_result_id_int
except:
return None
@classmethod
def display_student_exam_result_details(cls, exam_result_details):
student_id = exam_result_details[0]
student_full_name = exam_result_details[1]
date_of_birth = exam_result_details[2]
school_class_id = exam_result_details[3]
exam_id = exam_result_details[4]
total_available_points = exam_result_details[5]
total_points_gained = exam_result_details[6]
average_percentage_mark = exam_result_details[7]
cls.__ui_mainwindow.label_58.setText(str(student_id))
cls.__ui_mainwindow.label_72.setText(str(student_full_name))
cls.__ui_mainwindow.label_75.setText(str(date_of_birth))
cls.__ui_mainwindow.label_76.setText(str(school_class_id))
cls.__ui_mainwindow.label_77.setText(str(exam_id))
cls.__ui_mainwindow.label_78.setText(str(total_available_points))
cls.__ui_mainwindow.label_79.setText(str(total_points_gained))
cls.__ui_mainwindow.label_80.setText(str(average_percentage_mark) +
' %')
@classmethod
def get_exam_id_to_view_details(cls):
exam_id_text = cls.__ui_mainwindow.lineEdit_14.text()
if exam_id_text == '':
return None
try:
exam_id = int(exam_id_text)
return exam_id
except:
return None
<|reserved_special_token_0|>
@classmethod
def display_questions_on_view_exam_details_page(cls, questions_ids):
cls.__ui_mainwindow.tableWidget_7.clear()
questions_ids_list = cls.make_string_to_list(questions_ids)
row = 0
col = 0
for question_id in questions_ids_list:
question_text = 'Question ' + str(question_id)
question_item = QTableWidgetItem(question_text)
cls.__ui_mainwindow.tableWidget_7.setItem(row, col, question_item)
row += 1
@classmethod
def display_first_school_class_details_on_view_exam_details_page(cls,
school_class_id, students_full_names):
cls.display_first_school_class_id_on_view_exam_details_page(
school_class_id)
cls.__ui_mainwindow.tableWidget_27.clear()
row = 0
col = 0
for student_name, in students_full_names:
student_item = QTableWidgetItem(student_name)
cls.__ui_mainwindow.tableWidget_27.setItem(row, col, student_item)
row += 1
@classmethod
def display_first_school_class_id_on_view_exam_details_page(cls,
school_class_id):
cls.__ui_mainwindow.label_67.setText('CLass ' + str(school_class_id))
@classmethod
def display_second_school_class_details_on_view_exam_details_page(cls,
school_class_id, students_full_names):
cls.display_second_school_class_id_on_view_exam_details_page(
school_class_id)
cls.__ui_mainwindow.tableWidget_28.clear()
row = 0
col = 0
for student_name, in students_full_names:
student_item = QTableWidgetItem(student_name)
cls.__ui_mainwindow.tableWidget_28.setItem(row, col, student_item)
row += 1
@classmethod
def display_second_school_class_id_on_view_exam_details_page(cls,
school_class_id):
cls.__ui_mainwindow.label_68.setText('CLass ' + str(school_class_id))
@classmethod
def display_third_school_class_details_on_view_exam_details_page(cls,
school_class_id, students_full_names):
cls.display_third_school_class_id_on_view_exam_details_page(
school_class_id)
cls.__ui_mainwindow.tableWidget_29.clear()
row = 0
col = 0
for student_name, in students_full_names:
student_item = QTableWidgetItem(student_name)
cls.__ui_mainwindow.tableWidget_29.setItem(row, col, student_item)
row += 1
@classmethod
def display_third_school_class_id_on_view_exam_details_page(cls,
school_class_id):
cls.__ui_mainwindow.label_69.setText('CLass ' + str(school_class_id))
@classmethod
def display_fourth_school_class_details_on_view_exam_details_page(cls,
school_class_id, students_full_names):
cls.display_fourth_school_class_id_on_view_exam_details_page(
school_class_id)
cls.__ui_mainwindow.tableWidget_30.clear()
row = 0
col = 0
for student_name, in students_full_names:
student_item = QTableWidgetItem(student_name)
cls.__ui_mainwindow.tableWidget_30.setItem(row, col, student_item)
row += 1
@classmethod
def display_fourth_school_class_id_on_view_exam_details_page(cls,
school_class_id):
cls.__ui_mainwindow.label_70.setText('CLass ' + str(school_class_id))
@classmethod
def display_fifth_school_class_details_on_view_exam_details_page(cls,
school_class_id, students_full_names):
cls.display_fifth_school_class_id_on_view_exam_details_page(
school_class_id)
cls.__ui_mainwindow.tableWidget_31.clear()
row = 0
col = 0
for student_name, in students_full_names:
student_item = QTableWidgetItem(student_name)
cls.__ui_mainwindow.tableWidget_31.setItem(row, col, student_item)
row += 1
@classmethod
def display_fifth_school_class_id_on_view_exam_details_page(cls,
school_class_id):
cls.__ui_mainwindow.label_71.setText('CLass ' + str(school_class_id))
@classmethod
def make_string_to_list(cls, any_string):
any_string = str(any_string)
any_list = any_string.split(' ')
return any_list
@classmethod
def refresh_drop_student_to_view_exam_result_details_box(cls):
cls.__ui_mainwindow.tableWidget_22.clear()
@classmethod
def display_exam_result_id_invalid_message(cls):
cls.__ui_mainwindow.label_32.setText('Exam Result ID Invalid')
@classmethod
def refresh_load_exam_result_details_page(cls):
cls.__ui_mainwindow.label_33.clear()
cls.__ui_mainwindow.tableWidget_12.clear()
cls.__ui_mainwindow.lineEdit_23.clear()
cls.__ui_mainwindow.tableWidget_13.clear()
cls.__ui_mainwindow.tableWidget_22.clear()
cls.__ui_mainwindow.label_58.clear()
cls.__ui_mainwindow.label_72.clear()
cls.__ui_mainwindow.label_75.clear()
cls.__ui_mainwindow.label_76.clear()
cls.__ui_mainwindow.label_77.clear()
cls.__ui_mainwindow.label_78.clear()
cls.__ui_mainwindow.label_79.clear()
cls.__ui_mainwindow.label_80.clear()
@classmethod
def refresh_exam_result_id_validity_error_message(cls):
cls.__ui_mainwindow.label_32.clear()
@classmethod
def display_school_class_id_invalid_to_view_result_message(cls):
cls.__ui_mainwindow.label_81.setText('School Class ID Invalid To View')
@classmethod
def refresh_school_class_details_table_on_view_exam_result_page(cls):
cls.__ui_mainwindow.tableWidget_13.clear()
@classmethod
def refresh_school_class_id_invalid_to_view_exam_result_error_label(cls):
cls.__ui_mainwindow.label_81.clear()
@classmethod
def refresh_student_exam_result_details(cls):
cls.__ui_mainwindow.label_58.clear()
cls.__ui_mainwindow.label_72.clear()
cls.__ui_mainwindow.label_75.clear()
cls.__ui_mainwindow.label_76.clear()
cls.__ui_mainwindow.label_77.clear()
cls.__ui_mainwindow.label_78.clear()
cls.__ui_mainwindow.label_79.clear()
cls.__ui_mainwindow.label_80.clear()
@classmethod
def display_no_exam_result_id_selected_message(cls):
cls.__ui_mainwindow.label_81.setText('No Exam Result ID Selected')
@classmethod
def refresh_school_class_id_input_box_on_view_exam_result_details_page(cls
):
cls.__ui_mainwindow.lineEdit_23.clear()
@classmethod
def refresh_view_exam_details_by_id_page(cls):
cls.__ui_mainwindow.label_18.setText('Exam ID : ')
cls.__ui_mainwindow.tableWidget_7.clear()
cls.__ui_mainwindow.label_67.clear()
cls.__ui_mainwindow.label_68.clear()
cls.__ui_mainwindow.label_69.clear()
cls.__ui_mainwindow.label_70.clear()
cls.__ui_mainwindow.label_71.clear()
cls.__ui_mainwindow.tableWidget_27.clear()
cls.__ui_mainwindow.tableWidget_28.clear()
cls.__ui_mainwindow.tableWidget_29.clear()
cls.__ui_mainwindow.tableWidget_30.clear()
cls.__ui_mainwindow.tableWidget_31.clear()
@classmethod
def refresh_students_table_on_view_exam_result_details_page(cls):
cls.__ui_mainwindow.tableWidget_13.clear()
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QLineEdit, QRadioButton, QPushButton, QTableWidgetItem, QTableWidget, QApplication, QMainWindow, QDateEdit, QLabel, QDialog, QTextEdit, QCheckBox
from PyQt5.QtCore import QDate, QTime, QDateTime, Qt
from OOPCourseWorkTwo.GUI.SingleAnswerQuestionDialog import Ui_SingleAnswerQuestionDialog
from OOPCourseWorkTwo.GUI.MultipleAnswersQuestionDialog import Ui_MultipleAnswersQuestionDialog
from OOPCourseWorkTwo.GUI.EssayQuestionDialog import Ui_EssayQuestionDialog
from OOPCourseWorkTwo.GUI.MarkingEssayQuestionDialog import Ui_MarkingEssayQuestionDialog
class TeacherGUI():
def __init__(self):
pass
@classmethod
def setup(cls, ui_mainwindow):
cls.__ui_mainwindow = ui_mainwindow
@classmethod
def display_all_active_school_classes(cls, school_classes):
cls.__ui_mainwindow.tableWidget_14.clear()
row = 0
col = 0
for (school_class_id, ) in school_classes:
school_class_text = "Class " + str(school_class_id)
school_class_item = QTableWidgetItem(school_class_text)
cls.__ui_mainwindow.tableWidget_14.setItem(row, col, school_class_item)
if (col >= 4):
col = 0
row += 1
else:
col += 1
@classmethod
def display_all_exams(cls, all_exams):
cls.__ui_mainwindow.tableWidget_5.clear()
row = 0
col = 0
for (exam_id, ) in all_exams:
exam_text = "Exam " + str(exam_id)
exam_item = QTableWidgetItem(exam_text)
cls.__ui_mainwindow.tableWidget_5.setItem(row, col, exam_item)
if (col >= 9):
col = 0
row += 1
else:
col += 1
@classmethod
def display_not_completed_exams(cls, not_completed_exams):
cls.__ui_mainwindow.tableWidget_16.clear()
row = 0
col = 0
for (exam_id, ) in not_completed_exams:
exam_text = "Exam " + str(exam_id)
exam_item = QTableWidgetItem(exam_text)
cls.__ui_mainwindow.tableWidget_16.setItem(row, col, exam_item)
if (col >= 6):
col = 0
row += 1
else:
col += 1
@classmethod
def display_ready_to_be_marked_exams(cls, ready_to_be_marked_exams):
cls.__ui_mainwindow.tableWidget_17.clear()
row = 0
col = 0
for (exam_id, ) in ready_to_be_marked_exams:
exam_text = "Exam " + str(exam_id)
exam_item = QTableWidgetItem(exam_text)
cls.__ui_mainwindow.tableWidget_17.setItem(row, col, exam_item)
if (col >= 3):
col = 0
row += 1
else:
col += 1
@classmethod
def display_single_answer_question_dialog_preview(cls):
question_body = cls.__ui_mainwindow.textEdit.toPlainText()
option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()
option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()
option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()
option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()
option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()
cls.__dialog = QtWidgets.QDialog()
cls.__ui_dialog = Ui_SingleAnswerQuestionDialog()
cls.__ui_dialog.setupUi(cls.__dialog)
cls.__ui_dialog.label.setText(question_body)
cls.__ui_dialog.label_3.setText("A " + option_A_text)
cls.__ui_dialog.label_4.setText("B " + option_B_text)
cls.__ui_dialog.label_5.setText("C " + option_C_text)
cls.__ui_dialog.label_6.setText("D " + option_D_text)
cls.__ui_dialog.label_7.setText("E " + option_E_text)
cls.__dialog.show()
cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)
@classmethod
def display_multiple_answers_question_dialog_preview(cls):
question_body = cls.__ui_mainwindow.textEdit_14.toPlainText()
option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText()
option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText()
option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText()
option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText()
option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText()
cls.__dialog = QtWidgets.QDialog()
cls.__ui_dialog = Ui_MultipleAnswersQuestionDialog()
cls.__ui_dialog.setupUi(cls.__dialog)
cls.__ui_dialog.label.setText(question_body)
cls.__ui_dialog.label_3.setText(option_A_text)
cls.__ui_dialog.label_4.setText(option_B_text)
cls.__ui_dialog.label_5.setText(option_C_text)
cls.__ui_dialog.label_6.setText(option_D_text)
cls.__ui_dialog.label_7.setText(option_E_text)
cls.__dialog.show()
cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)
@classmethod
def display_essay_question_dialog_preview(cls):
question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()
cls.__dialog = QtWidgets.QDialog()
cls.__ui_dialog = Ui_EssayQuestionDialog()
cls.__ui_dialog.setupUi(cls.__dialog)
if (question_body == ""):
cls.__ui_dialog.label.setText("Question Body")
else:
cls.__ui_dialog.label.setText(question_body)
cls.__dialog.show()
cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)
@classmethod
def close_dialog(cls):
cls.__dialog.close()
@classmethod
def get_single_answer_question_details(cls):
question_body = cls.__ui_mainwindow.textEdit.toPlainText()
if (question_body == ""):
return None
option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()
if (option_A_text == ""):
return None
option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()
if (option_B_text == ""):
return None
option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()
if (option_C_text == ""):
return None
option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()
if (option_D_text == ""):
return None
option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()
if (option_E_text == ""):
return None
year_level_text = cls.__ui_mainwindow.lineEdit_3.text()
if (year_level_text == ""):
return None
try:
year_level = int(year_level_text)
except:
return None
phrase_tag_text = cls.__ui_mainwindow.lineEdit_4.text()
if (phrase_tag_text == ""):
return None
correct_answers_list = []
if (cls.__ui_mainwindow.radioButton.isChecked()):
correct_answers_list.append("A")
if (cls.__ui_mainwindow.radioButton_2.isChecked()):
correct_answers_list.append("B")
if (cls.__ui_mainwindow.radioButton_5.isChecked()):
correct_answers_list.append("C")
if (cls.__ui_mainwindow.radioButton_3.isChecked()):
correct_answers_list.append("D")
if (cls.__ui_mainwindow.radioButton_4.isChecked()):
correct_answers_list.append("E")
if (correct_answers_list == []):
return None
if (len(correct_answers_list) > 1):
return None
return (question_body, option_A_text, option_B_text, option_C_text, option_D_text, option_E_text, year_level, phrase_tag_text, correct_answers_list)
@classmethod
def get_multiple_answers_question_details(cls):
question_body = cls.__ui_mainwindow.textEdit_14.toPlainText()
if (question_body == ""):
return None
option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText()
if (option_A_text == ""):
return None
option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText()
if (option_B_text == ""):
return None
option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText()
if (option_C_text == ""):
return None
option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText()
if (option_D_text == ""):
return None
option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText()
if (option_E_text == ""):
return None
year_level_text = cls.__ui_mainwindow.lineEdit_25.text()
if (year_level_text == ""):
return None
try:
year_level = int(year_level_text)
except:
return None
phrase_tag_text = cls.__ui_mainwindow.lineEdit_7.text()
if (phrase_tag_text == ""):
return None
correct_answers_list = []
if (cls.__ui_mainwindow.checkBox.isChecked()):
correct_answers_list.append("A")
if (cls.__ui_mainwindow.checkBox_2.isChecked()):
correct_answers_list.append("B")
if (cls.__ui_mainwindow.checkBox_3.isChecked()):
correct_answers_list.append("C")
if (cls.__ui_mainwindow.checkBox_4.isChecked()):
correct_answers_list.append("D")
if (cls.__ui_mainwindow.checkBox_5.isChecked()):
correct_answers_list.append("E")
if (correct_answers_list == []):
return None
if (len(correct_answers_list) > 4):
return None
return (question_body, option_A_text, option_B_text, option_C_text, option_D_text, option_E_text, year_level, phrase_tag_text, correct_answers_list)
@classmethod
def get_essay_question_details(cls):
question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()
if (question_body == ""):
return None
year_level_text = cls.__ui_mainwindow.lineEdit_26.text()
if (year_level_text == ""):
return None
try:
year_level = int(year_level_text)
except:
return None
phrase_tag_text = cls.__ui_mainwindow.lineEdit_27.text()
if (phrase_tag_text == ""):
return None
return (question_body, year_level, phrase_tag_text)
@classmethod
def display_all_active_questions(cls, active_questions_tuple):
row = 0
col = 0
for question_pk_tuple in active_questions_tuple:
question_pk = question_pk_tuple[0]
question_text = "Question " + str(question_pk)
question_item = QTableWidgetItem(question_text)
cls.__ui_mainwindow.tableWidget.setItem(row, col, question_item)
if (col >= 7):
col = 0
row += 1
else:
col += 1
@classmethod
def display_create_single_answer_question_success(cls):
cls.__ui_mainwindow.label_4.setText("Create Single Answer Question Success")
@classmethod
def display_invalid_single_answer_question_creation_message(cls):
cls.__ui_mainwindow.label_4.setText("Invalid Single Answer Question Creation")
@classmethod
def display_create_multiple_answers_question_success(cls):
cls.__ui_mainwindow.label_11.setText("Create Multiple Answers Question Success")
@classmethod
def display_invalid_multiple_answers_question_creation_message(cls):
cls.__ui_mainwindow.label_11.setText("Invalid Multiple Answers Question Creation")
@classmethod
def display_invalid_essay_question_creation_message(cls):
cls.__ui_mainwindow.label_42.setText("Invalid Essay Question Creation")
@classmethod
def display_create_essay_question_success(cls):
cls.__ui_mainwindow.label_42.setText("Create Essay Question Success")
@classmethod
def display_invalid_modification_message(cls):
cls.__ui_mainwindow.label_57.setText("Invalid Modification")
@classmethod
def refresh_create_single_answer_question_page(cls):
cls.__ui_mainwindow.textEdit.clear()
cls.__ui_mainwindow.textEdit_2.clear()
cls.__ui_mainwindow.textEdit_3.clear()
cls.__ui_mainwindow.textEdit_4.clear()
cls.__ui_mainwindow.textEdit_5.clear()
cls.__ui_mainwindow.textEdit_6.clear()
cls.__ui_mainwindow.lineEdit_3.clear()
cls.__ui_mainwindow.lineEdit_4.clear()
cls.__ui_mainwindow.radioButton.setChecked(False)
cls.__ui_mainwindow.radioButton_2.setChecked(False)
cls.__ui_mainwindow.radioButton_3.setChecked(False)
cls.__ui_mainwindow.radioButton_4.setChecked(False)
cls.__ui_mainwindow.radioButton_5.setChecked(False)
@classmethod
def refresh_create_multiple_answers_question_page(cls):
cls.__ui_mainwindow.textEdit_14.clear()
cls.__ui_mainwindow.textEdit_13.clear()
cls.__ui_mainwindow.textEdit_15.clear()
cls.__ui_mainwindow.textEdit_16.clear()
cls.__ui_mainwindow.textEdit_17.clear()
cls.__ui_mainwindow.textEdit_18.clear()
cls.__ui_mainwindow.lineEdit_25.clear()
cls.__ui_mainwindow.lineEdit_7.clear()
cls.__ui_mainwindow.checkBox.setChecked(False)
cls.__ui_mainwindow.checkBox_2.setChecked(False)
cls.__ui_mainwindow.checkBox_3.setChecked(False)
cls.__ui_mainwindow.checkBox_4.setChecked(False)
cls.__ui_mainwindow.checkBox_5.setChecked(False)
@classmethod
def refresh_view_or_modify_question_page(cls):
cls.__ui_mainwindow.lineEdit_5.clear()
cls.__ui_mainwindow.label_45.setText("Question ID: ")
cls.__ui_mainwindow.label_47.setText("Question Type: ")
cls.__ui_mainwindow.label_57.clear()
cls.__ui_mainwindow.label_12.clear()
cls.__ui_mainwindow.textEdit_7.clear()
cls.__ui_mainwindow.textEdit_8.clear()
cls.__ui_mainwindow.textEdit_9.clear()
cls.__ui_mainwindow.textEdit_10.clear()
cls.__ui_mainwindow.textEdit_11.clear()
cls.__ui_mainwindow.textEdit_20.clear()
cls.__ui_mainwindow.lineEdit_6.clear()
cls.__ui_mainwindow.lineEdit_8.clear()
cls.__ui_mainwindow.lineEdit_28.clear()
cls.__ui_mainwindow.radioButton_6.setDisabled(False)
cls.__ui_mainwindow.radioButton_7.setDisabled(False)
cls.__ui_mainwindow.radioButton_8.setDisabled(False)
cls.__ui_mainwindow.radioButton_9.setDisabled(False)
cls.__ui_mainwindow.radioButton_10.setDisabled(False)
cls.__ui_mainwindow.textEdit_8.setDisabled(False)
cls.__ui_mainwindow.textEdit_9.setDisabled(False)
cls.__ui_mainwindow.textEdit_10.setDisabled(False)
cls.__ui_mainwindow.textEdit_11.setDisabled(False)
cls.__ui_mainwindow.textEdit_20.setDisabled(False)
cls.__ui_mainwindow.radioButton_6.setAutoExclusive(False)
cls.__ui_mainwindow.radioButton_6.setChecked(False)
cls.__ui_mainwindow.radioButton_7.setAutoExclusive(False)
cls.__ui_mainwindow.radioButton_7.setChecked(False)
cls.__ui_mainwindow.radioButton_8.setAutoExclusive(False)
cls.__ui_mainwindow.radioButton_8.setChecked(False)
cls.__ui_mainwindow.radioButton_9.setAutoExclusive(False)
cls.__ui_mainwindow.radioButton_9.setChecked(False)
cls.__ui_mainwindow.radioButton_10.setAutoExclusive(False)
cls.__ui_mainwindow.radioButton_10.setChecked(False)
@classmethod
def refresh_create_essay_question_page(cls):
cls.__ui_mainwindow.textEdit_19.clear()
cls.__ui_mainwindow.lineEdit_26.clear()
cls.__ui_mainwindow.lineEdit_27.clear()
@classmethod
def refresh_create_exam_page(cls):
cls.__ui_mainwindow.tableWidget_3.clear()
cls.__ui_mainwindow.tableWidget_4.clear()
cls.__ui_mainwindow.lineEdit_10.clear()
cls.__ui_mainwindow.lineEdit_11.clear()
cls.__ui_mainwindow.lineEdit_12.clear()
cls.__ui_mainwindow.lineEdit_13.clear()
@classmethod
def get_question_id_to_load(cls):
question_id_text = cls.__ui_mainwindow.lineEdit_5.text()
try:
question_id = int(question_id_text)
return question_id
except:
return None
@classmethod
def load_single_answer_question_details(cls, question_details):
question_id = question_details[0]
question_type = question_details[1]
points = question_details[2]
year_level = question_details[3]
question_tag = question_details[4]
question_body = question_details[5]
option_A_text = question_details[6]
option_B_text = question_details[7]
option_C_text = question_details[8]
option_D_text = question_details[9]
option_E_text = question_details[10]
correct_answer = question_details[11]
cls.__ui_mainwindow.label_45.setText("Question ID: " + str(question_id))
cls.__ui_mainwindow.label_47.setText("Question Type: " + str(question_type))
cls.__ui_mainwindow.textEdit_7.setText(question_body)
cls.__ui_mainwindow.textEdit_8.setText(option_A_text)
cls.__ui_mainwindow.textEdit_9.setText(option_B_text)
cls.__ui_mainwindow.textEdit_10.setText(option_C_text)
cls.__ui_mainwindow.textEdit_11.setText(option_D_text)
cls.__ui_mainwindow.textEdit_20.setText(option_E_text)
cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))
cls.__ui_mainwindow.lineEdit_8.setText(question_tag)
cls.__ui_mainwindow.lineEdit_28.setText(str(points))
if (correct_answer == "A"):
cls.__ui_mainwindow.radioButton_6.setChecked(True)
elif (correct_answer == "B"):
cls.__ui_mainwindow.radioButton_7.setChecked(True)
elif (correct_answer == "C"):
cls.__ui_mainwindow.radioButton_8.setChecked(True)
elif (correct_answer == "D"):
cls.__ui_mainwindow.radioButton_9.setChecked(True)
elif (correct_answer == "E"):
cls.__ui_mainwindow.radioButton_10.setChecked(True)
@classmethod
def load_multiple_answers_question_details(cls, question_details):
question_id = question_details[0]
question_type = question_details[1]
points = question_details[2]
year_level = question_details[3]
question_tag = question_details[4]
question_body = question_details[5]
option_A_text = question_details[6]
option_B_text = question_details[7]
option_C_text = question_details[8]
option_D_text = question_details[9]
option_E_text = question_details[10]
correct_answers = question_details[11]
cls.__ui_mainwindow.label_45.setText("Question ID: " + str(question_id))
cls.__ui_mainwindow.label_47.setText("Question Type: " + str(question_type))
cls.__ui_mainwindow.textEdit_7.setText(question_body)
cls.__ui_mainwindow.textEdit_8.setText(option_A_text)
cls.__ui_mainwindow.textEdit_9.setText(option_B_text)
cls.__ui_mainwindow.textEdit_10.setText(option_C_text)
cls.__ui_mainwindow.textEdit_11.setText(option_D_text)
cls.__ui_mainwindow.textEdit_20.setText(option_E_text)
cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))
cls.__ui_mainwindow.lineEdit_8.setText(question_tag)
cls.__ui_mainwindow.lineEdit_28.setText(str(points))
if (correct_answers.count("A") == 1):
cls.__ui_mainwindow.radioButton_6.setChecked(True)
if (correct_answers.count("B") == 1):
cls.__ui_mainwindow.radioButton_7.setChecked(True)
if (correct_answers.count("C") == 1):
cls.__ui_mainwindow.radioButton_8.setChecked(True)
if (correct_answers.count("D") == 1):
cls.__ui_mainwindow.radioButton_9.setChecked(True)
if (correct_answers.count("E") == 1):
cls.__ui_mainwindow.radioButton_10.setChecked(True)
@classmethod
def load_essay_question_details(cls, question_details):
question_id = question_details[0]
question_type = question_details[1]
points = question_details[2]
year_level = question_details[3]
question_tag = question_details[4]
question_body = question_details[5]
cls.__ui_mainwindow.label_45.setText("Question ID: " + str(question_id))
cls.__ui_mainwindow.label_47.setText("Question Type: " + str(question_type))
cls.__ui_mainwindow.textEdit_7.setText(question_body)
cls.__ui_mainwindow.radioButton_6.setDisabled(True)
cls.__ui_mainwindow.radioButton_7.setDisabled(True)
cls.__ui_mainwindow.radioButton_8.setDisabled(True)
cls.__ui_mainwindow.radioButton_9.setDisabled(True)
cls.__ui_mainwindow.radioButton_10.setDisabled(True)
cls.__ui_mainwindow.textEdit_8.setDisabled(True)
cls.__ui_mainwindow.textEdit_9.setDisabled(True)
cls.__ui_mainwindow.textEdit_10.setDisabled(True)
cls.__ui_mainwindow.textEdit_11.setDisabled(True)
cls.__ui_mainwindow.textEdit_20.setDisabled(True)
cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))
cls.__ui_mainwindow.lineEdit_8.setText(question_tag)
cls.__ui_mainwindow.lineEdit_28.setText(str(points))
@classmethod
def display_question_id_invalid_to_load_message(cls):
cls.__ui_mainwindow.label_12.setText("Invalid Question ID To Load")
@classmethod
def display_modification_success_message(cls):
cls.__ui_mainwindow.label_57.setText("Modification Success")
@classmethod
def display_invalid_school_class_id_message(cls):
cls.__ui_mainwindow.label_14.setText("Invalid School Class ID")
cls.__ui_mainwindow.tableWidget_15.clear()
@classmethod
def get_question_type_to_modify(cls):
question_type_text = cls.__ui_mainwindow.label_47.text()
if (question_type_text == "Question Type: Single Answer"):
return "Single Answer"
elif (question_type_text == "Question Type: Multiple Answers"):
return "Multiple Answers"
elif (question_type_text == "Question Type: Essay"):
return "Essay"
@classmethod
def get_single_answer_question_details_to_modify(cls):
question_pk = cls.get_question_id_to_modify()
question_type = cls.get_question_type_to_modify()
points = int(cls.__ui_mainwindow.lineEdit_28.text())
year_level = int(cls.__ui_mainwindow.lineEdit_6.text())
question_tag = cls.__ui_mainwindow.lineEdit_8.text()
question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()
option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()
option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()
option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()
option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()
option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()
correct_answer = cls.get_single_correct_answer_to_modify()
if (correct_answer == None):
return None
return (question_pk, question_type, points, year_level, question_tag,question_body, option_A_text, option_B_text, option_C_text, option_D_text, option_E_text, correct_answer)
@classmethod
def get_multiple_answers_question_details_to_modify(cls):
question_pk = cls.get_question_id_to_modify()
question_type = cls.get_question_type_to_modify()
points = int(cls.__ui_mainwindow.lineEdit_28.text())
year_level = int(cls.__ui_mainwindow.lineEdit_6.text())
question_tag = cls.__ui_mainwindow.lineEdit_8.text()
question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()
option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()
option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()
option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()
option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()
option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()
correct_answers = cls.get_multiple_correct_answers_to_modify()
if (correct_answers == None):
return None
return (question_pk, question_type, points, year_level, question_tag,question_body, option_A_text, option_B_text, option_C_text, option_D_text, option_E_text, correct_answers)
@classmethod
def get_essay_question_details_to_modify(cls):
question_pk = cls.get_question_id_to_modify()
question_type = cls.get_question_type_to_modify()
try:
points = int(cls.__ui_mainwindow.lineEdit_28.text())
except:
return None
try:
year_level = int(cls.__ui_mainwindow.lineEdit_6.text())
except:
return None
question_tag = cls.__ui_mainwindow.lineEdit_8.text()
if (question_tag == ""):
return None
question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()
if (question_body == ""):
return None
return (question_pk, question_type, points, year_level, question_tag, question_body)
@classmethod
def get_question_id_to_modify(cls):
question_id_text = cls.__ui_mainwindow.label_45.text()
question_id_text_split = question_id_text.split()
question_id = int(question_id_text_split.pop())
return question_id
@classmethod
def get_single_correct_answer_to_modify(cls):
correct_answer = ""
if (cls.__ui_mainwindow.radioButton_6.isChecked()):
correct_answer = correct_answer + "A"
if (cls.__ui_mainwindow.radioButton_7.isChecked()):
correct_answer = correct_answer + "B"
if (cls.__ui_mainwindow.radioButton_8.isChecked()):
correct_answer = correct_answer + "C"
if (cls.__ui_mainwindow.radioButton_9.isChecked()):
correct_answer = correct_answer + "D"
if (cls.__ui_mainwindow.radioButton_10.isChecked()):
correct_answer = correct_answer + "E"
if (len(correct_answer) == 0):
return None
if (len(correct_answer) > 1):
return None
return correct_answer
@classmethod
def get_multiple_correct_answers_to_modify(cls):
correct_answers = ""
if (cls.__ui_mainwindow.radioButton_6.isChecked()):
correct_answers = correct_answers + "A"
if (cls.__ui_mainwindow.radioButton_7.isChecked()):
correct_answers = correct_answers + "B"
if (cls.__ui_mainwindow.radioButton_8.isChecked()):
correct_answers = correct_answers + "C"
if (cls.__ui_mainwindow.radioButton_9.isChecked()):
correct_answers = correct_answers + "D"
if (cls.__ui_mainwindow.radioButton_10.isChecked()):
correct_answers = correct_answers + "E"
if (len(correct_answers) == 0):
return None
if (len(correct_answers) > 4):
return None
return correct_answers
@classmethod
def get_school_class_id_to_view_students(cls):
school_class_id_text = cls.__ui_mainwindow.lineEdit_9.text()
try:
school_class_id = int(school_class_id_text)
return school_class_id
except:
return None
@classmethod
def display_school_class_details(cls, school_class_details):
cls.__ui_mainwindow.tableWidget_15.clear()
row = 0
col = 0
for (student, ) in school_class_details:
student_item = QTableWidgetItem(student)
cls.__ui_mainwindow.tableWidget_15.setItem(row, col, student_item)
if (col >= 1):
col = 0
row += 1
else:
col += 1
@classmethod
def refresh_view_school_class_details_page(cls):
cls.__ui_mainwindow.label_14.clear()
@classmethod
def get_number_of_questions_in_current_exam(cls):
number_of_questions = 0
row = 0
col = 0
for counter in range(10):
if (cls.__ui_mainwindow.tableWidget_3.item(row, col) != None):
number_of_questions += 1
row += 1
return number_of_questions
@classmethod
def get_number_of_school_classes_in_current_exam(cls):
number_of_school_classes = 0
row = 0
col = 0
for counter in range(5):
if (cls.__ui_mainwindow.tableWidget_4.item(row, col) != None):
number_of_school_classes += 1
row += 1
return number_of_school_classes
@classmethod
def display_number_of_questions_full_in_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText("Questions Are Full In Current Exam")
@classmethod
def display_number_of_school_classes_full_in_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText("School Classes Are Full In Current Exam")
@classmethod
def display_no_question_in_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText("No Question In Current Exam")
@classmethod
def display_no_school_class_in_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText("No School Class In Current Exam")
@classmethod
def display_question_id_already_added_to_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText("Question ID Already Added To Current Exam")
@classmethod
def display_school_class_id_already_added_to_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText("School Class ID Already Added To Current Exam")
@classmethod
def display_question_id_invalid_message(cls):
cls.__ui_mainwindow.label_17.setText("Question ID Invalid")
@classmethod
def display_school_class_id_invalid_message(cls):
cls.__ui_mainwindow.label_17.setText("School CLass ID Invalid")
@classmethod
def display_question_id_not_already_in_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText("Question ID Not Aleady In Current Exam")
@classmethod
def display_school_class_id_not_already_in_current_exam_message(cls):
cls.__ui_mainwindow.label_17.setText("School Class ID Not Aleady In Current Exam")
@classmethod
def display_create_exam_success_message(cls):
cls.__ui_mainwindow.label_17.setText("Create Exam Success")
@classmethod
def refresh_mark_exam_drop_box(cls):
cls.__ui_mainwindow.tableWidget_19.clear()
@classmethod
def get_question_id_to_add_to_exam(cls):
question_id_text = cls.__ui_mainwindow.lineEdit_10.text()
try:
question_id = int(question_id_text)
return question_id
except:
return None
@classmethod
def get_school_class_id_to_add_to_exam(cls):
school_class_id_text = cls.__ui_mainwindow.lineEdit_11.text()
try:
school_class_id = int(school_class_id_text)
return school_class_id
except:
return None
@classmethod
def get_question_id_to_remove_from_exam(cls):
question_id_text = cls.__ui_mainwindow.lineEdit_12.text()
try:
question_id = int(question_id_text)
return question_id
except:
return None
@classmethod
def get_school_class_id_to_remove_from_exam(cls):
school_class_id_text = cls.__ui_mainwindow.lineEdit_13.text()
try:
school_class_id = int(school_class_id_text)
return school_class_id
except:
return None
@classmethod
def add_question_id_to_current_exam(cls, question_id):
row = 0
col = 0
for counter in range(10):
if (cls.__ui_mainwindow.tableWidget_3.item(row, col) == None):
question_text = "Question " + str(question_id)
question_item = QTableWidgetItem(question_text)
cls.__ui_mainwindow.tableWidget_3.setItem(row, col, question_item)
cls.__ui_mainwindow.lineEdit_10.clear()
cls.__ui_mainwindow.label_17.clear()
return
row += 1
@classmethod
def add_school_class_id_to_current_exam(cls, school_class_id):
row = 0
col = 0
for counter in range(10):
if (cls.__ui_mainwindow.tableWidget_4.item(row, col) == None):
school_class_text = "CLass " + str(school_class_id)
school_class_item = QTableWidgetItem(school_class_text)
cls.__ui_mainwindow.tableWidget_4.setItem(row, col, school_class_item)
cls.__ui_mainwindow.lineEdit_11.clear()
cls.__ui_mainwindow.label_17.clear()
return
row += 1
@classmethod
def remove_question_id_from_current_exam(cls, question_id):
col = 0
for row in range(10):
question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)
if (question_item != None):
question_text = question_item.text()
question_text_split = question_text.split(" ")
question_id_in_exam = int(question_text_split.pop())
if (question_id_in_exam == question_id):
cls.__ui_mainwindow.tableWidget_3.takeItem(row, col)
cls.__ui_mainwindow.lineEdit_12.clear()
cls.__ui_mainwindow.label_17.clear()
return
@classmethod
def remove_school_class_id_from_current_exam(cls, school_class_id):
col = 0
for row in range(5):
school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col)
if (school_class_item != None):
school_class_text = school_class_item.text()
school_class_text_split = school_class_text.split(" ")
school_class_id_in_exam = int(school_class_text_split.pop())
if (school_class_id_in_exam == school_class_id):
cls.__ui_mainwindow.tableWidget_4.takeItem(row, col)
cls.__ui_mainwindow.lineEdit_13.clear()
cls.__ui_mainwindow.label_17.clear()
return
@classmethod
def is_question_id_already_added_to_current_exam(cls, question_id):
string_of_question_ids_in_current_exam = cls.get_string_of_question_ids_in_current_exam()
list_of_question_ids = string_of_question_ids_in_current_exam.split(" ")
return list_of_question_ids.count(str(question_id)) == 1
@classmethod
def is_school_class_id_already_added_to_current_exam(cls, school_class_id):
string_of_school_classes_ids_in_current_exam = cls.get_string_of_school_classes_ids_in_current_exam()
list_of_school_classes_ids = string_of_school_classes_ids_in_current_exam.split(" ")
return list_of_school_classes_ids.count(str(school_class_id)) == 1
@classmethod
def get_string_of_question_ids_in_current_exam(cls):
string_of_question_ids = ""
col = 0
for row in range(10):
question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)
if (question_item != None):
question_text = question_item.text()
question_text_split = question_text.split(" ")
question_id = question_text_split.pop()
string_of_question_ids = string_of_question_ids + question_id + " "
return string_of_question_ids.rstrip()
@classmethod
def get_string_of_school_classes_ids_in_current_exam(cls):
string_of_school_classes_ids = ""
col = 0
for row in range(10):
school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col)
if (school_class_item != None):
school_class_text = school_class_item.text()
school_class_text_split = school_class_text.split(" ")
school_class_id = school_class_text_split.pop()
string_of_school_classes_ids = string_of_school_classes_ids + school_class_id + " "
return string_of_school_classes_ids.rstrip()
@classmethod
def get_exam_id_to_mark(cls):
exam_item = cls.__ui_mainwindow.tableWidget_20.item(0, 0)
exam_text = exam_item.text()
exam_text_split = exam_text.split(" ")
exam_id_text = exam_text_split.pop()
return int(exam_id_text)
@classmethod
def display_exam_id_on_marking_exam_page(cls, exam_id):
cls.__ui_mainwindow.label_49.setText("Exam ID: " + str(exam_id))
@classmethod
def display_students_full_names_with_questions_ready_to_be_marked(cls, students_names_list):
cls.__ui_mainwindow.tableWidget_6.clear()
row = 0
col = 0
for student_name in students_names_list:
student_item = QTableWidgetItem(student_name)
cls.__ui_mainwindow.tableWidget_6.setItem(row, col, student_item)
if (col >= 4):
row += 1
col = 0
else:
col += 1
@classmethod
def get_student_name_to_mark_answers(cls):
student_item = cls.__ui_mainwindow.tableWidget_19.item(0,0)
student_name = student_item.text()
return student_name
@classmethod
def get_exam_id_to_mark_student_answers(cls):
exam_id_text = cls.__ui_mainwindow.label_49.text()
exam_id_text_split = exam_id_text.split(" ")
exam_id = exam_id_text_split.pop()
return int(exam_id)
@classmethod
def display_exam_id_on_mark_student_answers_page(cls, exam_id):
exam_id_text = "Exam ID: " + str(exam_id)
cls.__ui_mainwindow.label_62.setText(exam_id_text)
@classmethod
def display_student_id_on_mark_student_answers_page(cls, student_id):
student_id_text = "Student ID: " + str(student_id)
cls.__ui_mainwindow.label_63.setText(student_id_text)
@classmethod
def display_student_name_on_mark_student_answers_page(cls,student_name):
student_name_text = "Student Name: " + str(student_name)
cls.__ui_mainwindow.label_50.setText(student_name_text)
@classmethod
def display_questions_ready_to_be_marked(cls, questions_ids_tuple):
cls.__ui_mainwindow.tableWidget_25.clear()
row = 0
col = 0
for (question_id,) in questions_ids_tuple:
question_text = "Question " + str(question_id)
question_item = QTableWidgetItem(question_text)
cls.__ui_mainwindow.tableWidget_25.setItem(row, col, question_item)
row += 1
@classmethod
def get_question_id_to_mark(cls):
question_item = cls.__ui_mainwindow.tableWidget_26.item(0,0)
if (question_item == None):
return None
question_id_text = question_item.text()
question_id_text_list = question_id_text.split(" ")
question_id = question_id_text_list.pop()
return int(question_id)
@classmethod
def get_exam_id_on_marking_question_page(cls):
exam_id_text = cls.__ui_mainwindow.label_62.text()
exam_id_text_list = exam_id_text.split(" ")
exam_id = exam_id_text_list.pop()
return int(exam_id)
@classmethod
def get_student_id_on_marking_question_page(cls):
student_id_text = cls.__ui_mainwindow.label_63.text()
student_id_text_list = student_id_text.split(" ")
student_id = student_id_text_list.pop()
return int(student_id)
@classmethod
def setup_essay_question_ui_dialog_to_mark(cls, question_details):
question_body = question_details[0]
student_answer = question_details[1]
available_points = question_details[2]
cls.__dialog = QtWidgets.QDialog()
cls.__ui_dialog = Ui_MarkingEssayQuestionDialog()
cls.__ui_dialog.setupUi(cls.__dialog)
cls.__ui_dialog.label_2.setText(question_body)
cls.__ui_dialog.label_3.setText(student_answer)
cls.__ui_dialog.label_4.setText("Total Available Points: " + str(available_points))
cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)
cls.__dialog.show()
return cls.__ui_dialog
@classmethod
def get_essay_question_marked_points(cls):
points_text = cls.__ui_dialog.lineEdit.text()
return int(points_text)
@classmethod
def refresh_drop_question_to_mark_box(cls):
cls.__ui_mainwindow.tableWidget_26.clear()
@classmethod
def refresh_mark_student_questions_answers_page(cls):
cls.__ui_mainwindow.label_62.clear()
cls.__ui_mainwindow.label_63.clear()
cls.__ui_mainwindow.label_50.clear()
@classmethod
def display_no_more_questions_to_mark_message(cls):
cls.__ui_mainwindow.label_66.setText("No More Questions To Mark")
@classmethod
def display_marked_exams(cls, marked_exams_ids):
cls.__ui_mainwindow.tableWidget_18.clear()
row = 0
col = 0
for (exam_id,) in marked_exams_ids:
exam_text = "Exam " + str(exam_id)
exam_item = QTableWidgetItem(exam_text)
cls.__ui_mainwindow.tableWidget_18.setItem(row, col, exam_item)
if (col >= 4):
row += 1
col = 0
else:
col += 1
@classmethod
def display_no_question_selected_to_mark_message(cls):
cls.__ui_mainwindow.label_66.setText("No Question Selected To Mark")
@classmethod
def refresh_drop_student_to_mark_questions_box(cls):
cls.__ui_mainwindow.tableWidget_19.clear()
@classmethod
def get_exam_id_to_release_result(cls):
exam_item = cls.__ui_mainwindow.tableWidget_21.item(0,0)
if (exam_item == None):
return None
exam_id_text = exam_item.text()
exam_id_text_list = exam_id_text.split(" ")
exam_id = exam_id_text_list.pop()
return int(exam_id)
@classmethod
def display_result_released_exams(cls, result_released_exams_ids):
cls.__ui_mainwindow.tableWidget_11.clear()
row = 0
col = 0
for (exam_id,) in result_released_exams_ids:
exam_text = "Exam " + str(exam_id) + " Result"
exam_item = QTableWidgetItem(exam_text)
cls.__ui_mainwindow.tableWidget_11.setItem(row, col, exam_item)
if (col >= 9):
row += 1
col = 0
else:
col += 1
@classmethod
def refresh_drop_exam_to_release_result_box(cls):
cls.__ui_mainwindow.tableWidget_21.clear()
@classmethod
def display_exam_results(cls, exam_results_ids):
cls.__ui_mainwindow.tableWidget_11.clear()
row = 0
col = 0
for (exam_result_id, ) in exam_results_ids:
exam_result_text = "Exam " + str(exam_result_id) + " Result"
exam_result_item = QTableWidgetItem(exam_result_text)
cls.__ui_mainwindow.tableWidget_11.setItem(row, col, exam_result_item)
if (col >= 9):
row += 1
col = 0
else:
col += 1
@classmethod
def get_exam_result_id_to_load_details(cls):
exam_result_id_text = cls.__ui_mainwindow.lineEdit_22.text()
return int(exam_result_id_text)
@classmethod
def display_school_classes_to_view_exam_result_details(cls, school_classes_ids):
school_classes_ids_list = cls.make_string_to_list(school_classes_ids)
cls.__ui_mainwindow.tableWidget_12.clear()
row = 0
col = 0
for school_class_id in school_classes_ids_list:
school_class_text = "Class " + str(school_class_id)
school_class_item = QTableWidgetItem(school_class_text)
cls.__ui_mainwindow.tableWidget_12.setItem(row, col, school_class_item)
row += 1
@classmethod
def display_exam_result_id_on_view_exam_result_details_page(cls, exam_result_id):
cls.__ui_mainwindow.label_33.setText("Exam Result ID: " + str(exam_result_id))
@classmethod
def get_school_class_id_to_view_exam_result(cls):
school_class_id_text = cls.__ui_mainwindow.lineEdit_23.text()
try:
school_class_id = int(school_class_id_text)
except:
return None
return school_class_id
@classmethod
def display_students_full_names_to_view_exam_result(cls, students_full_names):
cls.__ui_mainwindow.tableWidget_13.clear()
row = 0
col = 0
for (student_full_name, ) in students_full_names:
student_item = QTableWidgetItem(student_full_name)
cls.__ui_mainwindow.tableWidget_13.setItem(row, col, student_item)
row += 1
@classmethod
def get_student_full_name_to_view_exam_result(cls):
student_item = cls.__ui_mainwindow.tableWidget_22.item(0, 0)
student_name_text = student_item.text()
return student_name_text
@classmethod
def get_exam_result_id_on_view_exam_result_page(cls):
exam_result_id_text = cls.__ui_mainwindow.label_33.text()
exam_result_id_text_list = exam_result_id_text.split(" ")
exam_result_id = exam_result_id_text_list.pop()
try:
exam_result_id_int = int(exam_result_id)
return exam_result_id_int
except:
return None
@classmethod
def display_student_exam_result_details(cls, exam_result_details):
student_id = exam_result_details[0]
student_full_name = exam_result_details[1]
date_of_birth = exam_result_details[2]
school_class_id = exam_result_details[3]
exam_id = exam_result_details[4]
total_available_points = exam_result_details[5]
total_points_gained = exam_result_details[6]
average_percentage_mark = exam_result_details[7]
cls.__ui_mainwindow.label_58.setText(str(student_id))
cls.__ui_mainwindow.label_72.setText(str(student_full_name))
cls.__ui_mainwindow.label_75.setText(str(date_of_birth))
cls.__ui_mainwindow.label_76.setText(str(school_class_id))
cls.__ui_mainwindow.label_77.setText(str(exam_id))
cls.__ui_mainwindow.label_78.setText(str(total_available_points))
cls.__ui_mainwindow.label_79.setText(str(total_points_gained))
cls.__ui_mainwindow.label_80.setText(str(average_percentage_mark) + " %")
@classmethod
def get_exam_id_to_view_details(cls):
exam_id_text = cls.__ui_mainwindow.lineEdit_14.text()
if (exam_id_text == ""):
return None
try:
exam_id = int(exam_id_text)
return exam_id
except:
return None
@classmethod
def diaplay_exam_id_on_view_exam_details_page(cls, exam_id):
cls.__ui_mainwindow.label_18.setText("Exam ID: " + str(exam_id))
@classmethod
def display_questions_on_view_exam_details_page(cls, questions_ids):
cls.__ui_mainwindow.tableWidget_7.clear()
questions_ids_list = cls.make_string_to_list(questions_ids)
row = 0
col = 0
for question_id in questions_ids_list:
question_text = "Question " + str(question_id)
question_item = QTableWidgetItem(question_text)
cls.__ui_mainwindow.tableWidget_7.setItem(row, col, question_item)
row += 1
@classmethod
def display_first_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names):
cls.display_first_school_class_id_on_view_exam_details_page(school_class_id)
cls.__ui_mainwindow.tableWidget_27.clear()
row = 0
col = 0
for (student_name, ) in students_full_names:
student_item = QTableWidgetItem(student_name)
cls.__ui_mainwindow.tableWidget_27.setItem(row, col, student_item)
row += 1
@classmethod
def display_first_school_class_id_on_view_exam_details_page(cls, school_class_id):
cls.__ui_mainwindow.label_67.setText("CLass " + str(school_class_id))
@classmethod
def display_second_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names):
cls.display_second_school_class_id_on_view_exam_details_page(school_class_id)
cls.__ui_mainwindow.tableWidget_28.clear()
row = 0
col = 0
for (student_name, ) in students_full_names:
student_item = QTableWidgetItem(student_name)
cls.__ui_mainwindow.tableWidget_28.setItem(row, col, student_item)
row += 1
@classmethod
def display_second_school_class_id_on_view_exam_details_page(cls, school_class_id):
cls.__ui_mainwindow.label_68.setText("CLass " + str(school_class_id))
@classmethod
def display_third_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names):
cls.display_third_school_class_id_on_view_exam_details_page(school_class_id)
cls.__ui_mainwindow.tableWidget_29.clear()
row = 0
col = 0
for (student_name, ) in students_full_names:
student_item = QTableWidgetItem(student_name)
cls.__ui_mainwindow.tableWidget_29.setItem(row, col, student_item)
row += 1
@classmethod
def display_third_school_class_id_on_view_exam_details_page(cls, school_class_id):
cls.__ui_mainwindow.label_69.setText("CLass " + str(school_class_id))
@classmethod
def display_fourth_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names):
cls.display_fourth_school_class_id_on_view_exam_details_page(school_class_id)
cls.__ui_mainwindow.tableWidget_30.clear()
row = 0
col = 0
for (student_name, ) in students_full_names:
student_item = QTableWidgetItem(student_name)
cls.__ui_mainwindow.tableWidget_30.setItem(row, col, student_item)
row += 1
@classmethod
def display_fourth_school_class_id_on_view_exam_details_page(cls, school_class_id):
cls.__ui_mainwindow.label_70.setText("CLass " + str(school_class_id))
@classmethod
def display_fifth_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names):
cls.display_fifth_school_class_id_on_view_exam_details_page(school_class_id)
cls.__ui_mainwindow.tableWidget_31.clear()
row = 0
col = 0
for (student_name, ) in students_full_names:
student_item = QTableWidgetItem(student_name)
cls.__ui_mainwindow.tableWidget_31.setItem(row, col, student_item)
row += 1
@classmethod
def display_fifth_school_class_id_on_view_exam_details_page(cls, school_class_id):
cls.__ui_mainwindow.label_71.setText("CLass " + str(school_class_id))
@classmethod
def make_string_to_list(cls, any_string):
any_string = str(any_string)
any_list = any_string.split(" ")
return any_list
@classmethod
def refresh_drop_student_to_view_exam_result_details_box(cls):
cls.__ui_mainwindow.tableWidget_22.clear()
@classmethod
def display_exam_result_id_invalid_message(cls):
cls.__ui_mainwindow.label_32.setText("Exam Result ID Invalid")
@classmethod
def refresh_load_exam_result_details_page(cls):
cls.__ui_mainwindow.label_33.clear()
cls.__ui_mainwindow.tableWidget_12.clear()
cls.__ui_mainwindow.lineEdit_23.clear()
cls.__ui_mainwindow.tableWidget_13.clear()
cls.__ui_mainwindow.tableWidget_22.clear()
cls.__ui_mainwindow.label_58.clear()
cls.__ui_mainwindow.label_72.clear()
cls.__ui_mainwindow.label_75.clear()
cls.__ui_mainwindow.label_76.clear()
cls.__ui_mainwindow.label_77.clear()
cls.__ui_mainwindow.label_78.clear()
cls.__ui_mainwindow.label_79.clear()
cls.__ui_mainwindow.label_80.clear()
@classmethod
def refresh_exam_result_id_validity_error_message(cls):
cls.__ui_mainwindow.label_32.clear()
@classmethod
def display_school_class_id_invalid_to_view_result_message(cls):
cls.__ui_mainwindow.label_81.setText("School Class ID Invalid To View")
@classmethod
def refresh_school_class_details_table_on_view_exam_result_page(cls):
cls.__ui_mainwindow.tableWidget_13.clear()
@classmethod
def refresh_school_class_id_invalid_to_view_exam_result_error_label(cls):
cls.__ui_mainwindow.label_81.clear()
@classmethod
def refresh_student_exam_result_details(cls):
cls.__ui_mainwindow.label_58.clear()
cls.__ui_mainwindow.label_72.clear()
cls.__ui_mainwindow.label_75.clear()
cls.__ui_mainwindow.label_76.clear()
cls.__ui_mainwindow.label_77.clear()
cls.__ui_mainwindow.label_78.clear()
cls.__ui_mainwindow.label_79.clear()
cls.__ui_mainwindow.label_80.clear()
@classmethod
def display_no_exam_result_id_selected_message(cls):
cls.__ui_mainwindow.label_81.setText("No Exam Result ID Selected")
@classmethod
def refresh_school_class_id_input_box_on_view_exam_result_details_page(cls):
cls.__ui_mainwindow.lineEdit_23.clear()
@classmethod
def refresh_view_exam_details_by_id_page(cls):
cls.__ui_mainwindow.label_18.setText("Exam ID : ")
cls.__ui_mainwindow.tableWidget_7.clear()
cls.__ui_mainwindow.label_67.clear()
cls.__ui_mainwindow.label_68.clear()
cls.__ui_mainwindow.label_69.clear()
cls.__ui_mainwindow.label_70.clear()
cls.__ui_mainwindow.label_71.clear()
cls.__ui_mainwindow.tableWidget_27.clear()
cls.__ui_mainwindow.tableWidget_28.clear()
cls.__ui_mainwindow.tableWidget_29.clear()
cls.__ui_mainwindow.tableWidget_30.clear()
cls.__ui_mainwindow.tableWidget_31.clear()
@classmethod
def refresh_students_table_on_view_exam_result_details_page(cls):
cls.__ui_mainwindow.tableWidget_13.clear()
@classmethod
def refresh_school_classes_table_on_view_exam_result_details_page(cls):
cls.__ui_mainwindow.tableWidget_12.clear()
def __str__(self):
return ("This is TeacherGUI Object")
|
flexible
|
{
"blob_id": "98f234ca0cbec419466de0504fd8d5c68fd07627",
"index": 9609,
"step-1": "<mask token>\n\n\nclass TeacherGUI:\n <mask token>\n\n @classmethod\n def setup(cls, ui_mainwindow):\n cls.__ui_mainwindow = ui_mainwindow\n\n @classmethod\n def display_all_active_school_classes(cls, school_classes):\n cls.__ui_mainwindow.tableWidget_14.clear()\n row = 0\n col = 0\n for school_class_id, in school_classes:\n school_class_text = 'Class ' + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_14.setItem(row, col,\n school_class_item)\n if col >= 4:\n col = 0\n row += 1\n else:\n col += 1\n <mask token>\n\n @classmethod\n def display_not_completed_exams(cls, not_completed_exams):\n cls.__ui_mainwindow.tableWidget_16.clear()\n row = 0\n col = 0\n for exam_id, in not_completed_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_16.setItem(row, col, exam_item)\n if col >= 6:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_ready_to_be_marked_exams(cls, ready_to_be_marked_exams):\n cls.__ui_mainwindow.tableWidget_17.clear()\n row = 0\n col = 0\n for exam_id, in ready_to_be_marked_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_17.setItem(row, col, exam_item)\n if col >= 3:\n col = 0\n row += 1\n else:\n col += 1\n <mask token>\n\n @classmethod\n def display_multiple_answers_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_14.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_MultipleAnswersQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label.setText(question_body)\n cls.__ui_dialog.label_3.setText(option_A_text)\n cls.__ui_dialog.label_4.setText(option_B_text)\n cls.__ui_dialog.label_5.setText(option_C_text)\n cls.__ui_dialog.label_6.setText(option_D_text)\n cls.__ui_dialog.label_7.setText(option_E_text)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def display_essay_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_EssayQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n if question_body == '':\n cls.__ui_dialog.label.setText('Question Body')\n else:\n cls.__ui_dialog.label.setText(question_body)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def close_dialog(cls):\n cls.__dialog.close()\n\n @classmethod\n def get_single_answer_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit.toPlainText()\n if question_body == '':\n return None\n option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()\n if option_A_text == '':\n return None\n option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()\n if option_B_text == '':\n return None\n option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()\n if option_C_text == '':\n return None\n option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()\n if option_D_text == '':\n return None\n option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()\n if option_E_text == '':\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_3.text()\n if year_level_text == '':\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_4.text()\n if phrase_tag_text == '':\n return None\n correct_answers_list = []\n if cls.__ui_mainwindow.radioButton.isChecked():\n correct_answers_list.append('A')\n if cls.__ui_mainwindow.radioButton_2.isChecked():\n correct_answers_list.append('B')\n if cls.__ui_mainwindow.radioButton_5.isChecked():\n correct_answers_list.append('C')\n if cls.__ui_mainwindow.radioButton_3.isChecked():\n correct_answers_list.append('D')\n if cls.__ui_mainwindow.radioButton_4.isChecked():\n correct_answers_list.append('E')\n if correct_answers_list == []:\n return None\n if len(correct_answers_list) > 1:\n return None\n return (question_body, option_A_text, option_B_text, option_C_text,\n option_D_text, option_E_text, year_level, phrase_tag_text,\n correct_answers_list)\n <mask token>\n\n @classmethod\n def get_essay_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n if question_body == '':\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_26.text()\n if year_level_text == '':\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_27.text()\n if phrase_tag_text == '':\n return None\n return question_body, year_level, phrase_tag_text\n\n @classmethod\n def display_all_active_questions(cls, active_questions_tuple):\n row = 0\n col = 0\n for question_pk_tuple in active_questions_tuple:\n question_pk = question_pk_tuple[0]\n question_text = 'Question ' + str(question_pk)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget.setItem(row, col, question_item)\n if col >= 7:\n col = 0\n row += 1\n else:\n col += 1\n <mask token>\n\n @classmethod\n def display_invalid_single_answer_question_creation_message(cls):\n cls.__ui_mainwindow.label_4.setText(\n 'Invalid Single Answer Question Creation')\n\n @classmethod\n def display_create_multiple_answers_question_success(cls):\n cls.__ui_mainwindow.label_11.setText(\n 'Create Multiple Answers Question Success')\n\n @classmethod\n def display_invalid_multiple_answers_question_creation_message(cls):\n cls.__ui_mainwindow.label_11.setText(\n 'Invalid Multiple Answers Question Creation')\n\n @classmethod\n def display_invalid_essay_question_creation_message(cls):\n cls.__ui_mainwindow.label_42.setText('Invalid Essay Question Creation')\n\n @classmethod\n def display_create_essay_question_success(cls):\n cls.__ui_mainwindow.label_42.setText('Create Essay Question Success')\n\n @classmethod\n def display_invalid_modification_message(cls):\n cls.__ui_mainwindow.label_57.setText('Invalid Modification')\n\n @classmethod\n def refresh_create_single_answer_question_page(cls):\n cls.__ui_mainwindow.textEdit.clear()\n cls.__ui_mainwindow.textEdit_2.clear()\n cls.__ui_mainwindow.textEdit_3.clear()\n cls.__ui_mainwindow.textEdit_4.clear()\n cls.__ui_mainwindow.textEdit_5.clear()\n cls.__ui_mainwindow.textEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_3.clear()\n cls.__ui_mainwindow.lineEdit_4.clear()\n cls.__ui_mainwindow.radioButton.setChecked(False)\n cls.__ui_mainwindow.radioButton_2.setChecked(False)\n cls.__ui_mainwindow.radioButton_3.setChecked(False)\n cls.__ui_mainwindow.radioButton_4.setChecked(False)\n cls.__ui_mainwindow.radioButton_5.setChecked(False)\n <mask token>\n\n @classmethod\n def refresh_view_or_modify_question_page(cls):\n cls.__ui_mainwindow.lineEdit_5.clear()\n cls.__ui_mainwindow.label_45.setText('Question ID: ')\n cls.__ui_mainwindow.label_47.setText('Question Type: ')\n cls.__ui_mainwindow.label_57.clear()\n cls.__ui_mainwindow.label_12.clear()\n cls.__ui_mainwindow.textEdit_7.clear()\n cls.__ui_mainwindow.textEdit_8.clear()\n cls.__ui_mainwindow.textEdit_9.clear()\n cls.__ui_mainwindow.textEdit_10.clear()\n cls.__ui_mainwindow.textEdit_11.clear()\n cls.__ui_mainwindow.textEdit_20.clear()\n cls.__ui_mainwindow.lineEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_8.clear()\n cls.__ui_mainwindow.lineEdit_28.clear()\n cls.__ui_mainwindow.radioButton_6.setDisabled(False)\n cls.__ui_mainwindow.radioButton_7.setDisabled(False)\n cls.__ui_mainwindow.radioButton_8.setDisabled(False)\n cls.__ui_mainwindow.radioButton_9.setDisabled(False)\n cls.__ui_mainwindow.radioButton_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_8.setDisabled(False)\n cls.__ui_mainwindow.textEdit_9.setDisabled(False)\n cls.__ui_mainwindow.textEdit_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_11.setDisabled(False)\n cls.__ui_mainwindow.textEdit_20.setDisabled(False)\n cls.__ui_mainwindow.radioButton_6.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_6.setChecked(False)\n cls.__ui_mainwindow.radioButton_7.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_7.setChecked(False)\n cls.__ui_mainwindow.radioButton_8.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_8.setChecked(False)\n cls.__ui_mainwindow.radioButton_9.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_9.setChecked(False)\n cls.__ui_mainwindow.radioButton_10.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_10.setChecked(False)\n\n @classmethod\n def refresh_create_essay_question_page(cls):\n cls.__ui_mainwindow.textEdit_19.clear()\n cls.__ui_mainwindow.lineEdit_26.clear()\n cls.__ui_mainwindow.lineEdit_27.clear()\n\n @classmethod\n def refresh_create_exam_page(cls):\n cls.__ui_mainwindow.tableWidget_3.clear()\n cls.__ui_mainwindow.tableWidget_4.clear()\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.lineEdit_13.clear()\n\n @classmethod\n def get_question_id_to_load(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_5.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def load_single_answer_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answer = question_details[11]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n if correct_answer == 'A':\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n elif correct_answer == 'B':\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n elif correct_answer == 'C':\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n elif correct_answer == 'D':\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n elif correct_answer == 'E':\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n @classmethod\n def load_multiple_answers_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answers = question_details[11]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n if correct_answers.count('A') == 1:\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n if correct_answers.count('B') == 1:\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n if correct_answers.count('C') == 1:\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n if correct_answers.count('D') == 1:\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n if correct_answers.count('E') == 1:\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n @classmethod\n def load_essay_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.radioButton_6.setDisabled(True)\n cls.__ui_mainwindow.radioButton_7.setDisabled(True)\n cls.__ui_mainwindow.radioButton_8.setDisabled(True)\n cls.__ui_mainwindow.radioButton_9.setDisabled(True)\n cls.__ui_mainwindow.radioButton_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_8.setDisabled(True)\n cls.__ui_mainwindow.textEdit_9.setDisabled(True)\n cls.__ui_mainwindow.textEdit_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_11.setDisabled(True)\n cls.__ui_mainwindow.textEdit_20.setDisabled(True)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n\n @classmethod\n def display_question_id_invalid_to_load_message(cls):\n cls.__ui_mainwindow.label_12.setText('Invalid Question ID To Load')\n\n @classmethod\n def display_modification_success_message(cls):\n cls.__ui_mainwindow.label_57.setText('Modification Success')\n\n @classmethod\n def display_invalid_school_class_id_message(cls):\n cls.__ui_mainwindow.label_14.setText('Invalid School Class ID')\n cls.__ui_mainwindow.tableWidget_15.clear()\n\n @classmethod\n def get_question_type_to_modify(cls):\n question_type_text = cls.__ui_mainwindow.label_47.text()\n if question_type_text == 'Question Type: Single Answer':\n return 'Single Answer'\n elif question_type_text == 'Question Type: Multiple Answers':\n return 'Multiple Answers'\n elif question_type_text == 'Question Type: Essay':\n return 'Essay'\n\n @classmethod\n def get_single_answer_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answer = cls.get_single_correct_answer_to_modify()\n if correct_answer == None:\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body, option_A_text, option_B_text,\n option_C_text, option_D_text, option_E_text, correct_answer)\n\n @classmethod\n def get_multiple_answers_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answers = cls.get_multiple_correct_answers_to_modify()\n if correct_answers == None:\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body, option_A_text, option_B_text,\n option_C_text, option_D_text, option_E_text, correct_answers)\n\n @classmethod\n def get_essay_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n try:\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n except:\n return None\n try:\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n except:\n return None\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n if question_tag == '':\n return None\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n if question_body == '':\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body)\n\n @classmethod\n def get_question_id_to_modify(cls):\n question_id_text = cls.__ui_mainwindow.label_45.text()\n question_id_text_split = question_id_text.split()\n question_id = int(question_id_text_split.pop())\n return question_id\n <mask token>\n\n @classmethod\n def get_multiple_correct_answers_to_modify(cls):\n correct_answers = ''\n if cls.__ui_mainwindow.radioButton_6.isChecked():\n correct_answers = correct_answers + 'A'\n if cls.__ui_mainwindow.radioButton_7.isChecked():\n correct_answers = correct_answers + 'B'\n if cls.__ui_mainwindow.radioButton_8.isChecked():\n correct_answers = correct_answers + 'C'\n if cls.__ui_mainwindow.radioButton_9.isChecked():\n correct_answers = correct_answers + 'D'\n if cls.__ui_mainwindow.radioButton_10.isChecked():\n correct_answers = correct_answers + 'E'\n if len(correct_answers) == 0:\n return None\n if len(correct_answers) > 4:\n return None\n return correct_answers\n\n @classmethod\n def get_school_class_id_to_view_students(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_9.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def display_school_class_details(cls, school_class_details):\n cls.__ui_mainwindow.tableWidget_15.clear()\n row = 0\n col = 0\n for student, in school_class_details:\n student_item = QTableWidgetItem(student)\n cls.__ui_mainwindow.tableWidget_15.setItem(row, col, student_item)\n if col >= 1:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def refresh_view_school_class_details_page(cls):\n cls.__ui_mainwindow.label_14.clear()\n <mask token>\n\n @classmethod\n def get_number_of_school_classes_in_current_exam(cls):\n number_of_school_classes = 0\n row = 0\n col = 0\n for counter in range(5):\n if cls.__ui_mainwindow.tableWidget_4.item(row, col) != None:\n number_of_school_classes += 1\n row += 1\n return number_of_school_classes\n\n @classmethod\n def display_number_of_questions_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'Questions Are Full In Current Exam')\n\n @classmethod\n def display_number_of_school_classes_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Classes Are Full In Current Exam')\n\n @classmethod\n def display_no_question_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText('No Question In Current Exam')\n\n @classmethod\n def display_no_school_class_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText('No School Class In Current Exam')\n <mask token>\n\n @classmethod\n def display_school_class_id_already_added_to_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Class ID Already Added To Current Exam')\n\n @classmethod\n def display_question_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText('Question ID Invalid')\n\n @classmethod\n def display_school_class_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText('School CLass ID Invalid')\n\n @classmethod\n def display_question_id_not_already_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'Question ID Not Aleady In Current Exam')\n <mask token>\n\n @classmethod\n def display_create_exam_success_message(cls):\n cls.__ui_mainwindow.label_17.setText('Create Exam Success')\n\n @classmethod\n def refresh_mark_exam_drop_box(cls):\n cls.__ui_mainwindow.tableWidget_19.clear()\n\n @classmethod\n def get_question_id_to_add_to_exam(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_10.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n <mask token>\n <mask token>\n\n @classmethod\n def get_school_class_id_to_remove_from_exam(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_13.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def add_question_id_to_current_exam(cls, question_id):\n row = 0\n col = 0\n for counter in range(10):\n if cls.__ui_mainwindow.tableWidget_3.item(row, col) == None:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_3.setItem(row, col,\n question_item)\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def add_school_class_id_to_current_exam(cls, school_class_id):\n row = 0\n col = 0\n for counter in range(10):\n if cls.__ui_mainwindow.tableWidget_4.item(row, col) == None:\n school_class_text = 'CLass ' + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_4.setItem(row, col,\n school_class_item)\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def remove_question_id_from_current_exam(cls, question_id):\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if question_item != None:\n question_text = question_item.text()\n question_text_split = question_text.split(' ')\n question_id_in_exam = int(question_text_split.pop())\n if question_id_in_exam == question_id:\n cls.__ui_mainwindow.tableWidget_3.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n\n @classmethod\n def remove_school_class_id_from_current_exam(cls, school_class_id):\n col = 0\n for row in range(5):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col\n )\n if school_class_item != None:\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(' ')\n school_class_id_in_exam = int(school_class_text_split.pop())\n if school_class_id_in_exam == school_class_id:\n cls.__ui_mainwindow.tableWidget_4.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_13.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n <mask token>\n\n @classmethod\n def is_school_class_id_already_added_to_current_exam(cls, school_class_id):\n string_of_school_classes_ids_in_current_exam = (cls.\n get_string_of_school_classes_ids_in_current_exam())\n list_of_school_classes_ids = (\n string_of_school_classes_ids_in_current_exam.split(' '))\n return list_of_school_classes_ids.count(str(school_class_id)) == 1\n\n @classmethod\n def get_string_of_question_ids_in_current_exam(cls):\n string_of_question_ids = ''\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if question_item != None:\n question_text = question_item.text()\n question_text_split = question_text.split(' ')\n question_id = question_text_split.pop()\n string_of_question_ids = (string_of_question_ids +\n question_id + ' ')\n return string_of_question_ids.rstrip()\n\n @classmethod\n def get_string_of_school_classes_ids_in_current_exam(cls):\n string_of_school_classes_ids = ''\n col = 0\n for row in range(10):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col\n )\n if school_class_item != None:\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(' ')\n school_class_id = school_class_text_split.pop()\n string_of_school_classes_ids = (\n string_of_school_classes_ids + school_class_id + ' ')\n return string_of_school_classes_ids.rstrip()\n\n @classmethod\n def get_exam_id_to_mark(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_20.item(0, 0)\n exam_text = exam_item.text()\n exam_text_split = exam_text.split(' ')\n exam_id_text = exam_text_split.pop()\n return int(exam_id_text)\n <mask token>\n\n @classmethod\n def display_students_full_names_with_questions_ready_to_be_marked(cls,\n students_names_list):\n cls.__ui_mainwindow.tableWidget_6.clear()\n row = 0\n col = 0\n for student_name in students_names_list:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_6.setItem(row, col, student_item)\n if col >= 4:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def get_student_name_to_mark_answers(cls):\n student_item = cls.__ui_mainwindow.tableWidget_19.item(0, 0)\n student_name = student_item.text()\n return student_name\n\n @classmethod\n def get_exam_id_to_mark_student_answers(cls):\n exam_id_text = cls.__ui_mainwindow.label_49.text()\n exam_id_text_split = exam_id_text.split(' ')\n exam_id = exam_id_text_split.pop()\n return int(exam_id)\n <mask token>\n\n @classmethod\n def display_student_id_on_mark_student_answers_page(cls, student_id):\n student_id_text = 'Student ID: ' + str(student_id)\n cls.__ui_mainwindow.label_63.setText(student_id_text)\n\n @classmethod\n def display_student_name_on_mark_student_answers_page(cls, student_name):\n student_name_text = 'Student Name: ' + str(student_name)\n cls.__ui_mainwindow.label_50.setText(student_name_text)\n\n @classmethod\n def display_questions_ready_to_be_marked(cls, questions_ids_tuple):\n cls.__ui_mainwindow.tableWidget_25.clear()\n row = 0\n col = 0\n for question_id, in questions_ids_tuple:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_25.setItem(row, col, question_item)\n row += 1\n <mask token>\n\n @classmethod\n def get_exam_id_on_marking_question_page(cls):\n exam_id_text = cls.__ui_mainwindow.label_62.text()\n exam_id_text_list = exam_id_text.split(' ')\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def get_student_id_on_marking_question_page(cls):\n student_id_text = cls.__ui_mainwindow.label_63.text()\n student_id_text_list = student_id_text.split(' ')\n student_id = student_id_text_list.pop()\n return int(student_id)\n <mask token>\n\n @classmethod\n def get_essay_question_marked_points(cls):\n points_text = cls.__ui_dialog.lineEdit.text()\n return int(points_text)\n\n @classmethod\n def refresh_drop_question_to_mark_box(cls):\n cls.__ui_mainwindow.tableWidget_26.clear()\n\n @classmethod\n def refresh_mark_student_questions_answers_page(cls):\n cls.__ui_mainwindow.label_62.clear()\n cls.__ui_mainwindow.label_63.clear()\n cls.__ui_mainwindow.label_50.clear()\n\n @classmethod\n def display_no_more_questions_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText('No More Questions To Mark')\n\n @classmethod\n def display_marked_exams(cls, marked_exams_ids):\n cls.__ui_mainwindow.tableWidget_18.clear()\n row = 0\n col = 0\n for exam_id, in marked_exams_ids:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_18.setItem(row, col, exam_item)\n if col >= 4:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def display_no_question_selected_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText('No Question Selected To Mark')\n <mask token>\n\n @classmethod\n def get_exam_id_to_release_result(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_21.item(0, 0)\n if exam_item == None:\n return None\n exam_id_text = exam_item.text()\n exam_id_text_list = exam_id_text.split(' ')\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def display_result_released_exams(cls, result_released_exams_ids):\n cls.__ui_mainwindow.tableWidget_11.clear()\n row = 0\n col = 0\n for exam_id, in result_released_exams_ids:\n exam_text = 'Exam ' + str(exam_id) + ' Result'\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_11.setItem(row, col, exam_item)\n if col >= 9:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def refresh_drop_exam_to_release_result_box(cls):\n cls.__ui_mainwindow.tableWidget_21.clear()\n <mask token>\n\n @classmethod\n def get_exam_result_id_to_load_details(cls):\n exam_result_id_text = cls.__ui_mainwindow.lineEdit_22.text()\n return int(exam_result_id_text)\n <mask token>\n <mask token>\n\n @classmethod\n def get_school_class_id_to_view_exam_result(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_23.text()\n try:\n school_class_id = int(school_class_id_text)\n except:\n return None\n return school_class_id\n\n @classmethod\n def display_students_full_names_to_view_exam_result(cls,\n students_full_names):\n cls.__ui_mainwindow.tableWidget_13.clear()\n row = 0\n col = 0\n for student_full_name, in students_full_names:\n student_item = QTableWidgetItem(student_full_name)\n cls.__ui_mainwindow.tableWidget_13.setItem(row, col, student_item)\n row += 1\n <mask token>\n\n @classmethod\n def get_exam_result_id_on_view_exam_result_page(cls):\n exam_result_id_text = cls.__ui_mainwindow.label_33.text()\n exam_result_id_text_list = exam_result_id_text.split(' ')\n exam_result_id = exam_result_id_text_list.pop()\n try:\n exam_result_id_int = int(exam_result_id)\n return exam_result_id_int\n except:\n return None\n <mask token>\n <mask token>\n <mask token>\n\n @classmethod\n def display_questions_on_view_exam_details_page(cls, questions_ids):\n cls.__ui_mainwindow.tableWidget_7.clear()\n questions_ids_list = cls.make_string_to_list(questions_ids)\n row = 0\n col = 0\n for question_id in questions_ids_list:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_7.setItem(row, col, question_item)\n row += 1\n\n @classmethod\n def display_first_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_first_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_27.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_27.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_first_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_67.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_second_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_second_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_28.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_28.setItem(row, col, student_item)\n row += 1\n <mask token>\n <mask token>\n\n @classmethod\n def display_third_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_69.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_fourth_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_fourth_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_30.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_30.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fourth_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_70.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_fifth_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_fifth_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_31.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_31.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fifth_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_71.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def make_string_to_list(cls, any_string):\n any_string = str(any_string)\n any_list = any_string.split(' ')\n return any_list\n\n @classmethod\n def refresh_drop_student_to_view_exam_result_details_box(cls):\n cls.__ui_mainwindow.tableWidget_22.clear()\n\n @classmethod\n def display_exam_result_id_invalid_message(cls):\n cls.__ui_mainwindow.label_32.setText('Exam Result ID Invalid')\n\n @classmethod\n def refresh_load_exam_result_details_page(cls):\n cls.__ui_mainwindow.label_33.clear()\n cls.__ui_mainwindow.tableWidget_12.clear()\n cls.__ui_mainwindow.lineEdit_23.clear()\n cls.__ui_mainwindow.tableWidget_13.clear()\n cls.__ui_mainwindow.tableWidget_22.clear()\n cls.__ui_mainwindow.label_58.clear()\n cls.__ui_mainwindow.label_72.clear()\n cls.__ui_mainwindow.label_75.clear()\n cls.__ui_mainwindow.label_76.clear()\n cls.__ui_mainwindow.label_77.clear()\n cls.__ui_mainwindow.label_78.clear()\n cls.__ui_mainwindow.label_79.clear()\n cls.__ui_mainwindow.label_80.clear()\n\n @classmethod\n def refresh_exam_result_id_validity_error_message(cls):\n cls.__ui_mainwindow.label_32.clear()\n\n @classmethod\n def display_school_class_id_invalid_to_view_result_message(cls):\n cls.__ui_mainwindow.label_81.setText('School Class ID Invalid To View')\n\n @classmethod\n def refresh_school_class_details_table_on_view_exam_result_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n\n @classmethod\n def refresh_school_class_id_invalid_to_view_exam_result_error_label(cls):\n cls.__ui_mainwindow.label_81.clear()\n <mask token>\n\n @classmethod\n def display_no_exam_result_id_selected_message(cls):\n cls.__ui_mainwindow.label_81.setText('No Exam Result ID Selected')\n\n @classmethod\n def refresh_school_class_id_input_box_on_view_exam_result_details_page(cls\n ):\n cls.__ui_mainwindow.lineEdit_23.clear()\n\n @classmethod\n def refresh_view_exam_details_by_id_page(cls):\n cls.__ui_mainwindow.label_18.setText('Exam ID : ')\n cls.__ui_mainwindow.tableWidget_7.clear()\n cls.__ui_mainwindow.label_67.clear()\n cls.__ui_mainwindow.label_68.clear()\n cls.__ui_mainwindow.label_69.clear()\n cls.__ui_mainwindow.label_70.clear()\n cls.__ui_mainwindow.label_71.clear()\n cls.__ui_mainwindow.tableWidget_27.clear()\n cls.__ui_mainwindow.tableWidget_28.clear()\n cls.__ui_mainwindow.tableWidget_29.clear()\n cls.__ui_mainwindow.tableWidget_30.clear()\n cls.__ui_mainwindow.tableWidget_31.clear()\n\n @classmethod\n def refresh_students_table_on_view_exam_result_details_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass TeacherGUI:\n <mask token>\n\n @classmethod\n def setup(cls, ui_mainwindow):\n cls.__ui_mainwindow = ui_mainwindow\n\n @classmethod\n def display_all_active_school_classes(cls, school_classes):\n cls.__ui_mainwindow.tableWidget_14.clear()\n row = 0\n col = 0\n for school_class_id, in school_classes:\n school_class_text = 'Class ' + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_14.setItem(row, col,\n school_class_item)\n if col >= 4:\n col = 0\n row += 1\n else:\n col += 1\n <mask token>\n\n @classmethod\n def display_not_completed_exams(cls, not_completed_exams):\n cls.__ui_mainwindow.tableWidget_16.clear()\n row = 0\n col = 0\n for exam_id, in not_completed_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_16.setItem(row, col, exam_item)\n if col >= 6:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_ready_to_be_marked_exams(cls, ready_to_be_marked_exams):\n cls.__ui_mainwindow.tableWidget_17.clear()\n row = 0\n col = 0\n for exam_id, in ready_to_be_marked_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_17.setItem(row, col, exam_item)\n if col >= 3:\n col = 0\n row += 1\n else:\n col += 1\n <mask token>\n\n @classmethod\n def display_multiple_answers_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_14.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_MultipleAnswersQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label.setText(question_body)\n cls.__ui_dialog.label_3.setText(option_A_text)\n cls.__ui_dialog.label_4.setText(option_B_text)\n cls.__ui_dialog.label_5.setText(option_C_text)\n cls.__ui_dialog.label_6.setText(option_D_text)\n cls.__ui_dialog.label_7.setText(option_E_text)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def display_essay_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_EssayQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n if question_body == '':\n cls.__ui_dialog.label.setText('Question Body')\n else:\n cls.__ui_dialog.label.setText(question_body)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def close_dialog(cls):\n cls.__dialog.close()\n\n @classmethod\n def get_single_answer_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit.toPlainText()\n if question_body == '':\n return None\n option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()\n if option_A_text == '':\n return None\n option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()\n if option_B_text == '':\n return None\n option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()\n if option_C_text == '':\n return None\n option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()\n if option_D_text == '':\n return None\n option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()\n if option_E_text == '':\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_3.text()\n if year_level_text == '':\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_4.text()\n if phrase_tag_text == '':\n return None\n correct_answers_list = []\n if cls.__ui_mainwindow.radioButton.isChecked():\n correct_answers_list.append('A')\n if cls.__ui_mainwindow.radioButton_2.isChecked():\n correct_answers_list.append('B')\n if cls.__ui_mainwindow.radioButton_5.isChecked():\n correct_answers_list.append('C')\n if cls.__ui_mainwindow.radioButton_3.isChecked():\n correct_answers_list.append('D')\n if cls.__ui_mainwindow.radioButton_4.isChecked():\n correct_answers_list.append('E')\n if correct_answers_list == []:\n return None\n if len(correct_answers_list) > 1:\n return None\n return (question_body, option_A_text, option_B_text, option_C_text,\n option_D_text, option_E_text, year_level, phrase_tag_text,\n correct_answers_list)\n <mask token>\n\n @classmethod\n def get_essay_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n if question_body == '':\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_26.text()\n if year_level_text == '':\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_27.text()\n if phrase_tag_text == '':\n return None\n return question_body, year_level, phrase_tag_text\n\n @classmethod\n def display_all_active_questions(cls, active_questions_tuple):\n row = 0\n col = 0\n for question_pk_tuple in active_questions_tuple:\n question_pk = question_pk_tuple[0]\n question_text = 'Question ' + str(question_pk)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget.setItem(row, col, question_item)\n if col >= 7:\n col = 0\n row += 1\n else:\n col += 1\n <mask token>\n\n @classmethod\n def display_invalid_single_answer_question_creation_message(cls):\n cls.__ui_mainwindow.label_4.setText(\n 'Invalid Single Answer Question Creation')\n\n @classmethod\n def display_create_multiple_answers_question_success(cls):\n cls.__ui_mainwindow.label_11.setText(\n 'Create Multiple Answers Question Success')\n\n @classmethod\n def display_invalid_multiple_answers_question_creation_message(cls):\n cls.__ui_mainwindow.label_11.setText(\n 'Invalid Multiple Answers Question Creation')\n\n @classmethod\n def display_invalid_essay_question_creation_message(cls):\n cls.__ui_mainwindow.label_42.setText('Invalid Essay Question Creation')\n\n @classmethod\n def display_create_essay_question_success(cls):\n cls.__ui_mainwindow.label_42.setText('Create Essay Question Success')\n\n @classmethod\n def display_invalid_modification_message(cls):\n cls.__ui_mainwindow.label_57.setText('Invalid Modification')\n\n @classmethod\n def refresh_create_single_answer_question_page(cls):\n cls.__ui_mainwindow.textEdit.clear()\n cls.__ui_mainwindow.textEdit_2.clear()\n cls.__ui_mainwindow.textEdit_3.clear()\n cls.__ui_mainwindow.textEdit_4.clear()\n cls.__ui_mainwindow.textEdit_5.clear()\n cls.__ui_mainwindow.textEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_3.clear()\n cls.__ui_mainwindow.lineEdit_4.clear()\n cls.__ui_mainwindow.radioButton.setChecked(False)\n cls.__ui_mainwindow.radioButton_2.setChecked(False)\n cls.__ui_mainwindow.radioButton_3.setChecked(False)\n cls.__ui_mainwindow.radioButton_4.setChecked(False)\n cls.__ui_mainwindow.radioButton_5.setChecked(False)\n <mask token>\n\n @classmethod\n def refresh_view_or_modify_question_page(cls):\n cls.__ui_mainwindow.lineEdit_5.clear()\n cls.__ui_mainwindow.label_45.setText('Question ID: ')\n cls.__ui_mainwindow.label_47.setText('Question Type: ')\n cls.__ui_mainwindow.label_57.clear()\n cls.__ui_mainwindow.label_12.clear()\n cls.__ui_mainwindow.textEdit_7.clear()\n cls.__ui_mainwindow.textEdit_8.clear()\n cls.__ui_mainwindow.textEdit_9.clear()\n cls.__ui_mainwindow.textEdit_10.clear()\n cls.__ui_mainwindow.textEdit_11.clear()\n cls.__ui_mainwindow.textEdit_20.clear()\n cls.__ui_mainwindow.lineEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_8.clear()\n cls.__ui_mainwindow.lineEdit_28.clear()\n cls.__ui_mainwindow.radioButton_6.setDisabled(False)\n cls.__ui_mainwindow.radioButton_7.setDisabled(False)\n cls.__ui_mainwindow.radioButton_8.setDisabled(False)\n cls.__ui_mainwindow.radioButton_9.setDisabled(False)\n cls.__ui_mainwindow.radioButton_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_8.setDisabled(False)\n cls.__ui_mainwindow.textEdit_9.setDisabled(False)\n cls.__ui_mainwindow.textEdit_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_11.setDisabled(False)\n cls.__ui_mainwindow.textEdit_20.setDisabled(False)\n cls.__ui_mainwindow.radioButton_6.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_6.setChecked(False)\n cls.__ui_mainwindow.radioButton_7.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_7.setChecked(False)\n cls.__ui_mainwindow.radioButton_8.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_8.setChecked(False)\n cls.__ui_mainwindow.radioButton_9.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_9.setChecked(False)\n cls.__ui_mainwindow.radioButton_10.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_10.setChecked(False)\n\n @classmethod\n def refresh_create_essay_question_page(cls):\n cls.__ui_mainwindow.textEdit_19.clear()\n cls.__ui_mainwindow.lineEdit_26.clear()\n cls.__ui_mainwindow.lineEdit_27.clear()\n\n @classmethod\n def refresh_create_exam_page(cls):\n cls.__ui_mainwindow.tableWidget_3.clear()\n cls.__ui_mainwindow.tableWidget_4.clear()\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.lineEdit_13.clear()\n\n @classmethod\n def get_question_id_to_load(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_5.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def load_single_answer_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answer = question_details[11]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n if correct_answer == 'A':\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n elif correct_answer == 'B':\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n elif correct_answer == 'C':\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n elif correct_answer == 'D':\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n elif correct_answer == 'E':\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n @classmethod\n def load_multiple_answers_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answers = question_details[11]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n if correct_answers.count('A') == 1:\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n if correct_answers.count('B') == 1:\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n if correct_answers.count('C') == 1:\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n if correct_answers.count('D') == 1:\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n if correct_answers.count('E') == 1:\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n @classmethod\n def load_essay_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.radioButton_6.setDisabled(True)\n cls.__ui_mainwindow.radioButton_7.setDisabled(True)\n cls.__ui_mainwindow.radioButton_8.setDisabled(True)\n cls.__ui_mainwindow.radioButton_9.setDisabled(True)\n cls.__ui_mainwindow.radioButton_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_8.setDisabled(True)\n cls.__ui_mainwindow.textEdit_9.setDisabled(True)\n cls.__ui_mainwindow.textEdit_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_11.setDisabled(True)\n cls.__ui_mainwindow.textEdit_20.setDisabled(True)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n\n @classmethod\n def display_question_id_invalid_to_load_message(cls):\n cls.__ui_mainwindow.label_12.setText('Invalid Question ID To Load')\n\n @classmethod\n def display_modification_success_message(cls):\n cls.__ui_mainwindow.label_57.setText('Modification Success')\n\n @classmethod\n def display_invalid_school_class_id_message(cls):\n cls.__ui_mainwindow.label_14.setText('Invalid School Class ID')\n cls.__ui_mainwindow.tableWidget_15.clear()\n\n @classmethod\n def get_question_type_to_modify(cls):\n question_type_text = cls.__ui_mainwindow.label_47.text()\n if question_type_text == 'Question Type: Single Answer':\n return 'Single Answer'\n elif question_type_text == 'Question Type: Multiple Answers':\n return 'Multiple Answers'\n elif question_type_text == 'Question Type: Essay':\n return 'Essay'\n\n @classmethod\n def get_single_answer_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answer = cls.get_single_correct_answer_to_modify()\n if correct_answer == None:\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body, option_A_text, option_B_text,\n option_C_text, option_D_text, option_E_text, correct_answer)\n\n @classmethod\n def get_multiple_answers_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answers = cls.get_multiple_correct_answers_to_modify()\n if correct_answers == None:\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body, option_A_text, option_B_text,\n option_C_text, option_D_text, option_E_text, correct_answers)\n\n @classmethod\n def get_essay_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n try:\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n except:\n return None\n try:\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n except:\n return None\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n if question_tag == '':\n return None\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n if question_body == '':\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body)\n\n @classmethod\n def get_question_id_to_modify(cls):\n question_id_text = cls.__ui_mainwindow.label_45.text()\n question_id_text_split = question_id_text.split()\n question_id = int(question_id_text_split.pop())\n return question_id\n <mask token>\n\n @classmethod\n def get_multiple_correct_answers_to_modify(cls):\n correct_answers = ''\n if cls.__ui_mainwindow.radioButton_6.isChecked():\n correct_answers = correct_answers + 'A'\n if cls.__ui_mainwindow.radioButton_7.isChecked():\n correct_answers = correct_answers + 'B'\n if cls.__ui_mainwindow.radioButton_8.isChecked():\n correct_answers = correct_answers + 'C'\n if cls.__ui_mainwindow.radioButton_9.isChecked():\n correct_answers = correct_answers + 'D'\n if cls.__ui_mainwindow.radioButton_10.isChecked():\n correct_answers = correct_answers + 'E'\n if len(correct_answers) == 0:\n return None\n if len(correct_answers) > 4:\n return None\n return correct_answers\n\n @classmethod\n def get_school_class_id_to_view_students(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_9.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def display_school_class_details(cls, school_class_details):\n cls.__ui_mainwindow.tableWidget_15.clear()\n row = 0\n col = 0\n for student, in school_class_details:\n student_item = QTableWidgetItem(student)\n cls.__ui_mainwindow.tableWidget_15.setItem(row, col, student_item)\n if col >= 1:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def refresh_view_school_class_details_page(cls):\n cls.__ui_mainwindow.label_14.clear()\n <mask token>\n\n @classmethod\n def get_number_of_school_classes_in_current_exam(cls):\n number_of_school_classes = 0\n row = 0\n col = 0\n for counter in range(5):\n if cls.__ui_mainwindow.tableWidget_4.item(row, col) != None:\n number_of_school_classes += 1\n row += 1\n return number_of_school_classes\n\n @classmethod\n def display_number_of_questions_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'Questions Are Full In Current Exam')\n\n @classmethod\n def display_number_of_school_classes_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Classes Are Full In Current Exam')\n\n @classmethod\n def display_no_question_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText('No Question In Current Exam')\n\n @classmethod\n def display_no_school_class_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText('No School Class In Current Exam')\n <mask token>\n\n @classmethod\n def display_school_class_id_already_added_to_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Class ID Already Added To Current Exam')\n\n @classmethod\n def display_question_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText('Question ID Invalid')\n\n @classmethod\n def display_school_class_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText('School CLass ID Invalid')\n\n @classmethod\n def display_question_id_not_already_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'Question ID Not Aleady In Current Exam')\n <mask token>\n\n @classmethod\n def display_create_exam_success_message(cls):\n cls.__ui_mainwindow.label_17.setText('Create Exam Success')\n\n @classmethod\n def refresh_mark_exam_drop_box(cls):\n cls.__ui_mainwindow.tableWidget_19.clear()\n\n @classmethod\n def get_question_id_to_add_to_exam(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_10.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def get_school_class_id_to_add_to_exam(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_11.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n <mask token>\n\n @classmethod\n def get_school_class_id_to_remove_from_exam(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_13.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def add_question_id_to_current_exam(cls, question_id):\n row = 0\n col = 0\n for counter in range(10):\n if cls.__ui_mainwindow.tableWidget_3.item(row, col) == None:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_3.setItem(row, col,\n question_item)\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def add_school_class_id_to_current_exam(cls, school_class_id):\n row = 0\n col = 0\n for counter in range(10):\n if cls.__ui_mainwindow.tableWidget_4.item(row, col) == None:\n school_class_text = 'CLass ' + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_4.setItem(row, col,\n school_class_item)\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def remove_question_id_from_current_exam(cls, question_id):\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if question_item != None:\n question_text = question_item.text()\n question_text_split = question_text.split(' ')\n question_id_in_exam = int(question_text_split.pop())\n if question_id_in_exam == question_id:\n cls.__ui_mainwindow.tableWidget_3.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n\n @classmethod\n def remove_school_class_id_from_current_exam(cls, school_class_id):\n col = 0\n for row in range(5):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col\n )\n if school_class_item != None:\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(' ')\n school_class_id_in_exam = int(school_class_text_split.pop())\n if school_class_id_in_exam == school_class_id:\n cls.__ui_mainwindow.tableWidget_4.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_13.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n <mask token>\n\n @classmethod\n def is_school_class_id_already_added_to_current_exam(cls, school_class_id):\n string_of_school_classes_ids_in_current_exam = (cls.\n get_string_of_school_classes_ids_in_current_exam())\n list_of_school_classes_ids = (\n string_of_school_classes_ids_in_current_exam.split(' '))\n return list_of_school_classes_ids.count(str(school_class_id)) == 1\n\n @classmethod\n def get_string_of_question_ids_in_current_exam(cls):\n string_of_question_ids = ''\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if question_item != None:\n question_text = question_item.text()\n question_text_split = question_text.split(' ')\n question_id = question_text_split.pop()\n string_of_question_ids = (string_of_question_ids +\n question_id + ' ')\n return string_of_question_ids.rstrip()\n\n @classmethod\n def get_string_of_school_classes_ids_in_current_exam(cls):\n string_of_school_classes_ids = ''\n col = 0\n for row in range(10):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col\n )\n if school_class_item != None:\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(' ')\n school_class_id = school_class_text_split.pop()\n string_of_school_classes_ids = (\n string_of_school_classes_ids + school_class_id + ' ')\n return string_of_school_classes_ids.rstrip()\n\n @classmethod\n def get_exam_id_to_mark(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_20.item(0, 0)\n exam_text = exam_item.text()\n exam_text_split = exam_text.split(' ')\n exam_id_text = exam_text_split.pop()\n return int(exam_id_text)\n <mask token>\n\n @classmethod\n def display_students_full_names_with_questions_ready_to_be_marked(cls,\n students_names_list):\n cls.__ui_mainwindow.tableWidget_6.clear()\n row = 0\n col = 0\n for student_name in students_names_list:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_6.setItem(row, col, student_item)\n if col >= 4:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def get_student_name_to_mark_answers(cls):\n student_item = cls.__ui_mainwindow.tableWidget_19.item(0, 0)\n student_name = student_item.text()\n return student_name\n\n @classmethod\n def get_exam_id_to_mark_student_answers(cls):\n exam_id_text = cls.__ui_mainwindow.label_49.text()\n exam_id_text_split = exam_id_text.split(' ')\n exam_id = exam_id_text_split.pop()\n return int(exam_id)\n <mask token>\n\n @classmethod\n def display_student_id_on_mark_student_answers_page(cls, student_id):\n student_id_text = 'Student ID: ' + str(student_id)\n cls.__ui_mainwindow.label_63.setText(student_id_text)\n\n @classmethod\n def display_student_name_on_mark_student_answers_page(cls, student_name):\n student_name_text = 'Student Name: ' + str(student_name)\n cls.__ui_mainwindow.label_50.setText(student_name_text)\n\n @classmethod\n def display_questions_ready_to_be_marked(cls, questions_ids_tuple):\n cls.__ui_mainwindow.tableWidget_25.clear()\n row = 0\n col = 0\n for question_id, in questions_ids_tuple:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_25.setItem(row, col, question_item)\n row += 1\n <mask token>\n\n @classmethod\n def get_exam_id_on_marking_question_page(cls):\n exam_id_text = cls.__ui_mainwindow.label_62.text()\n exam_id_text_list = exam_id_text.split(' ')\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def get_student_id_on_marking_question_page(cls):\n student_id_text = cls.__ui_mainwindow.label_63.text()\n student_id_text_list = student_id_text.split(' ')\n student_id = student_id_text_list.pop()\n return int(student_id)\n <mask token>\n\n @classmethod\n def get_essay_question_marked_points(cls):\n points_text = cls.__ui_dialog.lineEdit.text()\n return int(points_text)\n\n @classmethod\n def refresh_drop_question_to_mark_box(cls):\n cls.__ui_mainwindow.tableWidget_26.clear()\n\n @classmethod\n def refresh_mark_student_questions_answers_page(cls):\n cls.__ui_mainwindow.label_62.clear()\n cls.__ui_mainwindow.label_63.clear()\n cls.__ui_mainwindow.label_50.clear()\n\n @classmethod\n def display_no_more_questions_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText('No More Questions To Mark')\n\n @classmethod\n def display_marked_exams(cls, marked_exams_ids):\n cls.__ui_mainwindow.tableWidget_18.clear()\n row = 0\n col = 0\n for exam_id, in marked_exams_ids:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_18.setItem(row, col, exam_item)\n if col >= 4:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def display_no_question_selected_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText('No Question Selected To Mark')\n <mask token>\n\n @classmethod\n def get_exam_id_to_release_result(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_21.item(0, 0)\n if exam_item == None:\n return None\n exam_id_text = exam_item.text()\n exam_id_text_list = exam_id_text.split(' ')\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def display_result_released_exams(cls, result_released_exams_ids):\n cls.__ui_mainwindow.tableWidget_11.clear()\n row = 0\n col = 0\n for exam_id, in result_released_exams_ids:\n exam_text = 'Exam ' + str(exam_id) + ' Result'\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_11.setItem(row, col, exam_item)\n if col >= 9:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def refresh_drop_exam_to_release_result_box(cls):\n cls.__ui_mainwindow.tableWidget_21.clear()\n <mask token>\n\n @classmethod\n def get_exam_result_id_to_load_details(cls):\n exam_result_id_text = cls.__ui_mainwindow.lineEdit_22.text()\n return int(exam_result_id_text)\n <mask token>\n\n @classmethod\n def display_exam_result_id_on_view_exam_result_details_page(cls,\n exam_result_id):\n cls.__ui_mainwindow.label_33.setText('Exam Result ID: ' + str(\n exam_result_id))\n\n @classmethod\n def get_school_class_id_to_view_exam_result(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_23.text()\n try:\n school_class_id = int(school_class_id_text)\n except:\n return None\n return school_class_id\n\n @classmethod\n def display_students_full_names_to_view_exam_result(cls,\n students_full_names):\n cls.__ui_mainwindow.tableWidget_13.clear()\n row = 0\n col = 0\n for student_full_name, in students_full_names:\n student_item = QTableWidgetItem(student_full_name)\n cls.__ui_mainwindow.tableWidget_13.setItem(row, col, student_item)\n row += 1\n <mask token>\n\n @classmethod\n def get_exam_result_id_on_view_exam_result_page(cls):\n exam_result_id_text = cls.__ui_mainwindow.label_33.text()\n exam_result_id_text_list = exam_result_id_text.split(' ')\n exam_result_id = exam_result_id_text_list.pop()\n try:\n exam_result_id_int = int(exam_result_id)\n return exam_result_id_int\n except:\n return None\n\n @classmethod\n def display_student_exam_result_details(cls, exam_result_details):\n student_id = exam_result_details[0]\n student_full_name = exam_result_details[1]\n date_of_birth = exam_result_details[2]\n school_class_id = exam_result_details[3]\n exam_id = exam_result_details[4]\n total_available_points = exam_result_details[5]\n total_points_gained = exam_result_details[6]\n average_percentage_mark = exam_result_details[7]\n cls.__ui_mainwindow.label_58.setText(str(student_id))\n cls.__ui_mainwindow.label_72.setText(str(student_full_name))\n cls.__ui_mainwindow.label_75.setText(str(date_of_birth))\n cls.__ui_mainwindow.label_76.setText(str(school_class_id))\n cls.__ui_mainwindow.label_77.setText(str(exam_id))\n cls.__ui_mainwindow.label_78.setText(str(total_available_points))\n cls.__ui_mainwindow.label_79.setText(str(total_points_gained))\n cls.__ui_mainwindow.label_80.setText(str(average_percentage_mark) +\n ' %')\n <mask token>\n <mask token>\n\n @classmethod\n def display_questions_on_view_exam_details_page(cls, questions_ids):\n cls.__ui_mainwindow.tableWidget_7.clear()\n questions_ids_list = cls.make_string_to_list(questions_ids)\n row = 0\n col = 0\n for question_id in questions_ids_list:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_7.setItem(row, col, question_item)\n row += 1\n\n @classmethod\n def display_first_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_first_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_27.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_27.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_first_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_67.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_second_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_second_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_28.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_28.setItem(row, col, student_item)\n row += 1\n <mask token>\n <mask token>\n\n @classmethod\n def display_third_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_69.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_fourth_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_fourth_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_30.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_30.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fourth_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_70.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_fifth_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_fifth_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_31.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_31.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fifth_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_71.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def make_string_to_list(cls, any_string):\n any_string = str(any_string)\n any_list = any_string.split(' ')\n return any_list\n\n @classmethod\n def refresh_drop_student_to_view_exam_result_details_box(cls):\n cls.__ui_mainwindow.tableWidget_22.clear()\n\n @classmethod\n def display_exam_result_id_invalid_message(cls):\n cls.__ui_mainwindow.label_32.setText('Exam Result ID Invalid')\n\n @classmethod\n def refresh_load_exam_result_details_page(cls):\n cls.__ui_mainwindow.label_33.clear()\n cls.__ui_mainwindow.tableWidget_12.clear()\n cls.__ui_mainwindow.lineEdit_23.clear()\n cls.__ui_mainwindow.tableWidget_13.clear()\n cls.__ui_mainwindow.tableWidget_22.clear()\n cls.__ui_mainwindow.label_58.clear()\n cls.__ui_mainwindow.label_72.clear()\n cls.__ui_mainwindow.label_75.clear()\n cls.__ui_mainwindow.label_76.clear()\n cls.__ui_mainwindow.label_77.clear()\n cls.__ui_mainwindow.label_78.clear()\n cls.__ui_mainwindow.label_79.clear()\n cls.__ui_mainwindow.label_80.clear()\n\n @classmethod\n def refresh_exam_result_id_validity_error_message(cls):\n cls.__ui_mainwindow.label_32.clear()\n\n @classmethod\n def display_school_class_id_invalid_to_view_result_message(cls):\n cls.__ui_mainwindow.label_81.setText('School Class ID Invalid To View')\n\n @classmethod\n def refresh_school_class_details_table_on_view_exam_result_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n\n @classmethod\n def refresh_school_class_id_invalid_to_view_exam_result_error_label(cls):\n cls.__ui_mainwindow.label_81.clear()\n <mask token>\n\n @classmethod\n def display_no_exam_result_id_selected_message(cls):\n cls.__ui_mainwindow.label_81.setText('No Exam Result ID Selected')\n\n @classmethod\n def refresh_school_class_id_input_box_on_view_exam_result_details_page(cls\n ):\n cls.__ui_mainwindow.lineEdit_23.clear()\n\n @classmethod\n def refresh_view_exam_details_by_id_page(cls):\n cls.__ui_mainwindow.label_18.setText('Exam ID : ')\n cls.__ui_mainwindow.tableWidget_7.clear()\n cls.__ui_mainwindow.label_67.clear()\n cls.__ui_mainwindow.label_68.clear()\n cls.__ui_mainwindow.label_69.clear()\n cls.__ui_mainwindow.label_70.clear()\n cls.__ui_mainwindow.label_71.clear()\n cls.__ui_mainwindow.tableWidget_27.clear()\n cls.__ui_mainwindow.tableWidget_28.clear()\n cls.__ui_mainwindow.tableWidget_29.clear()\n cls.__ui_mainwindow.tableWidget_30.clear()\n cls.__ui_mainwindow.tableWidget_31.clear()\n\n @classmethod\n def refresh_students_table_on_view_exam_result_details_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass TeacherGUI:\n\n def __init__(self):\n pass\n\n @classmethod\n def setup(cls, ui_mainwindow):\n cls.__ui_mainwindow = ui_mainwindow\n\n @classmethod\n def display_all_active_school_classes(cls, school_classes):\n cls.__ui_mainwindow.tableWidget_14.clear()\n row = 0\n col = 0\n for school_class_id, in school_classes:\n school_class_text = 'Class ' + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_14.setItem(row, col,\n school_class_item)\n if col >= 4:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_all_exams(cls, all_exams):\n cls.__ui_mainwindow.tableWidget_5.clear()\n row = 0\n col = 0\n for exam_id, in all_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_5.setItem(row, col, exam_item)\n if col >= 9:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_not_completed_exams(cls, not_completed_exams):\n cls.__ui_mainwindow.tableWidget_16.clear()\n row = 0\n col = 0\n for exam_id, in not_completed_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_16.setItem(row, col, exam_item)\n if col >= 6:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_ready_to_be_marked_exams(cls, ready_to_be_marked_exams):\n cls.__ui_mainwindow.tableWidget_17.clear()\n row = 0\n col = 0\n for exam_id, in ready_to_be_marked_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_17.setItem(row, col, exam_item)\n if col >= 3:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_single_answer_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_SingleAnswerQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label.setText(question_body)\n cls.__ui_dialog.label_3.setText('A ' + option_A_text)\n cls.__ui_dialog.label_4.setText('B ' + option_B_text)\n cls.__ui_dialog.label_5.setText('C ' + option_C_text)\n cls.__ui_dialog.label_6.setText('D ' + option_D_text)\n cls.__ui_dialog.label_7.setText('E ' + option_E_text)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def display_multiple_answers_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_14.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_MultipleAnswersQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label.setText(question_body)\n cls.__ui_dialog.label_3.setText(option_A_text)\n cls.__ui_dialog.label_4.setText(option_B_text)\n cls.__ui_dialog.label_5.setText(option_C_text)\n cls.__ui_dialog.label_6.setText(option_D_text)\n cls.__ui_dialog.label_7.setText(option_E_text)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def display_essay_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_EssayQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n if question_body == '':\n cls.__ui_dialog.label.setText('Question Body')\n else:\n cls.__ui_dialog.label.setText(question_body)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def close_dialog(cls):\n cls.__dialog.close()\n\n @classmethod\n def get_single_answer_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit.toPlainText()\n if question_body == '':\n return None\n option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()\n if option_A_text == '':\n return None\n option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()\n if option_B_text == '':\n return None\n option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()\n if option_C_text == '':\n return None\n option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()\n if option_D_text == '':\n return None\n option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()\n if option_E_text == '':\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_3.text()\n if year_level_text == '':\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_4.text()\n if phrase_tag_text == '':\n return None\n correct_answers_list = []\n if cls.__ui_mainwindow.radioButton.isChecked():\n correct_answers_list.append('A')\n if cls.__ui_mainwindow.radioButton_2.isChecked():\n correct_answers_list.append('B')\n if cls.__ui_mainwindow.radioButton_5.isChecked():\n correct_answers_list.append('C')\n if cls.__ui_mainwindow.radioButton_3.isChecked():\n correct_answers_list.append('D')\n if cls.__ui_mainwindow.radioButton_4.isChecked():\n correct_answers_list.append('E')\n if correct_answers_list == []:\n return None\n if len(correct_answers_list) > 1:\n return None\n return (question_body, option_A_text, option_B_text, option_C_text,\n option_D_text, option_E_text, year_level, phrase_tag_text,\n correct_answers_list)\n <mask token>\n\n @classmethod\n def get_essay_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n if question_body == '':\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_26.text()\n if year_level_text == '':\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_27.text()\n if phrase_tag_text == '':\n return None\n return question_body, year_level, phrase_tag_text\n\n @classmethod\n def display_all_active_questions(cls, active_questions_tuple):\n row = 0\n col = 0\n for question_pk_tuple in active_questions_tuple:\n question_pk = question_pk_tuple[0]\n question_text = 'Question ' + str(question_pk)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget.setItem(row, col, question_item)\n if col >= 7:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_create_single_answer_question_success(cls):\n cls.__ui_mainwindow.label_4.setText(\n 'Create Single Answer Question Success')\n\n @classmethod\n def display_invalid_single_answer_question_creation_message(cls):\n cls.__ui_mainwindow.label_4.setText(\n 'Invalid Single Answer Question Creation')\n\n @classmethod\n def display_create_multiple_answers_question_success(cls):\n cls.__ui_mainwindow.label_11.setText(\n 'Create Multiple Answers Question Success')\n\n @classmethod\n def display_invalid_multiple_answers_question_creation_message(cls):\n cls.__ui_mainwindow.label_11.setText(\n 'Invalid Multiple Answers Question Creation')\n\n @classmethod\n def display_invalid_essay_question_creation_message(cls):\n cls.__ui_mainwindow.label_42.setText('Invalid Essay Question Creation')\n\n @classmethod\n def display_create_essay_question_success(cls):\n cls.__ui_mainwindow.label_42.setText('Create Essay Question Success')\n\n @classmethod\n def display_invalid_modification_message(cls):\n cls.__ui_mainwindow.label_57.setText('Invalid Modification')\n\n @classmethod\n def refresh_create_single_answer_question_page(cls):\n cls.__ui_mainwindow.textEdit.clear()\n cls.__ui_mainwindow.textEdit_2.clear()\n cls.__ui_mainwindow.textEdit_3.clear()\n cls.__ui_mainwindow.textEdit_4.clear()\n cls.__ui_mainwindow.textEdit_5.clear()\n cls.__ui_mainwindow.textEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_3.clear()\n cls.__ui_mainwindow.lineEdit_4.clear()\n cls.__ui_mainwindow.radioButton.setChecked(False)\n cls.__ui_mainwindow.radioButton_2.setChecked(False)\n cls.__ui_mainwindow.radioButton_3.setChecked(False)\n cls.__ui_mainwindow.radioButton_4.setChecked(False)\n cls.__ui_mainwindow.radioButton_5.setChecked(False)\n <mask token>\n\n @classmethod\n def refresh_view_or_modify_question_page(cls):\n cls.__ui_mainwindow.lineEdit_5.clear()\n cls.__ui_mainwindow.label_45.setText('Question ID: ')\n cls.__ui_mainwindow.label_47.setText('Question Type: ')\n cls.__ui_mainwindow.label_57.clear()\n cls.__ui_mainwindow.label_12.clear()\n cls.__ui_mainwindow.textEdit_7.clear()\n cls.__ui_mainwindow.textEdit_8.clear()\n cls.__ui_mainwindow.textEdit_9.clear()\n cls.__ui_mainwindow.textEdit_10.clear()\n cls.__ui_mainwindow.textEdit_11.clear()\n cls.__ui_mainwindow.textEdit_20.clear()\n cls.__ui_mainwindow.lineEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_8.clear()\n cls.__ui_mainwindow.lineEdit_28.clear()\n cls.__ui_mainwindow.radioButton_6.setDisabled(False)\n cls.__ui_mainwindow.radioButton_7.setDisabled(False)\n cls.__ui_mainwindow.radioButton_8.setDisabled(False)\n cls.__ui_mainwindow.radioButton_9.setDisabled(False)\n cls.__ui_mainwindow.radioButton_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_8.setDisabled(False)\n cls.__ui_mainwindow.textEdit_9.setDisabled(False)\n cls.__ui_mainwindow.textEdit_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_11.setDisabled(False)\n cls.__ui_mainwindow.textEdit_20.setDisabled(False)\n cls.__ui_mainwindow.radioButton_6.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_6.setChecked(False)\n cls.__ui_mainwindow.radioButton_7.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_7.setChecked(False)\n cls.__ui_mainwindow.radioButton_8.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_8.setChecked(False)\n cls.__ui_mainwindow.radioButton_9.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_9.setChecked(False)\n cls.__ui_mainwindow.radioButton_10.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_10.setChecked(False)\n\n @classmethod\n def refresh_create_essay_question_page(cls):\n cls.__ui_mainwindow.textEdit_19.clear()\n cls.__ui_mainwindow.lineEdit_26.clear()\n cls.__ui_mainwindow.lineEdit_27.clear()\n\n @classmethod\n def refresh_create_exam_page(cls):\n cls.__ui_mainwindow.tableWidget_3.clear()\n cls.__ui_mainwindow.tableWidget_4.clear()\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.lineEdit_13.clear()\n\n @classmethod\n def get_question_id_to_load(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_5.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def load_single_answer_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answer = question_details[11]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n if correct_answer == 'A':\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n elif correct_answer == 'B':\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n elif correct_answer == 'C':\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n elif correct_answer == 'D':\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n elif correct_answer == 'E':\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n @classmethod\n def load_multiple_answers_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answers = question_details[11]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n if correct_answers.count('A') == 1:\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n if correct_answers.count('B') == 1:\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n if correct_answers.count('C') == 1:\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n if correct_answers.count('D') == 1:\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n if correct_answers.count('E') == 1:\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n @classmethod\n def load_essay_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.radioButton_6.setDisabled(True)\n cls.__ui_mainwindow.radioButton_7.setDisabled(True)\n cls.__ui_mainwindow.radioButton_8.setDisabled(True)\n cls.__ui_mainwindow.radioButton_9.setDisabled(True)\n cls.__ui_mainwindow.radioButton_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_8.setDisabled(True)\n cls.__ui_mainwindow.textEdit_9.setDisabled(True)\n cls.__ui_mainwindow.textEdit_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_11.setDisabled(True)\n cls.__ui_mainwindow.textEdit_20.setDisabled(True)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n\n @classmethod\n def display_question_id_invalid_to_load_message(cls):\n cls.__ui_mainwindow.label_12.setText('Invalid Question ID To Load')\n\n @classmethod\n def display_modification_success_message(cls):\n cls.__ui_mainwindow.label_57.setText('Modification Success')\n\n @classmethod\n def display_invalid_school_class_id_message(cls):\n cls.__ui_mainwindow.label_14.setText('Invalid School Class ID')\n cls.__ui_mainwindow.tableWidget_15.clear()\n\n @classmethod\n def get_question_type_to_modify(cls):\n question_type_text = cls.__ui_mainwindow.label_47.text()\n if question_type_text == 'Question Type: Single Answer':\n return 'Single Answer'\n elif question_type_text == 'Question Type: Multiple Answers':\n return 'Multiple Answers'\n elif question_type_text == 'Question Type: Essay':\n return 'Essay'\n\n @classmethod\n def get_single_answer_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answer = cls.get_single_correct_answer_to_modify()\n if correct_answer == None:\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body, option_A_text, option_B_text,\n option_C_text, option_D_text, option_E_text, correct_answer)\n\n @classmethod\n def get_multiple_answers_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answers = cls.get_multiple_correct_answers_to_modify()\n if correct_answers == None:\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body, option_A_text, option_B_text,\n option_C_text, option_D_text, option_E_text, correct_answers)\n\n @classmethod\n def get_essay_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n try:\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n except:\n return None\n try:\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n except:\n return None\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n if question_tag == '':\n return None\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n if question_body == '':\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body)\n\n @classmethod\n def get_question_id_to_modify(cls):\n question_id_text = cls.__ui_mainwindow.label_45.text()\n question_id_text_split = question_id_text.split()\n question_id = int(question_id_text_split.pop())\n return question_id\n <mask token>\n\n @classmethod\n def get_multiple_correct_answers_to_modify(cls):\n correct_answers = ''\n if cls.__ui_mainwindow.radioButton_6.isChecked():\n correct_answers = correct_answers + 'A'\n if cls.__ui_mainwindow.radioButton_7.isChecked():\n correct_answers = correct_answers + 'B'\n if cls.__ui_mainwindow.radioButton_8.isChecked():\n correct_answers = correct_answers + 'C'\n if cls.__ui_mainwindow.radioButton_9.isChecked():\n correct_answers = correct_answers + 'D'\n if cls.__ui_mainwindow.radioButton_10.isChecked():\n correct_answers = correct_answers + 'E'\n if len(correct_answers) == 0:\n return None\n if len(correct_answers) > 4:\n return None\n return correct_answers\n\n @classmethod\n def get_school_class_id_to_view_students(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_9.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def display_school_class_details(cls, school_class_details):\n cls.__ui_mainwindow.tableWidget_15.clear()\n row = 0\n col = 0\n for student, in school_class_details:\n student_item = QTableWidgetItem(student)\n cls.__ui_mainwindow.tableWidget_15.setItem(row, col, student_item)\n if col >= 1:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def refresh_view_school_class_details_page(cls):\n cls.__ui_mainwindow.label_14.clear()\n <mask token>\n\n @classmethod\n def get_number_of_school_classes_in_current_exam(cls):\n number_of_school_classes = 0\n row = 0\n col = 0\n for counter in range(5):\n if cls.__ui_mainwindow.tableWidget_4.item(row, col) != None:\n number_of_school_classes += 1\n row += 1\n return number_of_school_classes\n\n @classmethod\n def display_number_of_questions_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'Questions Are Full In Current Exam')\n\n @classmethod\n def display_number_of_school_classes_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Classes Are Full In Current Exam')\n\n @classmethod\n def display_no_question_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText('No Question In Current Exam')\n\n @classmethod\n def display_no_school_class_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText('No School Class In Current Exam')\n <mask token>\n\n @classmethod\n def display_school_class_id_already_added_to_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Class ID Already Added To Current Exam')\n\n @classmethod\n def display_question_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText('Question ID Invalid')\n\n @classmethod\n def display_school_class_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText('School CLass ID Invalid')\n\n @classmethod\n def display_question_id_not_already_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'Question ID Not Aleady In Current Exam')\n\n @classmethod\n def display_school_class_id_not_already_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Class ID Not Aleady In Current Exam')\n\n @classmethod\n def display_create_exam_success_message(cls):\n cls.__ui_mainwindow.label_17.setText('Create Exam Success')\n\n @classmethod\n def refresh_mark_exam_drop_box(cls):\n cls.__ui_mainwindow.tableWidget_19.clear()\n\n @classmethod\n def get_question_id_to_add_to_exam(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_10.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def get_school_class_id_to_add_to_exam(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_11.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def get_question_id_to_remove_from_exam(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_12.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def get_school_class_id_to_remove_from_exam(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_13.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def add_question_id_to_current_exam(cls, question_id):\n row = 0\n col = 0\n for counter in range(10):\n if cls.__ui_mainwindow.tableWidget_3.item(row, col) == None:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_3.setItem(row, col,\n question_item)\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def add_school_class_id_to_current_exam(cls, school_class_id):\n row = 0\n col = 0\n for counter in range(10):\n if cls.__ui_mainwindow.tableWidget_4.item(row, col) == None:\n school_class_text = 'CLass ' + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_4.setItem(row, col,\n school_class_item)\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def remove_question_id_from_current_exam(cls, question_id):\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if question_item != None:\n question_text = question_item.text()\n question_text_split = question_text.split(' ')\n question_id_in_exam = int(question_text_split.pop())\n if question_id_in_exam == question_id:\n cls.__ui_mainwindow.tableWidget_3.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n\n @classmethod\n def remove_school_class_id_from_current_exam(cls, school_class_id):\n col = 0\n for row in range(5):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col\n )\n if school_class_item != None:\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(' ')\n school_class_id_in_exam = int(school_class_text_split.pop())\n if school_class_id_in_exam == school_class_id:\n cls.__ui_mainwindow.tableWidget_4.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_13.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n <mask token>\n\n @classmethod\n def is_school_class_id_already_added_to_current_exam(cls, school_class_id):\n string_of_school_classes_ids_in_current_exam = (cls.\n get_string_of_school_classes_ids_in_current_exam())\n list_of_school_classes_ids = (\n string_of_school_classes_ids_in_current_exam.split(' '))\n return list_of_school_classes_ids.count(str(school_class_id)) == 1\n\n @classmethod\n def get_string_of_question_ids_in_current_exam(cls):\n string_of_question_ids = ''\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if question_item != None:\n question_text = question_item.text()\n question_text_split = question_text.split(' ')\n question_id = question_text_split.pop()\n string_of_question_ids = (string_of_question_ids +\n question_id + ' ')\n return string_of_question_ids.rstrip()\n\n @classmethod\n def get_string_of_school_classes_ids_in_current_exam(cls):\n string_of_school_classes_ids = ''\n col = 0\n for row in range(10):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col\n )\n if school_class_item != None:\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(' ')\n school_class_id = school_class_text_split.pop()\n string_of_school_classes_ids = (\n string_of_school_classes_ids + school_class_id + ' ')\n return string_of_school_classes_ids.rstrip()\n\n @classmethod\n def get_exam_id_to_mark(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_20.item(0, 0)\n exam_text = exam_item.text()\n exam_text_split = exam_text.split(' ')\n exam_id_text = exam_text_split.pop()\n return int(exam_id_text)\n <mask token>\n\n @classmethod\n def display_students_full_names_with_questions_ready_to_be_marked(cls,\n students_names_list):\n cls.__ui_mainwindow.tableWidget_6.clear()\n row = 0\n col = 0\n for student_name in students_names_list:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_6.setItem(row, col, student_item)\n if col >= 4:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def get_student_name_to_mark_answers(cls):\n student_item = cls.__ui_mainwindow.tableWidget_19.item(0, 0)\n student_name = student_item.text()\n return student_name\n\n @classmethod\n def get_exam_id_to_mark_student_answers(cls):\n exam_id_text = cls.__ui_mainwindow.label_49.text()\n exam_id_text_split = exam_id_text.split(' ')\n exam_id = exam_id_text_split.pop()\n return int(exam_id)\n <mask token>\n\n @classmethod\n def display_student_id_on_mark_student_answers_page(cls, student_id):\n student_id_text = 'Student ID: ' + str(student_id)\n cls.__ui_mainwindow.label_63.setText(student_id_text)\n\n @classmethod\n def display_student_name_on_mark_student_answers_page(cls, student_name):\n student_name_text = 'Student Name: ' + str(student_name)\n cls.__ui_mainwindow.label_50.setText(student_name_text)\n\n @classmethod\n def display_questions_ready_to_be_marked(cls, questions_ids_tuple):\n cls.__ui_mainwindow.tableWidget_25.clear()\n row = 0\n col = 0\n for question_id, in questions_ids_tuple:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_25.setItem(row, col, question_item)\n row += 1\n <mask token>\n\n @classmethod\n def get_exam_id_on_marking_question_page(cls):\n exam_id_text = cls.__ui_mainwindow.label_62.text()\n exam_id_text_list = exam_id_text.split(' ')\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def get_student_id_on_marking_question_page(cls):\n student_id_text = cls.__ui_mainwindow.label_63.text()\n student_id_text_list = student_id_text.split(' ')\n student_id = student_id_text_list.pop()\n return int(student_id)\n <mask token>\n\n @classmethod\n def get_essay_question_marked_points(cls):\n points_text = cls.__ui_dialog.lineEdit.text()\n return int(points_text)\n\n @classmethod\n def refresh_drop_question_to_mark_box(cls):\n cls.__ui_mainwindow.tableWidget_26.clear()\n\n @classmethod\n def refresh_mark_student_questions_answers_page(cls):\n cls.__ui_mainwindow.label_62.clear()\n cls.__ui_mainwindow.label_63.clear()\n cls.__ui_mainwindow.label_50.clear()\n\n @classmethod\n def display_no_more_questions_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText('No More Questions To Mark')\n\n @classmethod\n def display_marked_exams(cls, marked_exams_ids):\n cls.__ui_mainwindow.tableWidget_18.clear()\n row = 0\n col = 0\n for exam_id, in marked_exams_ids:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_18.setItem(row, col, exam_item)\n if col >= 4:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def display_no_question_selected_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText('No Question Selected To Mark')\n\n @classmethod\n def refresh_drop_student_to_mark_questions_box(cls):\n cls.__ui_mainwindow.tableWidget_19.clear()\n\n @classmethod\n def get_exam_id_to_release_result(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_21.item(0, 0)\n if exam_item == None:\n return None\n exam_id_text = exam_item.text()\n exam_id_text_list = exam_id_text.split(' ')\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def display_result_released_exams(cls, result_released_exams_ids):\n cls.__ui_mainwindow.tableWidget_11.clear()\n row = 0\n col = 0\n for exam_id, in result_released_exams_ids:\n exam_text = 'Exam ' + str(exam_id) + ' Result'\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_11.setItem(row, col, exam_item)\n if col >= 9:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def refresh_drop_exam_to_release_result_box(cls):\n cls.__ui_mainwindow.tableWidget_21.clear()\n\n @classmethod\n def display_exam_results(cls, exam_results_ids):\n cls.__ui_mainwindow.tableWidget_11.clear()\n row = 0\n col = 0\n for exam_result_id, in exam_results_ids:\n exam_result_text = 'Exam ' + str(exam_result_id) + ' Result'\n exam_result_item = QTableWidgetItem(exam_result_text)\n cls.__ui_mainwindow.tableWidget_11.setItem(row, col,\n exam_result_item)\n if col >= 9:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def get_exam_result_id_to_load_details(cls):\n exam_result_id_text = cls.__ui_mainwindow.lineEdit_22.text()\n return int(exam_result_id_text)\n <mask token>\n\n @classmethod\n def display_exam_result_id_on_view_exam_result_details_page(cls,\n exam_result_id):\n cls.__ui_mainwindow.label_33.setText('Exam Result ID: ' + str(\n exam_result_id))\n\n @classmethod\n def get_school_class_id_to_view_exam_result(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_23.text()\n try:\n school_class_id = int(school_class_id_text)\n except:\n return None\n return school_class_id\n\n @classmethod\n def display_students_full_names_to_view_exam_result(cls,\n students_full_names):\n cls.__ui_mainwindow.tableWidget_13.clear()\n row = 0\n col = 0\n for student_full_name, in students_full_names:\n student_item = QTableWidgetItem(student_full_name)\n cls.__ui_mainwindow.tableWidget_13.setItem(row, col, student_item)\n row += 1\n <mask token>\n\n @classmethod\n def get_exam_result_id_on_view_exam_result_page(cls):\n exam_result_id_text = cls.__ui_mainwindow.label_33.text()\n exam_result_id_text_list = exam_result_id_text.split(' ')\n exam_result_id = exam_result_id_text_list.pop()\n try:\n exam_result_id_int = int(exam_result_id)\n return exam_result_id_int\n except:\n return None\n\n @classmethod\n def display_student_exam_result_details(cls, exam_result_details):\n student_id = exam_result_details[0]\n student_full_name = exam_result_details[1]\n date_of_birth = exam_result_details[2]\n school_class_id = exam_result_details[3]\n exam_id = exam_result_details[4]\n total_available_points = exam_result_details[5]\n total_points_gained = exam_result_details[6]\n average_percentage_mark = exam_result_details[7]\n cls.__ui_mainwindow.label_58.setText(str(student_id))\n cls.__ui_mainwindow.label_72.setText(str(student_full_name))\n cls.__ui_mainwindow.label_75.setText(str(date_of_birth))\n cls.__ui_mainwindow.label_76.setText(str(school_class_id))\n cls.__ui_mainwindow.label_77.setText(str(exam_id))\n cls.__ui_mainwindow.label_78.setText(str(total_available_points))\n cls.__ui_mainwindow.label_79.setText(str(total_points_gained))\n cls.__ui_mainwindow.label_80.setText(str(average_percentage_mark) +\n ' %')\n <mask token>\n <mask token>\n\n @classmethod\n def display_questions_on_view_exam_details_page(cls, questions_ids):\n cls.__ui_mainwindow.tableWidget_7.clear()\n questions_ids_list = cls.make_string_to_list(questions_ids)\n row = 0\n col = 0\n for question_id in questions_ids_list:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_7.setItem(row, col, question_item)\n row += 1\n\n @classmethod\n def display_first_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_first_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_27.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_27.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_first_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_67.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_second_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_second_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_28.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_28.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_second_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_68.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_third_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_third_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_29.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_29.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_third_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_69.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_fourth_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_fourth_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_30.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_30.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fourth_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_70.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_fifth_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_fifth_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_31.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_31.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fifth_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_71.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def make_string_to_list(cls, any_string):\n any_string = str(any_string)\n any_list = any_string.split(' ')\n return any_list\n\n @classmethod\n def refresh_drop_student_to_view_exam_result_details_box(cls):\n cls.__ui_mainwindow.tableWidget_22.clear()\n\n @classmethod\n def display_exam_result_id_invalid_message(cls):\n cls.__ui_mainwindow.label_32.setText('Exam Result ID Invalid')\n\n @classmethod\n def refresh_load_exam_result_details_page(cls):\n cls.__ui_mainwindow.label_33.clear()\n cls.__ui_mainwindow.tableWidget_12.clear()\n cls.__ui_mainwindow.lineEdit_23.clear()\n cls.__ui_mainwindow.tableWidget_13.clear()\n cls.__ui_mainwindow.tableWidget_22.clear()\n cls.__ui_mainwindow.label_58.clear()\n cls.__ui_mainwindow.label_72.clear()\n cls.__ui_mainwindow.label_75.clear()\n cls.__ui_mainwindow.label_76.clear()\n cls.__ui_mainwindow.label_77.clear()\n cls.__ui_mainwindow.label_78.clear()\n cls.__ui_mainwindow.label_79.clear()\n cls.__ui_mainwindow.label_80.clear()\n\n @classmethod\n def refresh_exam_result_id_validity_error_message(cls):\n cls.__ui_mainwindow.label_32.clear()\n\n @classmethod\n def display_school_class_id_invalid_to_view_result_message(cls):\n cls.__ui_mainwindow.label_81.setText('School Class ID Invalid To View')\n\n @classmethod\n def refresh_school_class_details_table_on_view_exam_result_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n\n @classmethod\n def refresh_school_class_id_invalid_to_view_exam_result_error_label(cls):\n cls.__ui_mainwindow.label_81.clear()\n <mask token>\n\n @classmethod\n def display_no_exam_result_id_selected_message(cls):\n cls.__ui_mainwindow.label_81.setText('No Exam Result ID Selected')\n\n @classmethod\n def refresh_school_class_id_input_box_on_view_exam_result_details_page(cls\n ):\n cls.__ui_mainwindow.lineEdit_23.clear()\n\n @classmethod\n def refresh_view_exam_details_by_id_page(cls):\n cls.__ui_mainwindow.label_18.setText('Exam ID : ')\n cls.__ui_mainwindow.tableWidget_7.clear()\n cls.__ui_mainwindow.label_67.clear()\n cls.__ui_mainwindow.label_68.clear()\n cls.__ui_mainwindow.label_69.clear()\n cls.__ui_mainwindow.label_70.clear()\n cls.__ui_mainwindow.label_71.clear()\n cls.__ui_mainwindow.tableWidget_27.clear()\n cls.__ui_mainwindow.tableWidget_28.clear()\n cls.__ui_mainwindow.tableWidget_29.clear()\n cls.__ui_mainwindow.tableWidget_30.clear()\n cls.__ui_mainwindow.tableWidget_31.clear()\n\n @classmethod\n def refresh_students_table_on_view_exam_result_details_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n <mask token>\n <mask token>\n",
"step-4": "<mask token>\n\n\nclass TeacherGUI:\n\n def __init__(self):\n pass\n\n @classmethod\n def setup(cls, ui_mainwindow):\n cls.__ui_mainwindow = ui_mainwindow\n\n @classmethod\n def display_all_active_school_classes(cls, school_classes):\n cls.__ui_mainwindow.tableWidget_14.clear()\n row = 0\n col = 0\n for school_class_id, in school_classes:\n school_class_text = 'Class ' + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_14.setItem(row, col,\n school_class_item)\n if col >= 4:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_all_exams(cls, all_exams):\n cls.__ui_mainwindow.tableWidget_5.clear()\n row = 0\n col = 0\n for exam_id, in all_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_5.setItem(row, col, exam_item)\n if col >= 9:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_not_completed_exams(cls, not_completed_exams):\n cls.__ui_mainwindow.tableWidget_16.clear()\n row = 0\n col = 0\n for exam_id, in not_completed_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_16.setItem(row, col, exam_item)\n if col >= 6:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_ready_to_be_marked_exams(cls, ready_to_be_marked_exams):\n cls.__ui_mainwindow.tableWidget_17.clear()\n row = 0\n col = 0\n for exam_id, in ready_to_be_marked_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_17.setItem(row, col, exam_item)\n if col >= 3:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_single_answer_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_SingleAnswerQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label.setText(question_body)\n cls.__ui_dialog.label_3.setText('A ' + option_A_text)\n cls.__ui_dialog.label_4.setText('B ' + option_B_text)\n cls.__ui_dialog.label_5.setText('C ' + option_C_text)\n cls.__ui_dialog.label_6.setText('D ' + option_D_text)\n cls.__ui_dialog.label_7.setText('E ' + option_E_text)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def display_multiple_answers_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_14.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_MultipleAnswersQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label.setText(question_body)\n cls.__ui_dialog.label_3.setText(option_A_text)\n cls.__ui_dialog.label_4.setText(option_B_text)\n cls.__ui_dialog.label_5.setText(option_C_text)\n cls.__ui_dialog.label_6.setText(option_D_text)\n cls.__ui_dialog.label_7.setText(option_E_text)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def display_essay_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_EssayQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n if question_body == '':\n cls.__ui_dialog.label.setText('Question Body')\n else:\n cls.__ui_dialog.label.setText(question_body)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def close_dialog(cls):\n cls.__dialog.close()\n\n @classmethod\n def get_single_answer_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit.toPlainText()\n if question_body == '':\n return None\n option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()\n if option_A_text == '':\n return None\n option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()\n if option_B_text == '':\n return None\n option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()\n if option_C_text == '':\n return None\n option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()\n if option_D_text == '':\n return None\n option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()\n if option_E_text == '':\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_3.text()\n if year_level_text == '':\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_4.text()\n if phrase_tag_text == '':\n return None\n correct_answers_list = []\n if cls.__ui_mainwindow.radioButton.isChecked():\n correct_answers_list.append('A')\n if cls.__ui_mainwindow.radioButton_2.isChecked():\n correct_answers_list.append('B')\n if cls.__ui_mainwindow.radioButton_5.isChecked():\n correct_answers_list.append('C')\n if cls.__ui_mainwindow.radioButton_3.isChecked():\n correct_answers_list.append('D')\n if cls.__ui_mainwindow.radioButton_4.isChecked():\n correct_answers_list.append('E')\n if correct_answers_list == []:\n return None\n if len(correct_answers_list) > 1:\n return None\n return (question_body, option_A_text, option_B_text, option_C_text,\n option_D_text, option_E_text, year_level, phrase_tag_text,\n correct_answers_list)\n\n @classmethod\n def get_multiple_answers_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit_14.toPlainText()\n if question_body == '':\n return None\n option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText()\n if option_A_text == '':\n return None\n option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText()\n if option_B_text == '':\n return None\n option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText()\n if option_C_text == '':\n return None\n option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText()\n if option_D_text == '':\n return None\n option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText()\n if option_E_text == '':\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_25.text()\n if year_level_text == '':\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_7.text()\n if phrase_tag_text == '':\n return None\n correct_answers_list = []\n if cls.__ui_mainwindow.checkBox.isChecked():\n correct_answers_list.append('A')\n if cls.__ui_mainwindow.checkBox_2.isChecked():\n correct_answers_list.append('B')\n if cls.__ui_mainwindow.checkBox_3.isChecked():\n correct_answers_list.append('C')\n if cls.__ui_mainwindow.checkBox_4.isChecked():\n correct_answers_list.append('D')\n if cls.__ui_mainwindow.checkBox_5.isChecked():\n correct_answers_list.append('E')\n if correct_answers_list == []:\n return None\n if len(correct_answers_list) > 4:\n return None\n return (question_body, option_A_text, option_B_text, option_C_text,\n option_D_text, option_E_text, year_level, phrase_tag_text,\n correct_answers_list)\n\n @classmethod\n def get_essay_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n if question_body == '':\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_26.text()\n if year_level_text == '':\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_27.text()\n if phrase_tag_text == '':\n return None\n return question_body, year_level, phrase_tag_text\n\n @classmethod\n def display_all_active_questions(cls, active_questions_tuple):\n row = 0\n col = 0\n for question_pk_tuple in active_questions_tuple:\n question_pk = question_pk_tuple[0]\n question_text = 'Question ' + str(question_pk)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget.setItem(row, col, question_item)\n if col >= 7:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_create_single_answer_question_success(cls):\n cls.__ui_mainwindow.label_4.setText(\n 'Create Single Answer Question Success')\n\n @classmethod\n def display_invalid_single_answer_question_creation_message(cls):\n cls.__ui_mainwindow.label_4.setText(\n 'Invalid Single Answer Question Creation')\n\n @classmethod\n def display_create_multiple_answers_question_success(cls):\n cls.__ui_mainwindow.label_11.setText(\n 'Create Multiple Answers Question Success')\n\n @classmethod\n def display_invalid_multiple_answers_question_creation_message(cls):\n cls.__ui_mainwindow.label_11.setText(\n 'Invalid Multiple Answers Question Creation')\n\n @classmethod\n def display_invalid_essay_question_creation_message(cls):\n cls.__ui_mainwindow.label_42.setText('Invalid Essay Question Creation')\n\n @classmethod\n def display_create_essay_question_success(cls):\n cls.__ui_mainwindow.label_42.setText('Create Essay Question Success')\n\n @classmethod\n def display_invalid_modification_message(cls):\n cls.__ui_mainwindow.label_57.setText('Invalid Modification')\n\n @classmethod\n def refresh_create_single_answer_question_page(cls):\n cls.__ui_mainwindow.textEdit.clear()\n cls.__ui_mainwindow.textEdit_2.clear()\n cls.__ui_mainwindow.textEdit_3.clear()\n cls.__ui_mainwindow.textEdit_4.clear()\n cls.__ui_mainwindow.textEdit_5.clear()\n cls.__ui_mainwindow.textEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_3.clear()\n cls.__ui_mainwindow.lineEdit_4.clear()\n cls.__ui_mainwindow.radioButton.setChecked(False)\n cls.__ui_mainwindow.radioButton_2.setChecked(False)\n cls.__ui_mainwindow.radioButton_3.setChecked(False)\n cls.__ui_mainwindow.radioButton_4.setChecked(False)\n cls.__ui_mainwindow.radioButton_5.setChecked(False)\n <mask token>\n\n @classmethod\n def refresh_view_or_modify_question_page(cls):\n cls.__ui_mainwindow.lineEdit_5.clear()\n cls.__ui_mainwindow.label_45.setText('Question ID: ')\n cls.__ui_mainwindow.label_47.setText('Question Type: ')\n cls.__ui_mainwindow.label_57.clear()\n cls.__ui_mainwindow.label_12.clear()\n cls.__ui_mainwindow.textEdit_7.clear()\n cls.__ui_mainwindow.textEdit_8.clear()\n cls.__ui_mainwindow.textEdit_9.clear()\n cls.__ui_mainwindow.textEdit_10.clear()\n cls.__ui_mainwindow.textEdit_11.clear()\n cls.__ui_mainwindow.textEdit_20.clear()\n cls.__ui_mainwindow.lineEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_8.clear()\n cls.__ui_mainwindow.lineEdit_28.clear()\n cls.__ui_mainwindow.radioButton_6.setDisabled(False)\n cls.__ui_mainwindow.radioButton_7.setDisabled(False)\n cls.__ui_mainwindow.radioButton_8.setDisabled(False)\n cls.__ui_mainwindow.radioButton_9.setDisabled(False)\n cls.__ui_mainwindow.radioButton_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_8.setDisabled(False)\n cls.__ui_mainwindow.textEdit_9.setDisabled(False)\n cls.__ui_mainwindow.textEdit_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_11.setDisabled(False)\n cls.__ui_mainwindow.textEdit_20.setDisabled(False)\n cls.__ui_mainwindow.radioButton_6.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_6.setChecked(False)\n cls.__ui_mainwindow.radioButton_7.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_7.setChecked(False)\n cls.__ui_mainwindow.radioButton_8.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_8.setChecked(False)\n cls.__ui_mainwindow.radioButton_9.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_9.setChecked(False)\n cls.__ui_mainwindow.radioButton_10.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_10.setChecked(False)\n\n @classmethod\n def refresh_create_essay_question_page(cls):\n cls.__ui_mainwindow.textEdit_19.clear()\n cls.__ui_mainwindow.lineEdit_26.clear()\n cls.__ui_mainwindow.lineEdit_27.clear()\n\n @classmethod\n def refresh_create_exam_page(cls):\n cls.__ui_mainwindow.tableWidget_3.clear()\n cls.__ui_mainwindow.tableWidget_4.clear()\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.lineEdit_13.clear()\n\n @classmethod\n def get_question_id_to_load(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_5.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def load_single_answer_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answer = question_details[11]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n if correct_answer == 'A':\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n elif correct_answer == 'B':\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n elif correct_answer == 'C':\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n elif correct_answer == 'D':\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n elif correct_answer == 'E':\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n @classmethod\n def load_multiple_answers_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answers = question_details[11]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n if correct_answers.count('A') == 1:\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n if correct_answers.count('B') == 1:\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n if correct_answers.count('C') == 1:\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n if correct_answers.count('D') == 1:\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n if correct_answers.count('E') == 1:\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n @classmethod\n def load_essay_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.radioButton_6.setDisabled(True)\n cls.__ui_mainwindow.radioButton_7.setDisabled(True)\n cls.__ui_mainwindow.radioButton_8.setDisabled(True)\n cls.__ui_mainwindow.radioButton_9.setDisabled(True)\n cls.__ui_mainwindow.radioButton_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_8.setDisabled(True)\n cls.__ui_mainwindow.textEdit_9.setDisabled(True)\n cls.__ui_mainwindow.textEdit_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_11.setDisabled(True)\n cls.__ui_mainwindow.textEdit_20.setDisabled(True)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n\n @classmethod\n def display_question_id_invalid_to_load_message(cls):\n cls.__ui_mainwindow.label_12.setText('Invalid Question ID To Load')\n\n @classmethod\n def display_modification_success_message(cls):\n cls.__ui_mainwindow.label_57.setText('Modification Success')\n\n @classmethod\n def display_invalid_school_class_id_message(cls):\n cls.__ui_mainwindow.label_14.setText('Invalid School Class ID')\n cls.__ui_mainwindow.tableWidget_15.clear()\n\n @classmethod\n def get_question_type_to_modify(cls):\n question_type_text = cls.__ui_mainwindow.label_47.text()\n if question_type_text == 'Question Type: Single Answer':\n return 'Single Answer'\n elif question_type_text == 'Question Type: Multiple Answers':\n return 'Multiple Answers'\n elif question_type_text == 'Question Type: Essay':\n return 'Essay'\n\n @classmethod\n def get_single_answer_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answer = cls.get_single_correct_answer_to_modify()\n if correct_answer == None:\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body, option_A_text, option_B_text,\n option_C_text, option_D_text, option_E_text, correct_answer)\n\n @classmethod\n def get_multiple_answers_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answers = cls.get_multiple_correct_answers_to_modify()\n if correct_answers == None:\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body, option_A_text, option_B_text,\n option_C_text, option_D_text, option_E_text, correct_answers)\n\n @classmethod\n def get_essay_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n try:\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n except:\n return None\n try:\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n except:\n return None\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n if question_tag == '':\n return None\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n if question_body == '':\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body)\n\n @classmethod\n def get_question_id_to_modify(cls):\n question_id_text = cls.__ui_mainwindow.label_45.text()\n question_id_text_split = question_id_text.split()\n question_id = int(question_id_text_split.pop())\n return question_id\n\n @classmethod\n def get_single_correct_answer_to_modify(cls):\n correct_answer = ''\n if cls.__ui_mainwindow.radioButton_6.isChecked():\n correct_answer = correct_answer + 'A'\n if cls.__ui_mainwindow.radioButton_7.isChecked():\n correct_answer = correct_answer + 'B'\n if cls.__ui_mainwindow.radioButton_8.isChecked():\n correct_answer = correct_answer + 'C'\n if cls.__ui_mainwindow.radioButton_9.isChecked():\n correct_answer = correct_answer + 'D'\n if cls.__ui_mainwindow.radioButton_10.isChecked():\n correct_answer = correct_answer + 'E'\n if len(correct_answer) == 0:\n return None\n if len(correct_answer) > 1:\n return None\n return correct_answer\n\n @classmethod\n def get_multiple_correct_answers_to_modify(cls):\n correct_answers = ''\n if cls.__ui_mainwindow.radioButton_6.isChecked():\n correct_answers = correct_answers + 'A'\n if cls.__ui_mainwindow.radioButton_7.isChecked():\n correct_answers = correct_answers + 'B'\n if cls.__ui_mainwindow.radioButton_8.isChecked():\n correct_answers = correct_answers + 'C'\n if cls.__ui_mainwindow.radioButton_9.isChecked():\n correct_answers = correct_answers + 'D'\n if cls.__ui_mainwindow.radioButton_10.isChecked():\n correct_answers = correct_answers + 'E'\n if len(correct_answers) == 0:\n return None\n if len(correct_answers) > 4:\n return None\n return correct_answers\n\n @classmethod\n def get_school_class_id_to_view_students(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_9.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def display_school_class_details(cls, school_class_details):\n cls.__ui_mainwindow.tableWidget_15.clear()\n row = 0\n col = 0\n for student, in school_class_details:\n student_item = QTableWidgetItem(student)\n cls.__ui_mainwindow.tableWidget_15.setItem(row, col, student_item)\n if col >= 1:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def refresh_view_school_class_details_page(cls):\n cls.__ui_mainwindow.label_14.clear()\n\n @classmethod\n def get_number_of_questions_in_current_exam(cls):\n number_of_questions = 0\n row = 0\n col = 0\n for counter in range(10):\n if cls.__ui_mainwindow.tableWidget_3.item(row, col) != None:\n number_of_questions += 1\n row += 1\n return number_of_questions\n\n @classmethod\n def get_number_of_school_classes_in_current_exam(cls):\n number_of_school_classes = 0\n row = 0\n col = 0\n for counter in range(5):\n if cls.__ui_mainwindow.tableWidget_4.item(row, col) != None:\n number_of_school_classes += 1\n row += 1\n return number_of_school_classes\n\n @classmethod\n def display_number_of_questions_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'Questions Are Full In Current Exam')\n\n @classmethod\n def display_number_of_school_classes_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Classes Are Full In Current Exam')\n\n @classmethod\n def display_no_question_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText('No Question In Current Exam')\n\n @classmethod\n def display_no_school_class_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText('No School Class In Current Exam')\n <mask token>\n\n @classmethod\n def display_school_class_id_already_added_to_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Class ID Already Added To Current Exam')\n\n @classmethod\n def display_question_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText('Question ID Invalid')\n\n @classmethod\n def display_school_class_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText('School CLass ID Invalid')\n\n @classmethod\n def display_question_id_not_already_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'Question ID Not Aleady In Current Exam')\n\n @classmethod\n def display_school_class_id_not_already_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Class ID Not Aleady In Current Exam')\n\n @classmethod\n def display_create_exam_success_message(cls):\n cls.__ui_mainwindow.label_17.setText('Create Exam Success')\n\n @classmethod\n def refresh_mark_exam_drop_box(cls):\n cls.__ui_mainwindow.tableWidget_19.clear()\n\n @classmethod\n def get_question_id_to_add_to_exam(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_10.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def get_school_class_id_to_add_to_exam(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_11.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def get_question_id_to_remove_from_exam(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_12.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def get_school_class_id_to_remove_from_exam(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_13.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def add_question_id_to_current_exam(cls, question_id):\n row = 0\n col = 0\n for counter in range(10):\n if cls.__ui_mainwindow.tableWidget_3.item(row, col) == None:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_3.setItem(row, col,\n question_item)\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def add_school_class_id_to_current_exam(cls, school_class_id):\n row = 0\n col = 0\n for counter in range(10):\n if cls.__ui_mainwindow.tableWidget_4.item(row, col) == None:\n school_class_text = 'CLass ' + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_4.setItem(row, col,\n school_class_item)\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def remove_question_id_from_current_exam(cls, question_id):\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if question_item != None:\n question_text = question_item.text()\n question_text_split = question_text.split(' ')\n question_id_in_exam = int(question_text_split.pop())\n if question_id_in_exam == question_id:\n cls.__ui_mainwindow.tableWidget_3.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n\n @classmethod\n def remove_school_class_id_from_current_exam(cls, school_class_id):\n col = 0\n for row in range(5):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col\n )\n if school_class_item != None:\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(' ')\n school_class_id_in_exam = int(school_class_text_split.pop())\n if school_class_id_in_exam == school_class_id:\n cls.__ui_mainwindow.tableWidget_4.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_13.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n <mask token>\n\n @classmethod\n def is_school_class_id_already_added_to_current_exam(cls, school_class_id):\n string_of_school_classes_ids_in_current_exam = (cls.\n get_string_of_school_classes_ids_in_current_exam())\n list_of_school_classes_ids = (\n string_of_school_classes_ids_in_current_exam.split(' '))\n return list_of_school_classes_ids.count(str(school_class_id)) == 1\n\n @classmethod\n def get_string_of_question_ids_in_current_exam(cls):\n string_of_question_ids = ''\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if question_item != None:\n question_text = question_item.text()\n question_text_split = question_text.split(' ')\n question_id = question_text_split.pop()\n string_of_question_ids = (string_of_question_ids +\n question_id + ' ')\n return string_of_question_ids.rstrip()\n\n @classmethod\n def get_string_of_school_classes_ids_in_current_exam(cls):\n string_of_school_classes_ids = ''\n col = 0\n for row in range(10):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col\n )\n if school_class_item != None:\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(' ')\n school_class_id = school_class_text_split.pop()\n string_of_school_classes_ids = (\n string_of_school_classes_ids + school_class_id + ' ')\n return string_of_school_classes_ids.rstrip()\n\n @classmethod\n def get_exam_id_to_mark(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_20.item(0, 0)\n exam_text = exam_item.text()\n exam_text_split = exam_text.split(' ')\n exam_id_text = exam_text_split.pop()\n return int(exam_id_text)\n\n @classmethod\n def display_exam_id_on_marking_exam_page(cls, exam_id):\n cls.__ui_mainwindow.label_49.setText('Exam ID: ' + str(exam_id))\n\n @classmethod\n def display_students_full_names_with_questions_ready_to_be_marked(cls,\n students_names_list):\n cls.__ui_mainwindow.tableWidget_6.clear()\n row = 0\n col = 0\n for student_name in students_names_list:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_6.setItem(row, col, student_item)\n if col >= 4:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def get_student_name_to_mark_answers(cls):\n student_item = cls.__ui_mainwindow.tableWidget_19.item(0, 0)\n student_name = student_item.text()\n return student_name\n\n @classmethod\n def get_exam_id_to_mark_student_answers(cls):\n exam_id_text = cls.__ui_mainwindow.label_49.text()\n exam_id_text_split = exam_id_text.split(' ')\n exam_id = exam_id_text_split.pop()\n return int(exam_id)\n <mask token>\n\n @classmethod\n def display_student_id_on_mark_student_answers_page(cls, student_id):\n student_id_text = 'Student ID: ' + str(student_id)\n cls.__ui_mainwindow.label_63.setText(student_id_text)\n\n @classmethod\n def display_student_name_on_mark_student_answers_page(cls, student_name):\n student_name_text = 'Student Name: ' + str(student_name)\n cls.__ui_mainwindow.label_50.setText(student_name_text)\n\n @classmethod\n def display_questions_ready_to_be_marked(cls, questions_ids_tuple):\n cls.__ui_mainwindow.tableWidget_25.clear()\n row = 0\n col = 0\n for question_id, in questions_ids_tuple:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_25.setItem(row, col, question_item)\n row += 1\n\n @classmethod\n def get_question_id_to_mark(cls):\n question_item = cls.__ui_mainwindow.tableWidget_26.item(0, 0)\n if question_item == None:\n return None\n question_id_text = question_item.text()\n question_id_text_list = question_id_text.split(' ')\n question_id = question_id_text_list.pop()\n return int(question_id)\n\n @classmethod\n def get_exam_id_on_marking_question_page(cls):\n exam_id_text = cls.__ui_mainwindow.label_62.text()\n exam_id_text_list = exam_id_text.split(' ')\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def get_student_id_on_marking_question_page(cls):\n student_id_text = cls.__ui_mainwindow.label_63.text()\n student_id_text_list = student_id_text.split(' ')\n student_id = student_id_text_list.pop()\n return int(student_id)\n\n @classmethod\n def setup_essay_question_ui_dialog_to_mark(cls, question_details):\n question_body = question_details[0]\n student_answer = question_details[1]\n available_points = question_details[2]\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_MarkingEssayQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label_2.setText(question_body)\n cls.__ui_dialog.label_3.setText(student_answer)\n cls.__ui_dialog.label_4.setText('Total Available Points: ' + str(\n available_points))\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n cls.__dialog.show()\n return cls.__ui_dialog\n\n @classmethod\n def get_essay_question_marked_points(cls):\n points_text = cls.__ui_dialog.lineEdit.text()\n return int(points_text)\n\n @classmethod\n def refresh_drop_question_to_mark_box(cls):\n cls.__ui_mainwindow.tableWidget_26.clear()\n\n @classmethod\n def refresh_mark_student_questions_answers_page(cls):\n cls.__ui_mainwindow.label_62.clear()\n cls.__ui_mainwindow.label_63.clear()\n cls.__ui_mainwindow.label_50.clear()\n\n @classmethod\n def display_no_more_questions_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText('No More Questions To Mark')\n\n @classmethod\n def display_marked_exams(cls, marked_exams_ids):\n cls.__ui_mainwindow.tableWidget_18.clear()\n row = 0\n col = 0\n for exam_id, in marked_exams_ids:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_18.setItem(row, col, exam_item)\n if col >= 4:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def display_no_question_selected_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText('No Question Selected To Mark')\n\n @classmethod\n def refresh_drop_student_to_mark_questions_box(cls):\n cls.__ui_mainwindow.tableWidget_19.clear()\n\n @classmethod\n def get_exam_id_to_release_result(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_21.item(0, 0)\n if exam_item == None:\n return None\n exam_id_text = exam_item.text()\n exam_id_text_list = exam_id_text.split(' ')\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def display_result_released_exams(cls, result_released_exams_ids):\n cls.__ui_mainwindow.tableWidget_11.clear()\n row = 0\n col = 0\n for exam_id, in result_released_exams_ids:\n exam_text = 'Exam ' + str(exam_id) + ' Result'\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_11.setItem(row, col, exam_item)\n if col >= 9:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def refresh_drop_exam_to_release_result_box(cls):\n cls.__ui_mainwindow.tableWidget_21.clear()\n\n @classmethod\n def display_exam_results(cls, exam_results_ids):\n cls.__ui_mainwindow.tableWidget_11.clear()\n row = 0\n col = 0\n for exam_result_id, in exam_results_ids:\n exam_result_text = 'Exam ' + str(exam_result_id) + ' Result'\n exam_result_item = QTableWidgetItem(exam_result_text)\n cls.__ui_mainwindow.tableWidget_11.setItem(row, col,\n exam_result_item)\n if col >= 9:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def get_exam_result_id_to_load_details(cls):\n exam_result_id_text = cls.__ui_mainwindow.lineEdit_22.text()\n return int(exam_result_id_text)\n <mask token>\n\n @classmethod\n def display_exam_result_id_on_view_exam_result_details_page(cls,\n exam_result_id):\n cls.__ui_mainwindow.label_33.setText('Exam Result ID: ' + str(\n exam_result_id))\n\n @classmethod\n def get_school_class_id_to_view_exam_result(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_23.text()\n try:\n school_class_id = int(school_class_id_text)\n except:\n return None\n return school_class_id\n\n @classmethod\n def display_students_full_names_to_view_exam_result(cls,\n students_full_names):\n cls.__ui_mainwindow.tableWidget_13.clear()\n row = 0\n col = 0\n for student_full_name, in students_full_names:\n student_item = QTableWidgetItem(student_full_name)\n cls.__ui_mainwindow.tableWidget_13.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def get_student_full_name_to_view_exam_result(cls):\n student_item = cls.__ui_mainwindow.tableWidget_22.item(0, 0)\n student_name_text = student_item.text()\n return student_name_text\n\n @classmethod\n def get_exam_result_id_on_view_exam_result_page(cls):\n exam_result_id_text = cls.__ui_mainwindow.label_33.text()\n exam_result_id_text_list = exam_result_id_text.split(' ')\n exam_result_id = exam_result_id_text_list.pop()\n try:\n exam_result_id_int = int(exam_result_id)\n return exam_result_id_int\n except:\n return None\n\n @classmethod\n def display_student_exam_result_details(cls, exam_result_details):\n student_id = exam_result_details[0]\n student_full_name = exam_result_details[1]\n date_of_birth = exam_result_details[2]\n school_class_id = exam_result_details[3]\n exam_id = exam_result_details[4]\n total_available_points = exam_result_details[5]\n total_points_gained = exam_result_details[6]\n average_percentage_mark = exam_result_details[7]\n cls.__ui_mainwindow.label_58.setText(str(student_id))\n cls.__ui_mainwindow.label_72.setText(str(student_full_name))\n cls.__ui_mainwindow.label_75.setText(str(date_of_birth))\n cls.__ui_mainwindow.label_76.setText(str(school_class_id))\n cls.__ui_mainwindow.label_77.setText(str(exam_id))\n cls.__ui_mainwindow.label_78.setText(str(total_available_points))\n cls.__ui_mainwindow.label_79.setText(str(total_points_gained))\n cls.__ui_mainwindow.label_80.setText(str(average_percentage_mark) +\n ' %')\n\n @classmethod\n def get_exam_id_to_view_details(cls):\n exam_id_text = cls.__ui_mainwindow.lineEdit_14.text()\n if exam_id_text == '':\n return None\n try:\n exam_id = int(exam_id_text)\n return exam_id\n except:\n return None\n <mask token>\n\n @classmethod\n def display_questions_on_view_exam_details_page(cls, questions_ids):\n cls.__ui_mainwindow.tableWidget_7.clear()\n questions_ids_list = cls.make_string_to_list(questions_ids)\n row = 0\n col = 0\n for question_id in questions_ids_list:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_7.setItem(row, col, question_item)\n row += 1\n\n @classmethod\n def display_first_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_first_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_27.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_27.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_first_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_67.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_second_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_second_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_28.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_28.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_second_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_68.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_third_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_third_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_29.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_29.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_third_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_69.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_fourth_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_fourth_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_30.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_30.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fourth_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_70.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_fifth_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_fifth_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_31.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_31.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fifth_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_71.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def make_string_to_list(cls, any_string):\n any_string = str(any_string)\n any_list = any_string.split(' ')\n return any_list\n\n @classmethod\n def refresh_drop_student_to_view_exam_result_details_box(cls):\n cls.__ui_mainwindow.tableWidget_22.clear()\n\n @classmethod\n def display_exam_result_id_invalid_message(cls):\n cls.__ui_mainwindow.label_32.setText('Exam Result ID Invalid')\n\n @classmethod\n def refresh_load_exam_result_details_page(cls):\n cls.__ui_mainwindow.label_33.clear()\n cls.__ui_mainwindow.tableWidget_12.clear()\n cls.__ui_mainwindow.lineEdit_23.clear()\n cls.__ui_mainwindow.tableWidget_13.clear()\n cls.__ui_mainwindow.tableWidget_22.clear()\n cls.__ui_mainwindow.label_58.clear()\n cls.__ui_mainwindow.label_72.clear()\n cls.__ui_mainwindow.label_75.clear()\n cls.__ui_mainwindow.label_76.clear()\n cls.__ui_mainwindow.label_77.clear()\n cls.__ui_mainwindow.label_78.clear()\n cls.__ui_mainwindow.label_79.clear()\n cls.__ui_mainwindow.label_80.clear()\n\n @classmethod\n def refresh_exam_result_id_validity_error_message(cls):\n cls.__ui_mainwindow.label_32.clear()\n\n @classmethod\n def display_school_class_id_invalid_to_view_result_message(cls):\n cls.__ui_mainwindow.label_81.setText('School Class ID Invalid To View')\n\n @classmethod\n def refresh_school_class_details_table_on_view_exam_result_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n\n @classmethod\n def refresh_school_class_id_invalid_to_view_exam_result_error_label(cls):\n cls.__ui_mainwindow.label_81.clear()\n\n @classmethod\n def refresh_student_exam_result_details(cls):\n cls.__ui_mainwindow.label_58.clear()\n cls.__ui_mainwindow.label_72.clear()\n cls.__ui_mainwindow.label_75.clear()\n cls.__ui_mainwindow.label_76.clear()\n cls.__ui_mainwindow.label_77.clear()\n cls.__ui_mainwindow.label_78.clear()\n cls.__ui_mainwindow.label_79.clear()\n cls.__ui_mainwindow.label_80.clear()\n\n @classmethod\n def display_no_exam_result_id_selected_message(cls):\n cls.__ui_mainwindow.label_81.setText('No Exam Result ID Selected')\n\n @classmethod\n def refresh_school_class_id_input_box_on_view_exam_result_details_page(cls\n ):\n cls.__ui_mainwindow.lineEdit_23.clear()\n\n @classmethod\n def refresh_view_exam_details_by_id_page(cls):\n cls.__ui_mainwindow.label_18.setText('Exam ID : ')\n cls.__ui_mainwindow.tableWidget_7.clear()\n cls.__ui_mainwindow.label_67.clear()\n cls.__ui_mainwindow.label_68.clear()\n cls.__ui_mainwindow.label_69.clear()\n cls.__ui_mainwindow.label_70.clear()\n cls.__ui_mainwindow.label_71.clear()\n cls.__ui_mainwindow.tableWidget_27.clear()\n cls.__ui_mainwindow.tableWidget_28.clear()\n cls.__ui_mainwindow.tableWidget_29.clear()\n cls.__ui_mainwindow.tableWidget_30.clear()\n cls.__ui_mainwindow.tableWidget_31.clear()\n\n @classmethod\n def refresh_students_table_on_view_exam_result_details_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n <mask token>\n <mask token>\n",
"step-5": "from PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QLineEdit, QRadioButton, QPushButton, QTableWidgetItem, QTableWidget, QApplication, QMainWindow, QDateEdit, QLabel, QDialog, QTextEdit, QCheckBox\nfrom PyQt5.QtCore import QDate, QTime, QDateTime, Qt\n\n\nfrom OOPCourseWorkTwo.GUI.SingleAnswerQuestionDialog import Ui_SingleAnswerQuestionDialog\nfrom OOPCourseWorkTwo.GUI.MultipleAnswersQuestionDialog import Ui_MultipleAnswersQuestionDialog\nfrom OOPCourseWorkTwo.GUI.EssayQuestionDialog import Ui_EssayQuestionDialog\nfrom OOPCourseWorkTwo.GUI.MarkingEssayQuestionDialog import Ui_MarkingEssayQuestionDialog\n\n\nclass TeacherGUI():\n\n def __init__(self):\n pass\n\n @classmethod\n def setup(cls, ui_mainwindow):\n cls.__ui_mainwindow = ui_mainwindow\n\n @classmethod\n def display_all_active_school_classes(cls, school_classes):\n cls.__ui_mainwindow.tableWidget_14.clear()\n row = 0\n col = 0\n for (school_class_id, ) in school_classes:\n school_class_text = \"Class \" + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_14.setItem(row, col, school_class_item)\n if (col >= 4):\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_all_exams(cls, all_exams):\n cls.__ui_mainwindow.tableWidget_5.clear()\n row = 0\n col = 0\n for (exam_id, ) in all_exams:\n exam_text = \"Exam \" + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_5.setItem(row, col, exam_item)\n if (col >= 9):\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_not_completed_exams(cls, not_completed_exams):\n cls.__ui_mainwindow.tableWidget_16.clear()\n row = 0\n col = 0\n for (exam_id, ) in not_completed_exams:\n exam_text = \"Exam \" + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_16.setItem(row, col, exam_item)\n if (col >= 6):\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_ready_to_be_marked_exams(cls, ready_to_be_marked_exams):\n cls.__ui_mainwindow.tableWidget_17.clear()\n row = 0\n col = 0\n for (exam_id, ) in ready_to_be_marked_exams:\n exam_text = \"Exam \" + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_17.setItem(row, col, exam_item)\n if (col >= 3):\n col = 0\n row += 1\n else:\n col += 1\n\n\n @classmethod\n def display_single_answer_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_SingleAnswerQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label.setText(question_body)\n cls.__ui_dialog.label_3.setText(\"A \" + option_A_text)\n cls.__ui_dialog.label_4.setText(\"B \" + option_B_text)\n cls.__ui_dialog.label_5.setText(\"C \" + option_C_text)\n cls.__ui_dialog.label_6.setText(\"D \" + option_D_text)\n cls.__ui_dialog.label_7.setText(\"E \" + option_E_text)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def display_multiple_answers_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_14.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_MultipleAnswersQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label.setText(question_body)\n cls.__ui_dialog.label_3.setText(option_A_text)\n cls.__ui_dialog.label_4.setText(option_B_text)\n cls.__ui_dialog.label_5.setText(option_C_text)\n cls.__ui_dialog.label_6.setText(option_D_text)\n cls.__ui_dialog.label_7.setText(option_E_text)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def display_essay_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_EssayQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n if (question_body == \"\"):\n cls.__ui_dialog.label.setText(\"Question Body\")\n else:\n cls.__ui_dialog.label.setText(question_body)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n\n @classmethod\n def close_dialog(cls):\n cls.__dialog.close()\n\n @classmethod\n def get_single_answer_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit.toPlainText()\n if (question_body == \"\"):\n return None\n option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()\n if (option_A_text == \"\"):\n return None\n option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()\n if (option_B_text == \"\"):\n return None\n option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()\n if (option_C_text == \"\"):\n return None\n option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()\n if (option_D_text == \"\"):\n return None\n option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()\n if (option_E_text == \"\"):\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_3.text()\n if (year_level_text == \"\"):\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_4.text()\n if (phrase_tag_text == \"\"):\n return None\n correct_answers_list = []\n if (cls.__ui_mainwindow.radioButton.isChecked()):\n correct_answers_list.append(\"A\")\n if (cls.__ui_mainwindow.radioButton_2.isChecked()):\n correct_answers_list.append(\"B\")\n if (cls.__ui_mainwindow.radioButton_5.isChecked()):\n correct_answers_list.append(\"C\")\n if (cls.__ui_mainwindow.radioButton_3.isChecked()):\n correct_answers_list.append(\"D\")\n if (cls.__ui_mainwindow.radioButton_4.isChecked()):\n correct_answers_list.append(\"E\")\n if (correct_answers_list == []):\n return None\n if (len(correct_answers_list) > 1):\n return None\n return (question_body, option_A_text, option_B_text, option_C_text, option_D_text, option_E_text, year_level, phrase_tag_text, correct_answers_list)\n\n @classmethod\n def get_multiple_answers_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit_14.toPlainText()\n if (question_body == \"\"):\n return None\n option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText()\n if (option_A_text == \"\"):\n return None\n option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText()\n if (option_B_text == \"\"):\n return None\n option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText()\n if (option_C_text == \"\"):\n return None\n option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText()\n if (option_D_text == \"\"):\n return None\n option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText()\n if (option_E_text == \"\"):\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_25.text()\n if (year_level_text == \"\"):\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_7.text()\n if (phrase_tag_text == \"\"):\n return None\n correct_answers_list = []\n if (cls.__ui_mainwindow.checkBox.isChecked()):\n correct_answers_list.append(\"A\")\n if (cls.__ui_mainwindow.checkBox_2.isChecked()):\n correct_answers_list.append(\"B\")\n if (cls.__ui_mainwindow.checkBox_3.isChecked()):\n correct_answers_list.append(\"C\")\n if (cls.__ui_mainwindow.checkBox_4.isChecked()):\n correct_answers_list.append(\"D\")\n if (cls.__ui_mainwindow.checkBox_5.isChecked()):\n correct_answers_list.append(\"E\")\n if (correct_answers_list == []):\n return None\n if (len(correct_answers_list) > 4):\n return None\n return (question_body, option_A_text, option_B_text, option_C_text, option_D_text, option_E_text, year_level, phrase_tag_text, correct_answers_list)\n\n @classmethod\n def get_essay_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n if (question_body == \"\"):\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_26.text()\n if (year_level_text == \"\"):\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_27.text()\n if (phrase_tag_text == \"\"):\n return None\n return (question_body, year_level, phrase_tag_text)\n\n\n @classmethod\n def display_all_active_questions(cls, active_questions_tuple):\n row = 0\n col = 0\n for question_pk_tuple in active_questions_tuple:\n question_pk = question_pk_tuple[0]\n question_text = \"Question \" + str(question_pk)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget.setItem(row, col, question_item)\n if (col >= 7):\n col = 0\n row += 1\n else:\n col += 1\n\n\n @classmethod\n def display_create_single_answer_question_success(cls):\n cls.__ui_mainwindow.label_4.setText(\"Create Single Answer Question Success\")\n\n @classmethod\n def display_invalid_single_answer_question_creation_message(cls):\n cls.__ui_mainwindow.label_4.setText(\"Invalid Single Answer Question Creation\")\n\n @classmethod\n def display_create_multiple_answers_question_success(cls):\n cls.__ui_mainwindow.label_11.setText(\"Create Multiple Answers Question Success\")\n\n @classmethod\n def display_invalid_multiple_answers_question_creation_message(cls):\n cls.__ui_mainwindow.label_11.setText(\"Invalid Multiple Answers Question Creation\")\n\n @classmethod\n def display_invalid_essay_question_creation_message(cls):\n cls.__ui_mainwindow.label_42.setText(\"Invalid Essay Question Creation\")\n\n @classmethod\n def display_create_essay_question_success(cls):\n cls.__ui_mainwindow.label_42.setText(\"Create Essay Question Success\")\n\n @classmethod\n def display_invalid_modification_message(cls):\n cls.__ui_mainwindow.label_57.setText(\"Invalid Modification\")\n\n\n @classmethod\n def refresh_create_single_answer_question_page(cls):\n cls.__ui_mainwindow.textEdit.clear()\n cls.__ui_mainwindow.textEdit_2.clear()\n cls.__ui_mainwindow.textEdit_3.clear()\n cls.__ui_mainwindow.textEdit_4.clear()\n cls.__ui_mainwindow.textEdit_5.clear()\n cls.__ui_mainwindow.textEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_3.clear()\n cls.__ui_mainwindow.lineEdit_4.clear()\n cls.__ui_mainwindow.radioButton.setChecked(False)\n cls.__ui_mainwindow.radioButton_2.setChecked(False)\n cls.__ui_mainwindow.radioButton_3.setChecked(False)\n cls.__ui_mainwindow.radioButton_4.setChecked(False)\n cls.__ui_mainwindow.radioButton_5.setChecked(False)\n\n @classmethod\n def refresh_create_multiple_answers_question_page(cls):\n cls.__ui_mainwindow.textEdit_14.clear()\n cls.__ui_mainwindow.textEdit_13.clear()\n cls.__ui_mainwindow.textEdit_15.clear()\n cls.__ui_mainwindow.textEdit_16.clear()\n cls.__ui_mainwindow.textEdit_17.clear()\n cls.__ui_mainwindow.textEdit_18.clear()\n cls.__ui_mainwindow.lineEdit_25.clear()\n cls.__ui_mainwindow.lineEdit_7.clear()\n cls.__ui_mainwindow.checkBox.setChecked(False)\n cls.__ui_mainwindow.checkBox_2.setChecked(False)\n cls.__ui_mainwindow.checkBox_3.setChecked(False)\n cls.__ui_mainwindow.checkBox_4.setChecked(False)\n cls.__ui_mainwindow.checkBox_5.setChecked(False)\n\n @classmethod\n def refresh_view_or_modify_question_page(cls):\n cls.__ui_mainwindow.lineEdit_5.clear()\n cls.__ui_mainwindow.label_45.setText(\"Question ID: \")\n cls.__ui_mainwindow.label_47.setText(\"Question Type: \")\n cls.__ui_mainwindow.label_57.clear()\n cls.__ui_mainwindow.label_12.clear()\n cls.__ui_mainwindow.textEdit_7.clear()\n cls.__ui_mainwindow.textEdit_8.clear()\n cls.__ui_mainwindow.textEdit_9.clear()\n cls.__ui_mainwindow.textEdit_10.clear()\n cls.__ui_mainwindow.textEdit_11.clear()\n cls.__ui_mainwindow.textEdit_20.clear()\n cls.__ui_mainwindow.lineEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_8.clear()\n cls.__ui_mainwindow.lineEdit_28.clear()\n cls.__ui_mainwindow.radioButton_6.setDisabled(False)\n cls.__ui_mainwindow.radioButton_7.setDisabled(False)\n cls.__ui_mainwindow.radioButton_8.setDisabled(False)\n cls.__ui_mainwindow.radioButton_9.setDisabled(False)\n cls.__ui_mainwindow.radioButton_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_8.setDisabled(False)\n cls.__ui_mainwindow.textEdit_9.setDisabled(False)\n cls.__ui_mainwindow.textEdit_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_11.setDisabled(False)\n cls.__ui_mainwindow.textEdit_20.setDisabled(False)\n cls.__ui_mainwindow.radioButton_6.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_6.setChecked(False)\n cls.__ui_mainwindow.radioButton_7.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_7.setChecked(False)\n cls.__ui_mainwindow.radioButton_8.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_8.setChecked(False)\n cls.__ui_mainwindow.radioButton_9.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_9.setChecked(False)\n cls.__ui_mainwindow.radioButton_10.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_10.setChecked(False)\n\n @classmethod\n def refresh_create_essay_question_page(cls):\n cls.__ui_mainwindow.textEdit_19.clear()\n cls.__ui_mainwindow.lineEdit_26.clear()\n cls.__ui_mainwindow.lineEdit_27.clear()\n\n @classmethod\n def refresh_create_exam_page(cls):\n cls.__ui_mainwindow.tableWidget_3.clear()\n cls.__ui_mainwindow.tableWidget_4.clear()\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.lineEdit_13.clear()\n\n @classmethod\n def get_question_id_to_load(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_5.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def load_single_answer_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answer = question_details[11]\n\n cls.__ui_mainwindow.label_45.setText(\"Question ID: \" + str(question_id))\n cls.__ui_mainwindow.label_47.setText(\"Question Type: \" + str(question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n\n if (correct_answer == \"A\"):\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n elif (correct_answer == \"B\"):\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n elif (correct_answer == \"C\"):\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n elif (correct_answer == \"D\"):\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n elif (correct_answer == \"E\"):\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n @classmethod\n def load_multiple_answers_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answers = question_details[11]\n\n cls.__ui_mainwindow.label_45.setText(\"Question ID: \" + str(question_id))\n cls.__ui_mainwindow.label_47.setText(\"Question Type: \" + str(question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n\n if (correct_answers.count(\"A\") == 1):\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n if (correct_answers.count(\"B\") == 1):\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n if (correct_answers.count(\"C\") == 1):\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n if (correct_answers.count(\"D\") == 1):\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n if (correct_answers.count(\"E\") == 1):\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n\n @classmethod\n def load_essay_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n\n cls.__ui_mainwindow.label_45.setText(\"Question ID: \" + str(question_id))\n cls.__ui_mainwindow.label_47.setText(\"Question Type: \" + str(question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.radioButton_6.setDisabled(True)\n cls.__ui_mainwindow.radioButton_7.setDisabled(True)\n cls.__ui_mainwindow.radioButton_8.setDisabled(True)\n cls.__ui_mainwindow.radioButton_9.setDisabled(True)\n cls.__ui_mainwindow.radioButton_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_8.setDisabled(True)\n cls.__ui_mainwindow.textEdit_9.setDisabled(True)\n cls.__ui_mainwindow.textEdit_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_11.setDisabled(True)\n cls.__ui_mainwindow.textEdit_20.setDisabled(True)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n\n @classmethod\n def display_question_id_invalid_to_load_message(cls):\n cls.__ui_mainwindow.label_12.setText(\"Invalid Question ID To Load\")\n\n @classmethod\n def display_modification_success_message(cls):\n cls.__ui_mainwindow.label_57.setText(\"Modification Success\")\n\n @classmethod\n def display_invalid_school_class_id_message(cls):\n cls.__ui_mainwindow.label_14.setText(\"Invalid School Class ID\")\n cls.__ui_mainwindow.tableWidget_15.clear()\n\n\n @classmethod\n def get_question_type_to_modify(cls):\n question_type_text = cls.__ui_mainwindow.label_47.text()\n if (question_type_text == \"Question Type: Single Answer\"):\n return \"Single Answer\"\n elif (question_type_text == \"Question Type: Multiple Answers\"):\n return \"Multiple Answers\"\n elif (question_type_text == \"Question Type: Essay\"):\n return \"Essay\"\n\n @classmethod\n def get_single_answer_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answer = cls.get_single_correct_answer_to_modify()\n if (correct_answer == None):\n return None\n return (question_pk, question_type, points, year_level, question_tag,question_body, option_A_text, option_B_text, option_C_text, option_D_text, option_E_text, correct_answer)\n\n @classmethod\n def get_multiple_answers_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answers = cls.get_multiple_correct_answers_to_modify()\n if (correct_answers == None):\n return None\n return (question_pk, question_type, points, year_level, question_tag,question_body, option_A_text, option_B_text, option_C_text, option_D_text, option_E_text, correct_answers)\n\n @classmethod\n def get_essay_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n try:\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n except:\n return None\n try:\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n except:\n return None\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n if (question_tag == \"\"):\n return None\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n if (question_body == \"\"):\n return None\n return (question_pk, question_type, points, year_level, question_tag, question_body)\n\n @classmethod\n def get_question_id_to_modify(cls):\n question_id_text = cls.__ui_mainwindow.label_45.text()\n question_id_text_split = question_id_text.split()\n question_id = int(question_id_text_split.pop())\n return question_id\n\n\n @classmethod\n def get_single_correct_answer_to_modify(cls):\n correct_answer = \"\"\n if (cls.__ui_mainwindow.radioButton_6.isChecked()):\n correct_answer = correct_answer + \"A\"\n if (cls.__ui_mainwindow.radioButton_7.isChecked()):\n correct_answer = correct_answer + \"B\"\n if (cls.__ui_mainwindow.radioButton_8.isChecked()):\n correct_answer = correct_answer + \"C\"\n if (cls.__ui_mainwindow.radioButton_9.isChecked()):\n correct_answer = correct_answer + \"D\"\n if (cls.__ui_mainwindow.radioButton_10.isChecked()):\n correct_answer = correct_answer + \"E\"\n if (len(correct_answer) == 0):\n return None\n if (len(correct_answer) > 1):\n return None\n return correct_answer\n\n @classmethod\n def get_multiple_correct_answers_to_modify(cls):\n correct_answers = \"\"\n if (cls.__ui_mainwindow.radioButton_6.isChecked()):\n correct_answers = correct_answers + \"A\"\n if (cls.__ui_mainwindow.radioButton_7.isChecked()):\n correct_answers = correct_answers + \"B\"\n if (cls.__ui_mainwindow.radioButton_8.isChecked()):\n correct_answers = correct_answers + \"C\"\n if (cls.__ui_mainwindow.radioButton_9.isChecked()):\n correct_answers = correct_answers + \"D\"\n if (cls.__ui_mainwindow.radioButton_10.isChecked()):\n correct_answers = correct_answers + \"E\"\n if (len(correct_answers) == 0):\n return None\n if (len(correct_answers) > 4):\n return None\n return correct_answers\n\n @classmethod\n def get_school_class_id_to_view_students(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_9.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def display_school_class_details(cls, school_class_details):\n cls.__ui_mainwindow.tableWidget_15.clear()\n row = 0\n col = 0\n for (student, ) in school_class_details:\n student_item = QTableWidgetItem(student)\n cls.__ui_mainwindow.tableWidget_15.setItem(row, col, student_item)\n if (col >= 1):\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def refresh_view_school_class_details_page(cls):\n cls.__ui_mainwindow.label_14.clear()\n\n @classmethod\n def get_number_of_questions_in_current_exam(cls):\n number_of_questions = 0\n row = 0\n col = 0\n for counter in range(10):\n if (cls.__ui_mainwindow.tableWidget_3.item(row, col) != None):\n number_of_questions += 1\n row += 1\n return number_of_questions\n\n @classmethod\n def get_number_of_school_classes_in_current_exam(cls):\n number_of_school_classes = 0\n row = 0\n col = 0\n for counter in range(5):\n if (cls.__ui_mainwindow.tableWidget_4.item(row, col) != None):\n number_of_school_classes += 1\n row += 1\n return number_of_school_classes\n\n @classmethod\n def display_number_of_questions_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"Questions Are Full In Current Exam\")\n\n @classmethod\n def display_number_of_school_classes_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"School Classes Are Full In Current Exam\")\n\n @classmethod\n def display_no_question_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"No Question In Current Exam\")\n\n @classmethod\n def display_no_school_class_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"No School Class In Current Exam\")\n\n @classmethod\n def display_question_id_already_added_to_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"Question ID Already Added To Current Exam\")\n\n @classmethod\n def display_school_class_id_already_added_to_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"School Class ID Already Added To Current Exam\")\n\n @classmethod\n def display_question_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"Question ID Invalid\")\n\n @classmethod\n def display_school_class_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"School CLass ID Invalid\")\n\n @classmethod\n def display_question_id_not_already_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"Question ID Not Aleady In Current Exam\")\n\n @classmethod\n def display_school_class_id_not_already_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"School Class ID Not Aleady In Current Exam\")\n\n @classmethod\n def display_create_exam_success_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"Create Exam Success\")\n\n @classmethod\n def refresh_mark_exam_drop_box(cls):\n cls.__ui_mainwindow.tableWidget_19.clear()\n\n\n @classmethod\n def get_question_id_to_add_to_exam(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_10.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def get_school_class_id_to_add_to_exam(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_11.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def get_question_id_to_remove_from_exam(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_12.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def get_school_class_id_to_remove_from_exam(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_13.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def add_question_id_to_current_exam(cls, question_id):\n row = 0\n col = 0\n for counter in range(10):\n if (cls.__ui_mainwindow.tableWidget_3.item(row, col) == None):\n question_text = \"Question \" + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_3.setItem(row, col, question_item)\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def add_school_class_id_to_current_exam(cls, school_class_id):\n row = 0\n col = 0\n for counter in range(10):\n if (cls.__ui_mainwindow.tableWidget_4.item(row, col) == None):\n school_class_text = \"CLass \" + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_4.setItem(row, col, school_class_item)\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def remove_question_id_from_current_exam(cls, question_id):\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if (question_item != None):\n question_text = question_item.text()\n question_text_split = question_text.split(\" \")\n question_id_in_exam = int(question_text_split.pop())\n if (question_id_in_exam == question_id):\n cls.__ui_mainwindow.tableWidget_3.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n\n @classmethod\n def remove_school_class_id_from_current_exam(cls, school_class_id):\n col = 0\n for row in range(5):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col)\n if (school_class_item != None):\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(\" \")\n school_class_id_in_exam = int(school_class_text_split.pop())\n if (school_class_id_in_exam == school_class_id):\n cls.__ui_mainwindow.tableWidget_4.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_13.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n\n @classmethod\n def is_question_id_already_added_to_current_exam(cls, question_id):\n string_of_question_ids_in_current_exam = cls.get_string_of_question_ids_in_current_exam()\n list_of_question_ids = string_of_question_ids_in_current_exam.split(\" \")\n return list_of_question_ids.count(str(question_id)) == 1\n\n @classmethod\n def is_school_class_id_already_added_to_current_exam(cls, school_class_id):\n string_of_school_classes_ids_in_current_exam = cls.get_string_of_school_classes_ids_in_current_exam()\n list_of_school_classes_ids = string_of_school_classes_ids_in_current_exam.split(\" \")\n return list_of_school_classes_ids.count(str(school_class_id)) == 1\n\n @classmethod\n def get_string_of_question_ids_in_current_exam(cls):\n string_of_question_ids = \"\"\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if (question_item != None):\n question_text = question_item.text()\n question_text_split = question_text.split(\" \")\n question_id = question_text_split.pop()\n string_of_question_ids = string_of_question_ids + question_id + \" \"\n return string_of_question_ids.rstrip()\n\n @classmethod\n def get_string_of_school_classes_ids_in_current_exam(cls):\n string_of_school_classes_ids = \"\"\n col = 0\n for row in range(10):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col)\n if (school_class_item != None):\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(\" \")\n school_class_id = school_class_text_split.pop()\n string_of_school_classes_ids = string_of_school_classes_ids + school_class_id + \" \"\n return string_of_school_classes_ids.rstrip()\n\n @classmethod\n def get_exam_id_to_mark(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_20.item(0, 0)\n exam_text = exam_item.text()\n exam_text_split = exam_text.split(\" \")\n exam_id_text = exam_text_split.pop()\n return int(exam_id_text)\n\n\n @classmethod\n def display_exam_id_on_marking_exam_page(cls, exam_id):\n cls.__ui_mainwindow.label_49.setText(\"Exam ID: \" + str(exam_id))\n\n @classmethod\n def display_students_full_names_with_questions_ready_to_be_marked(cls, students_names_list):\n cls.__ui_mainwindow.tableWidget_6.clear()\n row = 0\n col = 0\n for student_name in students_names_list:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_6.setItem(row, col, student_item)\n if (col >= 4):\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def get_student_name_to_mark_answers(cls):\n student_item = cls.__ui_mainwindow.tableWidget_19.item(0,0)\n student_name = student_item.text()\n return student_name\n\n @classmethod\n def get_exam_id_to_mark_student_answers(cls):\n exam_id_text = cls.__ui_mainwindow.label_49.text()\n exam_id_text_split = exam_id_text.split(\" \")\n exam_id = exam_id_text_split.pop()\n return int(exam_id)\n\n @classmethod\n def display_exam_id_on_mark_student_answers_page(cls, exam_id):\n exam_id_text = \"Exam ID: \" + str(exam_id)\n cls.__ui_mainwindow.label_62.setText(exam_id_text)\n\n @classmethod\n def display_student_id_on_mark_student_answers_page(cls, student_id):\n student_id_text = \"Student ID: \" + str(student_id)\n cls.__ui_mainwindow.label_63.setText(student_id_text)\n\n @classmethod\n def display_student_name_on_mark_student_answers_page(cls,student_name):\n student_name_text = \"Student Name: \" + str(student_name)\n cls.__ui_mainwindow.label_50.setText(student_name_text)\n\n @classmethod\n def display_questions_ready_to_be_marked(cls, questions_ids_tuple):\n cls.__ui_mainwindow.tableWidget_25.clear()\n row = 0\n col = 0\n for (question_id,) in questions_ids_tuple:\n question_text = \"Question \" + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_25.setItem(row, col, question_item)\n row += 1\n\n @classmethod\n def get_question_id_to_mark(cls):\n question_item = cls.__ui_mainwindow.tableWidget_26.item(0,0)\n if (question_item == None):\n return None\n question_id_text = question_item.text()\n question_id_text_list = question_id_text.split(\" \")\n question_id = question_id_text_list.pop()\n return int(question_id)\n\n @classmethod\n def get_exam_id_on_marking_question_page(cls):\n exam_id_text = cls.__ui_mainwindow.label_62.text()\n exam_id_text_list = exam_id_text.split(\" \")\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def get_student_id_on_marking_question_page(cls):\n student_id_text = cls.__ui_mainwindow.label_63.text()\n student_id_text_list = student_id_text.split(\" \")\n student_id = student_id_text_list.pop()\n return int(student_id)\n\n @classmethod\n def setup_essay_question_ui_dialog_to_mark(cls, question_details):\n question_body = question_details[0]\n student_answer = question_details[1]\n available_points = question_details[2]\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_MarkingEssayQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label_2.setText(question_body)\n cls.__ui_dialog.label_3.setText(student_answer)\n cls.__ui_dialog.label_4.setText(\"Total Available Points: \" + str(available_points))\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n cls.__dialog.show()\n return cls.__ui_dialog\n\n @classmethod\n def get_essay_question_marked_points(cls):\n points_text = cls.__ui_dialog.lineEdit.text()\n return int(points_text)\n\n @classmethod\n def refresh_drop_question_to_mark_box(cls):\n cls.__ui_mainwindow.tableWidget_26.clear()\n\n @classmethod\n def refresh_mark_student_questions_answers_page(cls):\n cls.__ui_mainwindow.label_62.clear()\n cls.__ui_mainwindow.label_63.clear()\n cls.__ui_mainwindow.label_50.clear()\n\n @classmethod\n def display_no_more_questions_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText(\"No More Questions To Mark\")\n\n @classmethod\n def display_marked_exams(cls, marked_exams_ids):\n cls.__ui_mainwindow.tableWidget_18.clear()\n row = 0\n col = 0\n for (exam_id,) in marked_exams_ids:\n exam_text = \"Exam \" + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_18.setItem(row, col, exam_item)\n if (col >= 4):\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def display_no_question_selected_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText(\"No Question Selected To Mark\")\n\n @classmethod\n def refresh_drop_student_to_mark_questions_box(cls):\n cls.__ui_mainwindow.tableWidget_19.clear()\n\n @classmethod\n def get_exam_id_to_release_result(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_21.item(0,0)\n if (exam_item == None):\n return None\n exam_id_text = exam_item.text()\n exam_id_text_list = exam_id_text.split(\" \")\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def display_result_released_exams(cls, result_released_exams_ids):\n cls.__ui_mainwindow.tableWidget_11.clear()\n row = 0\n col = 0\n for (exam_id,) in result_released_exams_ids:\n exam_text = \"Exam \" + str(exam_id) + \" Result\"\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_11.setItem(row, col, exam_item)\n if (col >= 9):\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def refresh_drop_exam_to_release_result_box(cls):\n cls.__ui_mainwindow.tableWidget_21.clear()\n\n @classmethod\n def display_exam_results(cls, exam_results_ids):\n cls.__ui_mainwindow.tableWidget_11.clear()\n row = 0\n col = 0\n for (exam_result_id, ) in exam_results_ids:\n exam_result_text = \"Exam \" + str(exam_result_id) + \" Result\"\n exam_result_item = QTableWidgetItem(exam_result_text)\n cls.__ui_mainwindow.tableWidget_11.setItem(row, col, exam_result_item)\n if (col >= 9):\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def get_exam_result_id_to_load_details(cls):\n exam_result_id_text = cls.__ui_mainwindow.lineEdit_22.text()\n return int(exam_result_id_text)\n\n @classmethod\n def display_school_classes_to_view_exam_result_details(cls, school_classes_ids):\n school_classes_ids_list = cls.make_string_to_list(school_classes_ids)\n cls.__ui_mainwindow.tableWidget_12.clear()\n row = 0\n col = 0\n for school_class_id in school_classes_ids_list:\n school_class_text = \"Class \" + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_12.setItem(row, col, school_class_item)\n row += 1\n\n @classmethod\n def display_exam_result_id_on_view_exam_result_details_page(cls, exam_result_id):\n cls.__ui_mainwindow.label_33.setText(\"Exam Result ID: \" + str(exam_result_id))\n\n @classmethod\n def get_school_class_id_to_view_exam_result(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_23.text()\n try:\n school_class_id = int(school_class_id_text)\n except:\n return None\n return school_class_id\n\n @classmethod\n def display_students_full_names_to_view_exam_result(cls, students_full_names):\n cls.__ui_mainwindow.tableWidget_13.clear()\n row = 0\n col = 0\n for (student_full_name, ) in students_full_names:\n student_item = QTableWidgetItem(student_full_name)\n cls.__ui_mainwindow.tableWidget_13.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def get_student_full_name_to_view_exam_result(cls):\n student_item = cls.__ui_mainwindow.tableWidget_22.item(0, 0)\n student_name_text = student_item.text()\n return student_name_text\n\n @classmethod\n def get_exam_result_id_on_view_exam_result_page(cls):\n exam_result_id_text = cls.__ui_mainwindow.label_33.text()\n exam_result_id_text_list = exam_result_id_text.split(\" \")\n exam_result_id = exam_result_id_text_list.pop()\n try:\n exam_result_id_int = int(exam_result_id)\n return exam_result_id_int\n except:\n return None\n\n @classmethod\n def display_student_exam_result_details(cls, exam_result_details):\n student_id = exam_result_details[0]\n student_full_name = exam_result_details[1]\n date_of_birth = exam_result_details[2]\n school_class_id = exam_result_details[3]\n exam_id = exam_result_details[4]\n total_available_points = exam_result_details[5]\n total_points_gained = exam_result_details[6]\n average_percentage_mark = exam_result_details[7]\n cls.__ui_mainwindow.label_58.setText(str(student_id))\n cls.__ui_mainwindow.label_72.setText(str(student_full_name))\n cls.__ui_mainwindow.label_75.setText(str(date_of_birth))\n cls.__ui_mainwindow.label_76.setText(str(school_class_id))\n cls.__ui_mainwindow.label_77.setText(str(exam_id))\n cls.__ui_mainwindow.label_78.setText(str(total_available_points))\n cls.__ui_mainwindow.label_79.setText(str(total_points_gained))\n cls.__ui_mainwindow.label_80.setText(str(average_percentage_mark) + \" %\")\n\n @classmethod\n def get_exam_id_to_view_details(cls):\n exam_id_text = cls.__ui_mainwindow.lineEdit_14.text()\n if (exam_id_text == \"\"):\n return None\n try:\n exam_id = int(exam_id_text)\n return exam_id\n except:\n return None\n\n @classmethod\n def diaplay_exam_id_on_view_exam_details_page(cls, exam_id):\n cls.__ui_mainwindow.label_18.setText(\"Exam ID: \" + str(exam_id))\n\n @classmethod\n def display_questions_on_view_exam_details_page(cls, questions_ids):\n cls.__ui_mainwindow.tableWidget_7.clear()\n questions_ids_list = cls.make_string_to_list(questions_ids)\n row = 0\n col = 0\n for question_id in questions_ids_list:\n question_text = \"Question \" + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_7.setItem(row, col, question_item)\n row += 1\n\n @classmethod\n def display_first_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names):\n cls.display_first_school_class_id_on_view_exam_details_page(school_class_id)\n cls.__ui_mainwindow.tableWidget_27.clear()\n row = 0\n col = 0\n for (student_name, ) in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_27.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_first_school_class_id_on_view_exam_details_page(cls, school_class_id):\n cls.__ui_mainwindow.label_67.setText(\"CLass \" + str(school_class_id))\n\n @classmethod\n def display_second_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names):\n cls.display_second_school_class_id_on_view_exam_details_page(school_class_id)\n cls.__ui_mainwindow.tableWidget_28.clear()\n row = 0\n col = 0\n for (student_name, ) in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_28.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_second_school_class_id_on_view_exam_details_page(cls, school_class_id):\n cls.__ui_mainwindow.label_68.setText(\"CLass \" + str(school_class_id))\n\n @classmethod\n def display_third_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names):\n cls.display_third_school_class_id_on_view_exam_details_page(school_class_id)\n cls.__ui_mainwindow.tableWidget_29.clear()\n row = 0\n col = 0\n for (student_name, ) in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_29.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_third_school_class_id_on_view_exam_details_page(cls, school_class_id):\n cls.__ui_mainwindow.label_69.setText(\"CLass \" + str(school_class_id))\n\n @classmethod\n def display_fourth_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names):\n cls.display_fourth_school_class_id_on_view_exam_details_page(school_class_id)\n cls.__ui_mainwindow.tableWidget_30.clear()\n row = 0\n col = 0\n for (student_name, ) in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_30.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fourth_school_class_id_on_view_exam_details_page(cls, school_class_id):\n cls.__ui_mainwindow.label_70.setText(\"CLass \" + str(school_class_id))\n\n @classmethod\n def display_fifth_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names):\n cls.display_fifth_school_class_id_on_view_exam_details_page(school_class_id)\n cls.__ui_mainwindow.tableWidget_31.clear()\n row = 0\n col = 0\n for (student_name, ) in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_31.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fifth_school_class_id_on_view_exam_details_page(cls, school_class_id):\n cls.__ui_mainwindow.label_71.setText(\"CLass \" + str(school_class_id))\n\n @classmethod\n def make_string_to_list(cls, any_string):\n any_string = str(any_string)\n any_list = any_string.split(\" \")\n return any_list\n\n @classmethod\n def refresh_drop_student_to_view_exam_result_details_box(cls):\n cls.__ui_mainwindow.tableWidget_22.clear()\n\n @classmethod\n def display_exam_result_id_invalid_message(cls):\n cls.__ui_mainwindow.label_32.setText(\"Exam Result ID Invalid\")\n\n @classmethod\n def refresh_load_exam_result_details_page(cls):\n cls.__ui_mainwindow.label_33.clear()\n cls.__ui_mainwindow.tableWidget_12.clear()\n cls.__ui_mainwindow.lineEdit_23.clear()\n cls.__ui_mainwindow.tableWidget_13.clear()\n cls.__ui_mainwindow.tableWidget_22.clear()\n cls.__ui_mainwindow.label_58.clear()\n cls.__ui_mainwindow.label_72.clear()\n cls.__ui_mainwindow.label_75.clear()\n cls.__ui_mainwindow.label_76.clear()\n cls.__ui_mainwindow.label_77.clear()\n cls.__ui_mainwindow.label_78.clear()\n cls.__ui_mainwindow.label_79.clear()\n cls.__ui_mainwindow.label_80.clear()\n\n @classmethod\n def refresh_exam_result_id_validity_error_message(cls):\n cls.__ui_mainwindow.label_32.clear()\n\n @classmethod\n def display_school_class_id_invalid_to_view_result_message(cls):\n cls.__ui_mainwindow.label_81.setText(\"School Class ID Invalid To View\")\n\n @classmethod\n def refresh_school_class_details_table_on_view_exam_result_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n\n @classmethod\n def refresh_school_class_id_invalid_to_view_exam_result_error_label(cls):\n cls.__ui_mainwindow.label_81.clear()\n\n @classmethod\n def refresh_student_exam_result_details(cls):\n cls.__ui_mainwindow.label_58.clear()\n cls.__ui_mainwindow.label_72.clear()\n cls.__ui_mainwindow.label_75.clear()\n cls.__ui_mainwindow.label_76.clear()\n cls.__ui_mainwindow.label_77.clear()\n cls.__ui_mainwindow.label_78.clear()\n cls.__ui_mainwindow.label_79.clear()\n cls.__ui_mainwindow.label_80.clear()\n\n @classmethod\n def display_no_exam_result_id_selected_message(cls):\n cls.__ui_mainwindow.label_81.setText(\"No Exam Result ID Selected\")\n\n @classmethod\n def refresh_school_class_id_input_box_on_view_exam_result_details_page(cls):\n cls.__ui_mainwindow.lineEdit_23.clear()\n\n @classmethod\n def refresh_view_exam_details_by_id_page(cls):\n cls.__ui_mainwindow.label_18.setText(\"Exam ID : \")\n cls.__ui_mainwindow.tableWidget_7.clear()\n cls.__ui_mainwindow.label_67.clear()\n cls.__ui_mainwindow.label_68.clear()\n cls.__ui_mainwindow.label_69.clear()\n cls.__ui_mainwindow.label_70.clear()\n cls.__ui_mainwindow.label_71.clear()\n cls.__ui_mainwindow.tableWidget_27.clear()\n cls.__ui_mainwindow.tableWidget_28.clear()\n cls.__ui_mainwindow.tableWidget_29.clear()\n cls.__ui_mainwindow.tableWidget_30.clear()\n cls.__ui_mainwindow.tableWidget_31.clear()\n\n @classmethod\n def refresh_students_table_on_view_exam_result_details_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n\n @classmethod\n def refresh_school_classes_table_on_view_exam_result_details_page(cls):\n cls.__ui_mainwindow.tableWidget_12.clear()\n\n\n\n\n\n def __str__(self):\n return (\"This is TeacherGUI Object\")",
"step-ids": [
100,
103,
113,
122,
132
]
}
|
[
100,
103,
113,
122,
132
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
urlpatterns = [path('signup/', views.signup, name='signup'), path('home',
views.home, name='home'), path('collab/', views.collab, name='collab')]
<|reserved_special_token_1|>
from django.urls import path
from django.conf.urls.i18n import urlpatterns
from . import views
urlpatterns = [path('signup/', views.signup, name='signup'), path('home',
views.home, name='home'), path('collab/', views.collab, name='collab')]
<|reserved_special_token_1|>
from django.urls import path
from django.conf.urls.i18n import urlpatterns
from . import views
urlpatterns = [
path('signup/', views.signup, name='signup'),
path('home', views.home, name='home'),
path('collab/', views.collab, name='collab'),
]
|
flexible
|
{
"blob_id": "351963bee76ecaa9fa5c8d659f6d7c6ca9b22531",
"index": 2182,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nurlpatterns = [path('signup/', views.signup, name='signup'), path('home',\n views.home, name='home'), path('collab/', views.collab, name='collab')]\n",
"step-3": "from django.urls import path\nfrom django.conf.urls.i18n import urlpatterns\nfrom . import views\nurlpatterns = [path('signup/', views.signup, name='signup'), path('home',\n views.home, name='home'), path('collab/', views.collab, name='collab')]\n",
"step-4": "from django.urls import path\nfrom django.conf.urls.i18n import urlpatterns\n\nfrom . import views\n\nurlpatterns = [\n path('signup/', views.signup, name='signup'),\n path('home', views.home, name='home'),\n path('collab/', views.collab, name='collab'),\n]",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
def main():
s1 = 'mabaabm'
s2 = 'moktko!'
s3 = ex7(s1, s2)
print(s3)
def ex7(in1, in2):
out1 = in1[0] + in1[int(len(in1) / 2)] + in1[int(len(in1) - 1)] + in2[0
] + in2[int(len(in2) / 2)] + in2[int(len(in2) - 1)]
return out1
if __name__ == '__main__':
main()
|
normal
|
{
"blob_id": "f45cae397aa3b7bdba6e3f36e20b926487cb160d",
"index": 9238,
"step-1": "<mask token>\n",
"step-2": "def main():\n s1 = 'mabaabm'\n s2 = 'moktko!'\n s3 = ex7(s1, s2)\n print(s3)\n\n\n<mask token>\n",
"step-3": "def main():\n s1 = 'mabaabm'\n s2 = 'moktko!'\n s3 = ex7(s1, s2)\n print(s3)\n\n\ndef ex7(in1, in2):\n out1 = in1[0] + in1[int(len(in1) / 2)] + in1[int(len(in1) - 1)] + in2[0\n ] + in2[int(len(in2) / 2)] + in2[int(len(in2) - 1)]\n return out1\n\n\n<mask token>\n",
"step-4": "def main():\n s1 = 'mabaabm'\n s2 = 'moktko!'\n s3 = ex7(s1, s2)\n print(s3)\n\n\ndef ex7(in1, in2):\n out1 = in1[0] + in1[int(len(in1) / 2)] + in1[int(len(in1) - 1)] + in2[0\n ] + in2[int(len(in2) / 2)] + in2[int(len(in2) - 1)]\n return out1\n\n\nif __name__ == '__main__':\n main()\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
import requests
import re
import time
import os
import argparse
import json
url = "https://contactform7.com/captcha/"
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.1 Safari/605.1.15',
'Content-Type': "multipart/form-data; boundary=----WebKitFormBoundaryQgctpYC5kRiIjznW","Connection": "keep-alive",
"Cookie": "lang = en_US;_ga = GA1.2.765999315.1562601614;_gid = GA1.2.1701684676.1562913704;__cfduid = d695b369369d5130db03260060ed2edec1562601611"
}
ap=argparse.ArgumentParser()
ap.add_argument("-o","--output",required=True,help="Path to save the images")
ap.add_argument("-n","--number",required=False,default=500,help="number of images to download")
args=vars(ap.parse_args())
s=requests.Session()
result = s.get(url, headers=headers).content.decode("UTF-8")
count =1
result = re.findall("src=\"(.*[0-9]{1,}\.png)\"", result)
for j in result:
print("\033[095m Downloading image \033[00m : \033[092m {}/{} \033[00m ".format(count, args["number"]))
print(j.encode("ascii"))
r = s.get(j.encode("ascii"), headers=headers)
p = os.path.sep.join([args["output"], "{}.jpg".format(str(count).zfill(5))])
f = open(p, "wb")
f.write(r.content)
f.close()
time.sleep(0.1)
count += 1
url = "https://contactform7.com/wp-json/contact-form-7/v1/contact-forms/1209/feedback"
images=["captcha-118","captcha-170","captcha-778"]
while count<args["number"]:
try:
s = requests.Session()
result = json.loads(s.post(url, headers=headers).content.decode("UTF-8"))
#print(result["captcha"])
#print(result["captcha"][u'captcha-118'].encode("ascii"))
for j in range(3):
print("\033[095m Downloading image \033[00m : \033[092m {}/{} \033[00m ".format(count,args["number"]))
# print(j.encode("ascii"))
r = s.get(result["captcha"][images[j]].encode("ascii"), headers=headers)
p= os.path.sep.join([args["output"],"{}.jpg".format(str(count).zfill(5))])
f=open(p,"wb")
f.write(r.content)
f.close()
time.sleep(0.1)
count+=1
except Exception:
print("\033[92m Error Downloading Webpage \033[00m")
time.sleep(1)
|
normal
|
{
"blob_id": "6990b5f34af654b4e1a39c3d73b6822fa48e4835",
"index": 9159,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nap.add_argument('-o', '--output', required=True, help='Path to save the images'\n )\nap.add_argument('-n', '--number', required=False, default=500, help=\n 'number of images to download')\n<mask token>\nfor j in result:\n print('\\x1b[095m Downloading image \\x1b[00m : \\x1b[092m {}/{} \\x1b[00m '\n .format(count, args['number']))\n print(j.encode('ascii'))\n r = s.get(j.encode('ascii'), headers=headers)\n p = os.path.sep.join([args['output'], '{}.jpg'.format(str(count).zfill(5))]\n )\n f = open(p, 'wb')\n f.write(r.content)\n f.close()\n time.sleep(0.1)\n count += 1\n<mask token>\nwhile count < args['number']:\n try:\n s = requests.Session()\n result = json.loads(s.post(url, headers=headers).content.decode(\n 'UTF-8'))\n for j in range(3):\n print(\n '\\x1b[095m Downloading image \\x1b[00m : \\x1b[092m {}/{} \\x1b[00m '\n .format(count, args['number']))\n r = s.get(result['captcha'][images[j]].encode('ascii'), headers\n =headers)\n p = os.path.sep.join([args['output'], '{}.jpg'.format(str(count\n ).zfill(5))])\n f = open(p, 'wb')\n f.write(r.content)\n f.close()\n time.sleep(0.1)\n count += 1\n except Exception:\n print('\\x1b[92m Error Downloading Webpage \\x1b[00m')\n time.sleep(1)\n",
"step-3": "<mask token>\nurl = 'https://contactform7.com/captcha/'\nheaders = {'User-Agent':\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.1 Safari/605.1.15'\n , 'Content-Type':\n 'multipart/form-data; boundary=----WebKitFormBoundaryQgctpYC5kRiIjznW',\n 'Connection': 'keep-alive', 'Cookie':\n 'lang = en_US;_ga = GA1.2.765999315.1562601614;_gid = GA1.2.1701684676.1562913704;__cfduid = d695b369369d5130db03260060ed2edec1562601611'\n }\nap = argparse.ArgumentParser()\nap.add_argument('-o', '--output', required=True, help='Path to save the images'\n )\nap.add_argument('-n', '--number', required=False, default=500, help=\n 'number of images to download')\nargs = vars(ap.parse_args())\ns = requests.Session()\nresult = s.get(url, headers=headers).content.decode('UTF-8')\ncount = 1\nresult = re.findall('src=\"(.*[0-9]{1,}\\\\.png)\"', result)\nfor j in result:\n print('\\x1b[095m Downloading image \\x1b[00m : \\x1b[092m {}/{} \\x1b[00m '\n .format(count, args['number']))\n print(j.encode('ascii'))\n r = s.get(j.encode('ascii'), headers=headers)\n p = os.path.sep.join([args['output'], '{}.jpg'.format(str(count).zfill(5))]\n )\n f = open(p, 'wb')\n f.write(r.content)\n f.close()\n time.sleep(0.1)\n count += 1\nurl = (\n 'https://contactform7.com/wp-json/contact-form-7/v1/contact-forms/1209/feedback'\n )\nimages = ['captcha-118', 'captcha-170', 'captcha-778']\nwhile count < args['number']:\n try:\n s = requests.Session()\n result = json.loads(s.post(url, headers=headers).content.decode(\n 'UTF-8'))\n for j in range(3):\n print(\n '\\x1b[095m Downloading image \\x1b[00m : \\x1b[092m {}/{} \\x1b[00m '\n .format(count, args['number']))\n r = s.get(result['captcha'][images[j]].encode('ascii'), headers\n =headers)\n p = os.path.sep.join([args['output'], '{}.jpg'.format(str(count\n ).zfill(5))])\n f = open(p, 'wb')\n f.write(r.content)\n f.close()\n time.sleep(0.1)\n count += 1\n except Exception:\n print('\\x1b[92m Error Downloading Webpage \\x1b[00m')\n time.sleep(1)\n",
"step-4": "import requests\nimport re\nimport time\nimport os\nimport argparse\nimport json\nurl = 'https://contactform7.com/captcha/'\nheaders = {'User-Agent':\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.1 Safari/605.1.15'\n , 'Content-Type':\n 'multipart/form-data; boundary=----WebKitFormBoundaryQgctpYC5kRiIjznW',\n 'Connection': 'keep-alive', 'Cookie':\n 'lang = en_US;_ga = GA1.2.765999315.1562601614;_gid = GA1.2.1701684676.1562913704;__cfduid = d695b369369d5130db03260060ed2edec1562601611'\n }\nap = argparse.ArgumentParser()\nap.add_argument('-o', '--output', required=True, help='Path to save the images'\n )\nap.add_argument('-n', '--number', required=False, default=500, help=\n 'number of images to download')\nargs = vars(ap.parse_args())\ns = requests.Session()\nresult = s.get(url, headers=headers).content.decode('UTF-8')\ncount = 1\nresult = re.findall('src=\"(.*[0-9]{1,}\\\\.png)\"', result)\nfor j in result:\n print('\\x1b[095m Downloading image \\x1b[00m : \\x1b[092m {}/{} \\x1b[00m '\n .format(count, args['number']))\n print(j.encode('ascii'))\n r = s.get(j.encode('ascii'), headers=headers)\n p = os.path.sep.join([args['output'], '{}.jpg'.format(str(count).zfill(5))]\n )\n f = open(p, 'wb')\n f.write(r.content)\n f.close()\n time.sleep(0.1)\n count += 1\nurl = (\n 'https://contactform7.com/wp-json/contact-form-7/v1/contact-forms/1209/feedback'\n )\nimages = ['captcha-118', 'captcha-170', 'captcha-778']\nwhile count < args['number']:\n try:\n s = requests.Session()\n result = json.loads(s.post(url, headers=headers).content.decode(\n 'UTF-8'))\n for j in range(3):\n print(\n '\\x1b[095m Downloading image \\x1b[00m : \\x1b[092m {}/{} \\x1b[00m '\n .format(count, args['number']))\n r = s.get(result['captcha'][images[j]].encode('ascii'), headers\n =headers)\n p = os.path.sep.join([args['output'], '{}.jpg'.format(str(count\n ).zfill(5))])\n f = open(p, 'wb')\n f.write(r.content)\n f.close()\n time.sleep(0.1)\n count += 1\n except Exception:\n print('\\x1b[92m Error Downloading Webpage \\x1b[00m')\n time.sleep(1)\n",
"step-5": "import requests\nimport re\nimport time\nimport os\nimport argparse\nimport json\n\nurl = \"https://contactform7.com/captcha/\"\nheaders = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.1 Safari/605.1.15',\n 'Content-Type': \"multipart/form-data; boundary=----WebKitFormBoundaryQgctpYC5kRiIjznW\",\"Connection\": \"keep-alive\",\n \"Cookie\": \"lang = en_US;_ga = GA1.2.765999315.1562601614;_gid = GA1.2.1701684676.1562913704;__cfduid = d695b369369d5130db03260060ed2edec1562601611\"\n}\n\nap=argparse.ArgumentParser()\nap.add_argument(\"-o\",\"--output\",required=True,help=\"Path to save the images\")\nap.add_argument(\"-n\",\"--number\",required=False,default=500,help=\"number of images to download\")\nargs=vars(ap.parse_args())\ns=requests.Session()\nresult = s.get(url, headers=headers).content.decode(\"UTF-8\")\n\ncount =1\nresult = re.findall(\"src=\\\"(.*[0-9]{1,}\\.png)\\\"\", result)\nfor j in result:\n print(\"\\033[095m Downloading image \\033[00m : \\033[092m {}/{} \\033[00m \".format(count, args[\"number\"]))\n print(j.encode(\"ascii\"))\n r = s.get(j.encode(\"ascii\"), headers=headers)\n p = os.path.sep.join([args[\"output\"], \"{}.jpg\".format(str(count).zfill(5))])\n f = open(p, \"wb\")\n f.write(r.content)\n f.close()\n time.sleep(0.1)\n count += 1\n\nurl = \"https://contactform7.com/wp-json/contact-form-7/v1/contact-forms/1209/feedback\"\nimages=[\"captcha-118\",\"captcha-170\",\"captcha-778\"]\nwhile count<args[\"number\"]:\n try:\n s = requests.Session()\n result = json.loads(s.post(url, headers=headers).content.decode(\"UTF-8\"))\n #print(result[\"captcha\"])\n #print(result[\"captcha\"][u'captcha-118'].encode(\"ascii\"))\n\n for j in range(3):\n print(\"\\033[095m Downloading image \\033[00m : \\033[092m {}/{} \\033[00m \".format(count,args[\"number\"]))\n # print(j.encode(\"ascii\"))\n r = s.get(result[\"captcha\"][images[j]].encode(\"ascii\"), headers=headers)\n p= os.path.sep.join([args[\"output\"],\"{}.jpg\".format(str(count).zfill(5))])\n f=open(p,\"wb\")\n f.write(r.content)\n f.close()\n time.sleep(0.1)\n count+=1\n\n except Exception:\n print(\"\\033[92m Error Downloading Webpage \\033[00m\")\n time.sleep(1)\n\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
def resultados(request, total):
latest_question_list = Pregunta.objects.order_by('fecha')[:total]
output = ', '.join([q.descripcion for q in latest_question_list])
return HttpResponse(output)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def detalle(request, id_pregunta):
pregunta = Pregunta.objects.get(id=id_pregunta)
template = loader.get_template('polls/detalle.html')
context = {'pregunta': pregunta}
return HttpResponse(template.render(context, request))
def resultados(request, total):
latest_question_list = Pregunta.objects.order_by('fecha')[:total]
output = ', '.join([q.descripcion for q in latest_question_list])
return HttpResponse(output)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def index(request):
preguntas = Pregunta.objects.order_by('-fecha')[:5]
template = loader.get_template('polls/index.html')
context = {'listado': preguntas}
return HttpResponse(template.render(context, request))
def detalle(request, id_pregunta):
pregunta = Pregunta.objects.get(id=id_pregunta)
template = loader.get_template('polls/detalle.html')
context = {'pregunta': pregunta}
return HttpResponse(template.render(context, request))
def resultados(request, total):
latest_question_list = Pregunta.objects.order_by('fecha')[:total]
output = ', '.join([q.descripcion for q in latest_question_list])
return HttpResponse(output)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
from django.http import HttpResponse
from polls.models import Pregunta
from django.template import loader
def index(request):
preguntas = Pregunta.objects.order_by('-fecha')[:5]
template = loader.get_template('polls/index.html')
context = {'listado': preguntas}
return HttpResponse(template.render(context, request))
def detalle(request, id_pregunta):
pregunta = Pregunta.objects.get(id=id_pregunta)
template = loader.get_template('polls/detalle.html')
context = {'pregunta': pregunta}
return HttpResponse(template.render(context, request))
def resultados(request, total):
latest_question_list = Pregunta.objects.order_by('fecha')[:total]
output = ', '.join([q.descripcion for q in latest_question_list])
return HttpResponse(output)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
from django.http import HttpResponse
from polls.models import Pregunta
from django.template import loader
def index(request):
preguntas = Pregunta.objects.order_by('-fecha')[:5]
template = loader.get_template('polls/index.html')
context = { 'listado': preguntas,}
return HttpResponse(template.render(context, request))
def detalle(request, id_pregunta):
pregunta = Pregunta.objects.get(id=id_pregunta)
template = loader.get_template('polls/detalle.html')
context = { 'pregunta': pregunta }
return HttpResponse(template.render(context, request))
def resultados(request, total):
latest_question_list = Pregunta.objects.order_by('fecha')[:total]
output = ', '.join([q.descripcion for q in latest_question_list])
return HttpResponse(output)
"""
-Construir una vista que retorne todas las opciones asociadas a una pregunta
*FILTRAR POR ID DE PREGUNTA
"""
|
flexible
|
{
"blob_id": "07dc058ecef323ffd41299245e4fcafdc9e41506",
"index": 2131,
"step-1": "<mask token>\n\n\ndef resultados(request, total):\n latest_question_list = Pregunta.objects.order_by('fecha')[:total]\n output = ', '.join([q.descripcion for q in latest_question_list])\n return HttpResponse(output)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef detalle(request, id_pregunta):\n pregunta = Pregunta.objects.get(id=id_pregunta)\n template = loader.get_template('polls/detalle.html')\n context = {'pregunta': pregunta}\n return HttpResponse(template.render(context, request))\n\n\ndef resultados(request, total):\n latest_question_list = Pregunta.objects.order_by('fecha')[:total]\n output = ', '.join([q.descripcion for q in latest_question_list])\n return HttpResponse(output)\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef index(request):\n preguntas = Pregunta.objects.order_by('-fecha')[:5]\n template = loader.get_template('polls/index.html')\n context = {'listado': preguntas}\n return HttpResponse(template.render(context, request))\n\n\ndef detalle(request, id_pregunta):\n pregunta = Pregunta.objects.get(id=id_pregunta)\n template = loader.get_template('polls/detalle.html')\n context = {'pregunta': pregunta}\n return HttpResponse(template.render(context, request))\n\n\ndef resultados(request, total):\n latest_question_list = Pregunta.objects.order_by('fecha')[:total]\n output = ', '.join([q.descripcion for q in latest_question_list])\n return HttpResponse(output)\n\n\n<mask token>\n",
"step-4": "from django.http import HttpResponse\nfrom polls.models import Pregunta\nfrom django.template import loader\n\n\ndef index(request):\n preguntas = Pregunta.objects.order_by('-fecha')[:5]\n template = loader.get_template('polls/index.html')\n context = {'listado': preguntas}\n return HttpResponse(template.render(context, request))\n\n\ndef detalle(request, id_pregunta):\n pregunta = Pregunta.objects.get(id=id_pregunta)\n template = loader.get_template('polls/detalle.html')\n context = {'pregunta': pregunta}\n return HttpResponse(template.render(context, request))\n\n\ndef resultados(request, total):\n latest_question_list = Pregunta.objects.order_by('fecha')[:total]\n output = ', '.join([q.descripcion for q in latest_question_list])\n return HttpResponse(output)\n\n\n<mask token>\n",
"step-5": "from django.http import HttpResponse\r\n\r\nfrom polls.models import Pregunta\r\n\r\nfrom django.template import loader\r\n\r\n\r\ndef index(request):\r\n\tpreguntas = Pregunta.objects.order_by('-fecha')[:5]\r\n\ttemplate = loader.get_template('polls/index.html')\r\n\tcontext = { 'listado': preguntas,}\r\n\treturn HttpResponse(template.render(context, request))\r\n\r\ndef detalle(request, id_pregunta):\r\n\tpregunta = Pregunta.objects.get(id=id_pregunta)\r\n\ttemplate = loader.get_template('polls/detalle.html')\r\n\tcontext = { 'pregunta': pregunta }\r\n\treturn HttpResponse(template.render(context, request))\r\n\r\ndef resultados(request, total):\r\n latest_question_list = Pregunta.objects.order_by('fecha')[:total]\r\n output = ', '.join([q.descripcion for q in latest_question_list])\r\n return HttpResponse(output)\r\n\r\n\"\"\"\r\n\t-Construir una vista que retorne todas las opciones asociadas a una pregunta\r\n\t*FILTRAR POR ID DE PREGUNTA\r\n\"\"\"",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
#coding: utf-8
import numpy as np
import cv2
leftgray = cv2.imread('../image/1.jpg')
rightgray = cv2.imread('../image/2.jpg')
hessian=500
surf=cv2.xfeatures2d.SURF_create(hessian) #将Hessian Threshold设置为400,阈值越大能检测的特征就越少
kp1,des1=surf.detectAndCompute(leftgray,None) #查找关键点和描述符
kp2,des2=surf.detectAndCompute(rightgray,None)
FLANN_INDEX_KDTREE=0 #建立FLANN匹配器的参数
indexParams=dict(algorithm=FLANN_INDEX_KDTREE,trees=5) #配置索引,密度树的数量为5
searchParams=dict(checks=50) #指定递归次数
#FlannBasedMatcher:是目前最快的特征匹配算法(最近邻搜索)
flann=cv2.FlannBasedMatcher(indexParams,searchParams) #建立匹配器
matches=flann.knnMatch(des1,des2,k=2) #得出匹配的关键点
a = cv2.drawMatchesKnn(leftgray, kp1, rightgray, kp2, matches,None, flags=2)
cv2.namedWindow("mathches",1)
cv2.imshow("mathches",a)
cv2.waitKey()
good=[]
#提取优秀的特征点
for m,n in matches:
if m.distance < 0.45*n.distance: #如果第一个邻近距离比第二个邻近距离的0.7倍小,则保留
good.append(m)
print(len(good))
result = cv2.drawMatches(leftgray, kp1, rightgray, kp2, good,None, flags=2)
cv2.namedWindow("result",1)
cv2.imshow("result",result)
cv2.waitKey()
src_pts = np.array([ kp1[m.queryIdx].pt for m in good]) #查询图像的特征描述子索引
dst_pts = np.array([ kp2[m.trainIdx].pt for m in good]) #训练(模板)图像的特征描述子索引
print(len(src_pts),len(dst_pts))
H=cv2.findHomography(src_pts,dst_pts) #生成变换矩阵
print('H:',H)
h,w=leftgray.shape[:2]
h1,w1=rightgray.shape[:2]
shft=np.array([[1.0,0,w],[0,1.0,0],[0,0,1.0]])
print('shft:',shft)
M=np.dot(shft,H[0]) #获取左边图像到右边图像的投影映射关系
print('M:',M)
dst_corners=cv2.warpPerspective(leftgray,M,(w*2 ,h))#透视变换,新图像可容纳完整的两幅图
cv2.namedWindow("tiledImg1" ,cv2.WINDOW_NORMAL)
cv2.imshow('tiledImg1',dst_corners) #显示,第一幅图已在标准位置
cv2.waitKey()
dst_corners[0:h,w:w*2]=rightgray #将第二幅图放在右侧
#cv2.imwrite('tiled.jpg',dst_corners)
cv2.namedWindow("tiledImg" ,cv2.WINDOW_NORMAL)
cv2.imshow('tiledImg',dst_corners)
#cv2.imshow('leftgray',leftgray)
#cv2.imshow('rightgray',rightgray)
cv2.waitKey()
cv2.destroyAllWindows()
|
normal
|
{
"blob_id": "60953878c377382f1c7f25ce284c9fa12b8eb25f",
"index": 4667,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ncv2.namedWindow('mathches', 1)\ncv2.imshow('mathches', a)\ncv2.waitKey()\n<mask token>\nfor m, n in matches:\n if m.distance < 0.45 * n.distance:\n good.append(m)\nprint(len(good))\n<mask token>\ncv2.namedWindow('result', 1)\ncv2.imshow('result', result)\ncv2.waitKey()\n<mask token>\nprint(len(src_pts), len(dst_pts))\n<mask token>\nprint('H:', H)\n<mask token>\nprint('shft:', shft)\n<mask token>\nprint('M:', M)\n<mask token>\ncv2.namedWindow('tiledImg1', cv2.WINDOW_NORMAL)\ncv2.imshow('tiledImg1', dst_corners)\ncv2.waitKey()\n<mask token>\ncv2.namedWindow('tiledImg', cv2.WINDOW_NORMAL)\ncv2.imshow('tiledImg', dst_corners)\ncv2.waitKey()\ncv2.destroyAllWindows()\n",
"step-3": "<mask token>\nleftgray = cv2.imread('../image/1.jpg')\nrightgray = cv2.imread('../image/2.jpg')\nhessian = 500\nsurf = cv2.xfeatures2d.SURF_create(hessian)\nkp1, des1 = surf.detectAndCompute(leftgray, None)\nkp2, des2 = surf.detectAndCompute(rightgray, None)\nFLANN_INDEX_KDTREE = 0\nindexParams = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)\nsearchParams = dict(checks=50)\nflann = cv2.FlannBasedMatcher(indexParams, searchParams)\nmatches = flann.knnMatch(des1, des2, k=2)\na = cv2.drawMatchesKnn(leftgray, kp1, rightgray, kp2, matches, None, flags=2)\ncv2.namedWindow('mathches', 1)\ncv2.imshow('mathches', a)\ncv2.waitKey()\ngood = []\nfor m, n in matches:\n if m.distance < 0.45 * n.distance:\n good.append(m)\nprint(len(good))\nresult = cv2.drawMatches(leftgray, kp1, rightgray, kp2, good, None, flags=2)\ncv2.namedWindow('result', 1)\ncv2.imshow('result', result)\ncv2.waitKey()\nsrc_pts = np.array([kp1[m.queryIdx].pt for m in good])\ndst_pts = np.array([kp2[m.trainIdx].pt for m in good])\nprint(len(src_pts), len(dst_pts))\nH = cv2.findHomography(src_pts, dst_pts)\nprint('H:', H)\nh, w = leftgray.shape[:2]\nh1, w1 = rightgray.shape[:2]\nshft = np.array([[1.0, 0, w], [0, 1.0, 0], [0, 0, 1.0]])\nprint('shft:', shft)\nM = np.dot(shft, H[0])\nprint('M:', M)\ndst_corners = cv2.warpPerspective(leftgray, M, (w * 2, h))\ncv2.namedWindow('tiledImg1', cv2.WINDOW_NORMAL)\ncv2.imshow('tiledImg1', dst_corners)\ncv2.waitKey()\ndst_corners[0:h, w:w * 2] = rightgray\ncv2.namedWindow('tiledImg', cv2.WINDOW_NORMAL)\ncv2.imshow('tiledImg', dst_corners)\ncv2.waitKey()\ncv2.destroyAllWindows()\n",
"step-4": "import numpy as np\nimport cv2\nleftgray = cv2.imread('../image/1.jpg')\nrightgray = cv2.imread('../image/2.jpg')\nhessian = 500\nsurf = cv2.xfeatures2d.SURF_create(hessian)\nkp1, des1 = surf.detectAndCompute(leftgray, None)\nkp2, des2 = surf.detectAndCompute(rightgray, None)\nFLANN_INDEX_KDTREE = 0\nindexParams = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)\nsearchParams = dict(checks=50)\nflann = cv2.FlannBasedMatcher(indexParams, searchParams)\nmatches = flann.knnMatch(des1, des2, k=2)\na = cv2.drawMatchesKnn(leftgray, kp1, rightgray, kp2, matches, None, flags=2)\ncv2.namedWindow('mathches', 1)\ncv2.imshow('mathches', a)\ncv2.waitKey()\ngood = []\nfor m, n in matches:\n if m.distance < 0.45 * n.distance:\n good.append(m)\nprint(len(good))\nresult = cv2.drawMatches(leftgray, kp1, rightgray, kp2, good, None, flags=2)\ncv2.namedWindow('result', 1)\ncv2.imshow('result', result)\ncv2.waitKey()\nsrc_pts = np.array([kp1[m.queryIdx].pt for m in good])\ndst_pts = np.array([kp2[m.trainIdx].pt for m in good])\nprint(len(src_pts), len(dst_pts))\nH = cv2.findHomography(src_pts, dst_pts)\nprint('H:', H)\nh, w = leftgray.shape[:2]\nh1, w1 = rightgray.shape[:2]\nshft = np.array([[1.0, 0, w], [0, 1.0, 0], [0, 0, 1.0]])\nprint('shft:', shft)\nM = np.dot(shft, H[0])\nprint('M:', M)\ndst_corners = cv2.warpPerspective(leftgray, M, (w * 2, h))\ncv2.namedWindow('tiledImg1', cv2.WINDOW_NORMAL)\ncv2.imshow('tiledImg1', dst_corners)\ncv2.waitKey()\ndst_corners[0:h, w:w * 2] = rightgray\ncv2.namedWindow('tiledImg', cv2.WINDOW_NORMAL)\ncv2.imshow('tiledImg', dst_corners)\ncv2.waitKey()\ncv2.destroyAllWindows()\n",
"step-5": "#coding: utf-8\nimport numpy as np\nimport cv2\n\n\nleftgray = cv2.imread('../image/1.jpg')\nrightgray = cv2.imread('../image/2.jpg')\n \nhessian=500\nsurf=cv2.xfeatures2d.SURF_create(hessian) #将Hessian Threshold设置为400,阈值越大能检测的特征就越少\nkp1,des1=surf.detectAndCompute(leftgray,None) #查找关键点和描述符\nkp2,des2=surf.detectAndCompute(rightgray,None)\n \nFLANN_INDEX_KDTREE=0 #建立FLANN匹配器的参数\nindexParams=dict(algorithm=FLANN_INDEX_KDTREE,trees=5) #配置索引,密度树的数量为5\nsearchParams=dict(checks=50) #指定递归次数\n#FlannBasedMatcher:是目前最快的特征匹配算法(最近邻搜索)\nflann=cv2.FlannBasedMatcher(indexParams,searchParams) #建立匹配器\nmatches=flann.knnMatch(des1,des2,k=2) #得出匹配的关键点\n\na = cv2.drawMatchesKnn(leftgray, kp1, rightgray, kp2, matches,None, flags=2)\n\ncv2.namedWindow(\"mathches\",1)\ncv2.imshow(\"mathches\",a)\ncv2.waitKey()\n\ngood=[]\n#提取优秀的特征点\nfor m,n in matches:\n if m.distance < 0.45*n.distance: #如果第一个邻近距离比第二个邻近距离的0.7倍小,则保留\n good.append(m)\nprint(len(good))\nresult = cv2.drawMatches(leftgray, kp1, rightgray, kp2, good,None, flags=2)\ncv2.namedWindow(\"result\",1)\ncv2.imshow(\"result\",result)\ncv2.waitKey()\n\nsrc_pts = np.array([ kp1[m.queryIdx].pt for m in good]) #查询图像的特征描述子索引\ndst_pts = np.array([ kp2[m.trainIdx].pt for m in good]) #训练(模板)图像的特征描述子索引\n\nprint(len(src_pts),len(dst_pts))\nH=cv2.findHomography(src_pts,dst_pts) #生成变换矩阵\n\nprint('H:',H)\n \nh,w=leftgray.shape[:2]\nh1,w1=rightgray.shape[:2]\nshft=np.array([[1.0,0,w],[0,1.0,0],[0,0,1.0]])\nprint('shft:',shft)\nM=np.dot(shft,H[0]) #获取左边图像到右边图像的投影映射关系\nprint('M:',M)\ndst_corners=cv2.warpPerspective(leftgray,M,(w*2 ,h))#透视变换,新图像可容纳完整的两幅图\ncv2.namedWindow(\"tiledImg1\" ,cv2.WINDOW_NORMAL)\ncv2.imshow('tiledImg1',dst_corners) #显示,第一幅图已在标准位置\n\ncv2.waitKey()\ndst_corners[0:h,w:w*2]=rightgray #将第二幅图放在右侧\n#cv2.imwrite('tiled.jpg',dst_corners)\ncv2.namedWindow(\"tiledImg\" ,cv2.WINDOW_NORMAL)\n \ncv2.imshow('tiledImg',dst_corners)\n#cv2.imshow('leftgray',leftgray)\n#cv2.imshow('rightgray',rightgray)\ncv2.waitKey()\ncv2.destroyAllWindows()\n\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
''' Load a variety of relevant physical parameters.
All quantities are in atomic units, such that
m_e = 1
e = 1
hbar = 1
1/4\pi\epsilon = 1
'''
import numpy as np
hbar = 1.0
m_e = 1.0
h22m = hbar**2 / (2*m_e)
pi = np.pi
eV = 1/27.21138505
eV_Ha = eV
nm = 18.89726124565
kB_eV = 8.6173324e-5
kB = kB_eV * eV_Ha
|
normal
|
{
"blob_id": "f9f835b24aa8fc77109db9e2d89a3f43bcb4b181",
"index": 7079,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nhbar = 1.0\nm_e = 1.0\nh22m = hbar ** 2 / (2 * m_e)\npi = np.pi\neV = 1 / 27.21138505\neV_Ha = eV\nnm = 18.89726124565\nkB_eV = 8.6173324e-05\nkB = kB_eV * eV_Ha\n",
"step-3": "<mask token>\nimport numpy as np\nhbar = 1.0\nm_e = 1.0\nh22m = hbar ** 2 / (2 * m_e)\npi = np.pi\neV = 1 / 27.21138505\neV_Ha = eV\nnm = 18.89726124565\nkB_eV = 8.6173324e-05\nkB = kB_eV * eV_Ha\n",
"step-4": "''' Load a variety of relevant physical parameters.\n\nAll quantities are in atomic units, such that\n m_e = 1\n e = 1\n hbar = 1\n 1/4\\pi\\epsilon = 1\n'''\n\nimport numpy as np\n\nhbar = 1.0\nm_e = 1.0\nh22m = hbar**2 / (2*m_e)\npi = np.pi\neV = 1/27.21138505\neV_Ha = eV\nnm = 18.89726124565\n\nkB_eV = 8.6173324e-5\nkB = kB_eV * eV_Ha \n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
# Jeremy Jao
# University of Pittsburgh: DBMI
# 6/18/2013
#
# This is the thing that returns the dictionary of the key. we can edit more code to return different values in the keys (gene) in each dictionary inside the dictionary.
# my sys.argv isn't working in my situation due to my IDE (nor do I not know how it would work.... but yeah........... It's easy to code this.
import cPickle
#import sys
#
#arg = sys.argv[0]
print "Displaying dictionary for " + "MESTIT1"
hi = open("geneDictionary.pickle", "r")
hello = cPickle.load(hi)
print hello["MESTIT1"]
|
normal
|
{
"blob_id": "7016a7dda80c0cfae0e15cf239f6ae64eb9004b7",
"index": 9733,
"step-1": "# Jeremy Jao\r\n# University of Pittsburgh: DBMI\r\n# 6/18/2013\r\n#\r\n# This is the thing that returns the dictionary of the key. we can edit more code to return different values in the keys (gene) in each dictionary inside the dictionary.\r\n# my sys.argv isn't working in my situation due to my IDE (nor do I not know how it would work.... but yeah........... It's easy to code this.\r\n\r\nimport cPickle\r\n#import sys\r\n#\r\n#arg = sys.argv[0]\r\n\r\nprint \"Displaying dictionary for \" + \"MESTIT1\"\r\n\r\nhi = open(\"geneDictionary.pickle\", \"r\")\r\n\r\nhello = cPickle.load(hi)\r\n\r\nprint hello[\"MESTIT1\"]",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
# Copyright 2016 Tesora, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
charset = {"big5": ["big5_chinese_ci", "big5_bin"],
"dec8": ["dec8_swedish_ci", "dec8_bin"],
"cp850": ["cp850_general_ci", "cp850_bin"],
"hp8": ["hp8_english_ci", "hp8_bin"],
"koi8r": ["koi8r_general_ci", "koi8r_bin"],
"latin1": ["latin1_swedish_ci",
"latin1_german1_ci",
"latin1_danish_ci",
"latin1_german2_ci",
"latin1_bin",
"latin1_general_ci",
"latin1_general_cs",
"latin1_spanish_ci"],
"latin2": ["latin2_general_ci",
"latin2_czech_cs",
"latin2_hungarian_ci",
"latin2_croatian_ci",
"latin2_bin"],
"swe7": ["swe7_swedish_ci", "swe7_bin"],
"ascii": ["ascii_general_ci", "ascii_bin"],
"ujis": ["ujis_japanese_ci", "ujis_bin"],
"sjis": ["sjis_japanese_ci", "sjis_bin"],
"hebrew": ["hebrew_general_ci", "hebrew_bin"],
"tis620": ["tis620_thai_ci", "tis620_bin"],
"euckr": ["euckr_korean_ci", "euckr_bin"],
"koi8u": ["koi8u_general_ci", "koi8u_bin"],
"gb2312": ["gb2312_chinese_ci", "gb2312_bin"],
"greek": ["greek_general_ci", "greek_bin"],
"cp1250": ["cp1250_general_ci",
"cp1250_czech_cs",
"cp1250_croatian_ci",
"cp1250_bin",
"cp1250_polish_ci"],
"gbk": ["gbk_chinese_ci", "gbk_bin"],
"latin5": ["latin5_turkish_ci", "latin5_bin"],
"armscii8": ["armscii8_general_ci", "armscii8_bin"],
"utf8": ["utf8_general_ci",
"utf8_bin",
"utf8_unicode_ci",
"utf8_icelandic_ci",
"utf8_latvian_ci",
"utf8_romanian_ci",
"utf8_slovenian_ci",
"utf8_polish_ci",
"utf8_estonian_ci",
"utf8_spanish_ci",
"utf8_swedish_ci",
"utf8_turkish_ci",
"utf8_czech_ci",
"utf8_danish_ci",
"utf8_lithuanian_ci",
"utf8_slovak_ci",
"utf8_spanish2_ci",
"utf8_roman_ci",
"utf8_persian_ci",
"utf8_esperanto_ci",
"utf8_hungarian_ci",
"utf8_sinhala_ci",
"utf8_german2_ci",
"utf8_croatian_ci",
"utf8_unicode_520_ci",
"utf8_vietnamese_ci",
"utf8_general_mysql500_ci"
],
"utf8mb4": ["utf8mb4_0900_ai_ci"],
"utf8mb3": ["utf8mb3_general_ci"],
"ucs2": ["ucs2_general_ci",
"ucs2_bin",
"ucs2_unicode_ci",
"ucs2_icelandic_ci",
"ucs2_latvian_ci",
"ucs2_romanian_ci",
"ucs2_slovenian_ci",
"ucs2_polish_ci",
"ucs2_estonian_ci",
"ucs2_spanish_ci",
"ucs2_swedish_ci",
"ucs2_turkish_ci",
"ucs2_czech_ci",
"ucs2_danish_ci",
"ucs2_lithuanian_ci",
"ucs2_slovak_ci",
"ucs2_spanish2_ci",
"ucs2_roman_ci",
"ucs2_persian_ci",
"ucs2_esperanto_ci",
"ucs2_hungarian_ci",
"ucs2_sinhala_ci",
"ucs2_german2_ci",
"ucs2_croatian_ci",
"ucs2_unicode_520_ci",
"ucs2_vietnamese_ci",
"ucs2_general_mysql500_ci"
],
"cp866": ["cp866_general_ci", "cp866_bin"],
"keybcs2": ["keybcs2_general_ci", "keybcs2_bin"],
"macce": ["macce_general_ci", "macce_bin"],
"macroman": ["macroman_general_ci", "macroman_bin"],
"cp852": ["cp852_general_ci", "cp852_bin"],
"latin7": ["latin7_general_ci",
"latin7_estonian_cs",
"latin7_general_cs",
"latin7_bin"],
"utf8mb4": ["utf8mb4_general_ci",
"utf8mb4_bin",
"utf8mb4_unicode_ci",
"utf8mb4_icelandic_ci",
"utf8mb4_latvian_ci",
"utf8mb4_romanian_ci",
"utf8mb4_slovenian_ci",
"utf8mb4_polish_ci",
"utf8mb4_estonian_ci",
"utf8mb4_spanish_ci",
"utf8mb4_swedish_ci",
"utf8mb4_turkish_ci",
"utf8mb4_czech_ci",
"utf8mb4_danish_ci",
"utf8mb4_lithuanian_ci",
"utf8mb4_slovak_ci",
"utf8mb4_spanish2_ci",
"utf8mb4_roman_ci",
"utf8mb4_persian_ci",
"utf8mb4_esperanto_ci",
"utf8mb4_hungarian_ci",
"utf8mb4_sinhala_ci",
"utf8mb4_german2_ci",
"utf8mb4_croatian_ci",
"utf8mb4_unicode_520_ci",
"utf8mb4_vietnamese_ci"],
"cp1251": ["cp1251_general_ci",
"cp1251_bulgarian_ci",
"cp1251_ukrainian_ci",
"cp1251_bin",
"cp1251_general_cs"],
"utf16": ["utf16_general_ci",
"utf16_bin",
"utf16_unicode_ci",
"utf16_icelandic_ci",
"utf16_latvian_ci",
"utf16_romanian_ci",
"utf16_slovenian_ci",
"utf16_polish_ci",
"utf16_estonian_ci",
"utf16_spanish_ci",
"utf16_swedish_ci",
"utf16_turkish_ci",
"utf16_czech_ci",
"utf16_danish_ci",
"utf16_lithuanian_ci",
"utf16_slovak_ci",
"utf16_spanish2_ci",
"utf16_roman_ci",
"utf16_persian_ci",
"utf16_esperanto_ci",
"utf16_hungarian_ci",
"utf16_sinhala_ci",
"utf16_german2_ci",
"utf16_croatian_ci",
"utf16_unicode_520_ci",
"utf16_vietnamese_ci"],
"utf16le": ["utf16le_general_ci",
"utf16le_bin"],
"cp1256": ["cp1256_general_ci", "cp1256_bin"],
"cp1257": ["cp1257_general_ci",
"cp1257_lithuanian_ci",
"cp1257_bin"],
"utf32": ["utf32_general_ci",
"utf32_bin",
"utf32_unicode_ci",
"utf32_icelandic_ci",
"utf32_latvian_ci",
"utf32_romanian_ci",
"utf32_slovenian_ci",
"utf32_polish_ci",
"utf32_estonian_ci",
"utf32_spanish_ci",
"utf32_swedish_ci",
"utf32_turkish_ci",
"utf32_czech_ci",
"utf32_danish_ci",
"utf32_lithuanian_ci",
"utf32_slovak_ci",
"utf32_spanish2_ci",
"utf32_roman_ci",
"utf32_persian_ci",
"utf32_esperanto_ci",
"utf32_hungarian_ci",
"utf32_sinhala_ci",
"utf32_german2_ci",
"utf32_croatian_ci",
"utf32_unicode_520_ci",
"utf32_vietnamese_ci"],
"binary": ["binary"],
"geostd8": ["geostd8_general_ci", "geostd8_bin"],
"cp932": ["cp932_japanese_ci", "cp932_bin"],
"eucjpms": ["eucjpms_japanese_ci", "eucjpms_bin"],
"gb18030": ["gb18030_chinese_ci",
"gb18030_bin",
"gb18030_unicode_520_ci"]}
collation = {"big5_chinese_ci": "big5",
"big5_bin": "big5",
"dec8_swedish_ci": "dec8",
"dec8_bin": "dec8",
"cp850_general_ci": "cp850",
"cp850_bin": "cp850",
"hp8_english_ci": "hp8",
"hp8_bin": "hp8",
"koi8r_general_ci": "koi8r",
"koi8r_bin": "koi8r",
"latin1_german1_ci": "latin1",
"latin1_swedish_ci": "latin1",
"latin1_danish_ci": "latin1",
"latin1_german2_ci": "latin1",
"latin1_bin": "latin1",
"latin1_general_ci": "latin1",
"latin1_general_cs": "latin1",
"latin1_spanish_ci": "latin1",
"latin2_czech_cs": "latin2",
"latin2_general_ci": "latin2",
"latin2_hungarian_ci": "latin2",
"latin2_croatian_ci": "latin2",
"latin2_bin": "latin2",
"swe7_swedish_ci": "swe7",
"swe7_bin": "swe7",
"ascii_general_ci": "ascii",
"ascii_bin": "ascii",
"ujis_japanese_ci": "ujis",
"ujis_bin": "ujis",
"sjis_japanese_ci": "sjis",
"sjis_bin": "sjis",
"hebrew_general_ci": "hebrew",
"hebrew_bin": "hebrew",
"tis620_thai_ci": "tis620",
"tis620_bin": "tis620",
"euckr_korean_ci": "euckr",
"euckr_bin": "euckr",
"koi8u_general_ci": "koi8u",
"koi8u_bin": "koi8u",
"gb2312_chinese_ci": "gb2312",
"gb2312_bin": "gb2312",
"greek_general_ci": "greek",
"greek_bin": "greek",
"cp1250_general_ci": "cp1250",
"cp1250_czech_cs": "cp1250",
"cp1250_croatian_ci": "cp1250",
"cp1250_bin": "cp1250",
"cp1250_polish_ci": "cp1250",
"gbk_chinese_ci": "gbk",
"gbk_bin": "gbk",
"latin5_turkish_ci": "latin5",
"latin5_bin": "latin5",
"armscii8_general_ci": "armscii8",
"armscii8_bin": "armscii8",
"utf8_general_ci": "utf8",
"utf8mb3_general_ci": "utf8mb3",
"utf8_bin": "utf8",
"utf8_unicode_ci": "utf8",
"utf8_icelandic_ci": "utf8",
"utf8_latvian_ci": "utf8",
"utf8_romanian_ci": "utf8",
"utf8_slovenian_ci": "utf8",
"utf8_polish_ci": "utf8",
"utf8_estonian_ci": "utf8",
"utf8_spanish_ci": "utf8",
"utf8_swedish_ci": "utf8",
"utf8_turkish_ci": "utf8",
"utf8_czech_ci": "utf8",
"utf8_danish_ci": "utf8",
"utf8_lithuanian_ci": "utf8",
"utf8_slovak_ci": "utf8",
"utf8_spanish2_ci": "utf8",
"utf8_roman_ci": "utf8",
"utf8_persian_ci": "utf8",
"utf8_esperanto_ci": "utf8",
"utf8_hungarian_ci": "utf8",
"utf8_sinhala_ci": "utf8",
"utf8_german2_ci": "utf8",
"utf8_croatian_ci": "utf8",
"utf8_unicode_520_ci": "utf8",
"utf8_vietnamese_ci": "utf8",
"utf8_general_mysql500_ci": "utf8",
"utf8mb4_0900_ai_ci": "utf8mb4",
"ucs2_general_ci": "ucs2",
"ucs2_bin": "ucs2",
"ucs2_unicode_ci": "ucs2",
"ucs2_icelandic_ci": "ucs2",
"ucs2_latvian_ci": "ucs2",
"ucs2_romanian_ci": "ucs2",
"ucs2_slovenian_ci": "ucs2",
"ucs2_polish_ci": "ucs2",
"ucs2_estonian_ci": "ucs2",
"ucs2_spanish_ci": "ucs2",
"ucs2_swedish_ci": "ucs2",
"ucs2_turkish_ci": "ucs2",
"ucs2_czech_ci": "ucs2",
"ucs2_danish_ci": "ucs2",
"ucs2_lithuanian_ci": "ucs2",
"ucs2_slovak_ci": "ucs2",
"ucs2_spanish2_ci": "ucs2",
"ucs2_roman_ci": "ucs2",
"ucs2_persian_ci": "ucs2",
"ucs2_esperanto_ci": "ucs2",
"ucs2_hungarian_ci": "ucs2",
"ucs2_sinhala_ci": "ucs2",
"ucs2_german2_ci": "ucs2",
"ucs2_croatian_ci": "ucs2",
"ucs2_unicode_520_ci": "ucs2",
"ucs2_vietnamese_ci": "ucs2",
"ucs2_general_mysql500_ci": "ucs2",
"cp866_general_ci": "cp866",
"cp866_bin": "cp866",
"keybcs2_general_ci": "keybcs2",
"keybcs2_bin": "keybcs2",
"macce_general_ci": "macce",
"macce_bin": "macce",
"macroman_general_ci": "macroman",
"macroman_bin": "macroman",
"cp852_general_ci": "cp852",
"cp852_bin": "cp852",
"latin7_estonian_cs": "latin7",
"latin7_general_ci": "latin7",
"latin7_general_cs": "latin7",
"latin7_bin": "latin7",
"utf8mb4_general_ci": "utf8mb4",
"utf8mb4_bin": "utf8mb4",
"utf8mb4_unicode_ci": "utf8mb4",
"utf8mb4_icelandic_ci": "utf8mb4",
"utf8mb4_latvian_ci": "utf8mb4",
"utf8mb4_romanian_ci": "utf8mb4",
"utf8mb4_slovenian_ci": "utf8mb4",
"utf8mb4_polish_ci": "utf8mb4",
"utf8mb4_estonian_ci": "utf8mb4",
"utf8mb4_spanish_ci": "utf8mb4",
"utf8mb4_swedish_ci": "utf8mb4",
"utf8mb4_turkish_ci": "utf8mb4",
"utf8mb4_czech_ci": "utf8mb4",
"utf8mb4_danish_ci": "utf8mb4",
"utf8mb4_lithuanian_ci": "utf8mb4",
"utf8mb4_slovak_ci": "utf8mb4",
"utf8mb4_spanish2_ci": "utf8mb4",
"utf8mb4_roman_ci": "utf8mb4",
"utf8mb4_persian_ci": "utf8mb4",
"utf8mb4_esperanto_ci": "utf8mb4",
"utf8mb4_hungarian_ci": "utf8mb4",
"utf8mb4_sinhala_ci": "utf8mb4",
"utf8mb4_german2_ci": "utf8mb4",
"utf8mb4_croatian_ci": "utf8mb4",
"utf8mb4_unicode_520_ci": "utf8mb4",
"utf8mb4_vietnamese_ci": "utf8mb4",
"cp1251_bulgarian_ci": "cp1251",
"cp1251_ukrainian_ci": "cp1251",
"cp1251_bin": "cp1251",
"cp1251_general_ci": "cp1251",
"cp1251_general_cs": "cp1251",
"utf16_general_ci": "utf16",
"utf16_bin": "utf16",
"utf16_unicode_ci": "utf16",
"utf16_icelandic_ci": "utf16",
"utf16_latvian_ci": "utf16",
"utf16_romanian_ci": "utf16",
"utf16_slovenian_ci": "utf16",
"utf16_polish_ci": "utf16",
"utf16_estonian_ci": "utf16",
"utf16_spanish_ci": "utf16",
"utf16_swedish_ci": "utf16",
"utf16_turkish_ci": "utf16",
"utf16_czech_ci": "utf16",
"utf16_danish_ci": "utf16",
"utf16_lithuanian_ci": "utf16",
"utf16_slovak_ci": "utf16",
"utf16_spanish2_ci": "utf16",
"utf16_roman_ci": "utf16",
"utf16_persian_ci": "utf16",
"utf16_esperanto_ci": "utf16",
"utf16_hungarian_ci": "utf16",
"utf16_sinhala_ci": "utf16",
"utf16_german2_ci": "utf16",
"utf16_croatian_ci": "utf16",
"utf16_unicode_520_ci": "utf16",
"utf16_vietnamese_ci": "utf16",
"utf16le_general_ci": "utf16le",
"utf16le_bin": "utf16le",
"cp1256_general_ci": "cp1256",
"cp1256_bin": "cp1256",
"cp1257_lithuanian_ci": "cp1257",
"cp1257_bin": "cp1257",
"cp1257_general_ci": "cp1257",
"utf32_general_ci": "utf32",
"utf32_bin": "utf32",
"utf32_unicode_ci": "utf32",
"utf32_icelandic_ci": "utf32",
"utf32_latvian_ci": "utf32",
"utf32_romanian_ci": "utf32",
"utf32_slovenian_ci": "utf32",
"utf32_polish_ci": "utf32",
"utf32_estonian_ci": "utf32",
"utf32_spanish_ci": "utf32",
"utf32_swedish_ci": "utf32",
"utf32_turkish_ci": "utf32",
"utf32_czech_ci": "utf32",
"utf32_danish_ci": "utf32",
"utf32_lithuanian_ci": "utf32",
"utf32_slovak_ci": "utf32",
"utf32_spanish2_ci": "utf32",
"utf32_roman_ci": "utf32",
"utf32_persian_ci": "utf32",
"utf32_esperanto_ci": "utf32",
"utf32_hungarian_ci": "utf32",
"utf32_sinhala_ci": "utf32",
"utf32_german2_ci": "utf32",
"utf32_croatian_ci": "utf32",
"utf32_unicode_520_ci": "utf32",
"utf32_vietnamese_ci": "utf32",
"binary": "binary",
"geostd8_general_ci": "geostd8",
"geostd8_bin": "geostd8",
"cp932_japanese_ci": "cp932",
"cp932_bin": "cp932",
"eucjpms_japanese_ci": "eucjpms",
"eucjpms_bin": "eucjpms",
"gb18030_chinese_ci": "gb18030",
"gb18030_bin": "gb18030",
"gb18030_unicode_520_ci": "gb18030"}
|
normal
|
{
"blob_id": "5e29c6d1034f6612b0081037f8dc679b49f1dbef",
"index": 2855,
"step-1": "<mask token>\n",
"step-2": "charset = {'big5': ['big5_chinese_ci', 'big5_bin'], 'dec8': [\n 'dec8_swedish_ci', 'dec8_bin'], 'cp850': ['cp850_general_ci',\n 'cp850_bin'], 'hp8': ['hp8_english_ci', 'hp8_bin'], 'koi8r': [\n 'koi8r_general_ci', 'koi8r_bin'], 'latin1': ['latin1_swedish_ci',\n 'latin1_german1_ci', 'latin1_danish_ci', 'latin1_german2_ci',\n 'latin1_bin', 'latin1_general_ci', 'latin1_general_cs',\n 'latin1_spanish_ci'], 'latin2': ['latin2_general_ci', 'latin2_czech_cs',\n 'latin2_hungarian_ci', 'latin2_croatian_ci', 'latin2_bin'], 'swe7': [\n 'swe7_swedish_ci', 'swe7_bin'], 'ascii': ['ascii_general_ci',\n 'ascii_bin'], 'ujis': ['ujis_japanese_ci', 'ujis_bin'], 'sjis': [\n 'sjis_japanese_ci', 'sjis_bin'], 'hebrew': ['hebrew_general_ci',\n 'hebrew_bin'], 'tis620': ['tis620_thai_ci', 'tis620_bin'], 'euckr': [\n 'euckr_korean_ci', 'euckr_bin'], 'koi8u': ['koi8u_general_ci',\n 'koi8u_bin'], 'gb2312': ['gb2312_chinese_ci', 'gb2312_bin'], 'greek': [\n 'greek_general_ci', 'greek_bin'], 'cp1250': ['cp1250_general_ci',\n 'cp1250_czech_cs', 'cp1250_croatian_ci', 'cp1250_bin',\n 'cp1250_polish_ci'], 'gbk': ['gbk_chinese_ci', 'gbk_bin'], 'latin5': [\n 'latin5_turkish_ci', 'latin5_bin'], 'armscii8': ['armscii8_general_ci',\n 'armscii8_bin'], 'utf8': ['utf8_general_ci', 'utf8_bin',\n 'utf8_unicode_ci', 'utf8_icelandic_ci', 'utf8_latvian_ci',\n 'utf8_romanian_ci', 'utf8_slovenian_ci', 'utf8_polish_ci',\n 'utf8_estonian_ci', 'utf8_spanish_ci', 'utf8_swedish_ci',\n 'utf8_turkish_ci', 'utf8_czech_ci', 'utf8_danish_ci',\n 'utf8_lithuanian_ci', 'utf8_slovak_ci', 'utf8_spanish2_ci',\n 'utf8_roman_ci', 'utf8_persian_ci', 'utf8_esperanto_ci',\n 'utf8_hungarian_ci', 'utf8_sinhala_ci', 'utf8_german2_ci',\n 'utf8_croatian_ci', 'utf8_unicode_520_ci', 'utf8_vietnamese_ci',\n 'utf8_general_mysql500_ci'], 'utf8mb4': ['utf8mb4_0900_ai_ci'],\n 'utf8mb3': ['utf8mb3_general_ci'], 'ucs2': ['ucs2_general_ci',\n 'ucs2_bin', 'ucs2_unicode_ci', 'ucs2_icelandic_ci', 'ucs2_latvian_ci',\n 'ucs2_romanian_ci', 'ucs2_slovenian_ci', 'ucs2_polish_ci',\n 'ucs2_estonian_ci', 'ucs2_spanish_ci', 'ucs2_swedish_ci',\n 'ucs2_turkish_ci', 'ucs2_czech_ci', 'ucs2_danish_ci',\n 'ucs2_lithuanian_ci', 'ucs2_slovak_ci', 'ucs2_spanish2_ci',\n 'ucs2_roman_ci', 'ucs2_persian_ci', 'ucs2_esperanto_ci',\n 'ucs2_hungarian_ci', 'ucs2_sinhala_ci', 'ucs2_german2_ci',\n 'ucs2_croatian_ci', 'ucs2_unicode_520_ci', 'ucs2_vietnamese_ci',\n 'ucs2_general_mysql500_ci'], 'cp866': ['cp866_general_ci', 'cp866_bin'],\n 'keybcs2': ['keybcs2_general_ci', 'keybcs2_bin'], 'macce': [\n 'macce_general_ci', 'macce_bin'], 'macroman': ['macroman_general_ci',\n 'macroman_bin'], 'cp852': ['cp852_general_ci', 'cp852_bin'], 'latin7':\n ['latin7_general_ci', 'latin7_estonian_cs', 'latin7_general_cs',\n 'latin7_bin'], 'utf8mb4': ['utf8mb4_general_ci', 'utf8mb4_bin',\n 'utf8mb4_unicode_ci', 'utf8mb4_icelandic_ci', 'utf8mb4_latvian_ci',\n 'utf8mb4_romanian_ci', 'utf8mb4_slovenian_ci', 'utf8mb4_polish_ci',\n 'utf8mb4_estonian_ci', 'utf8mb4_spanish_ci', 'utf8mb4_swedish_ci',\n 'utf8mb4_turkish_ci', 'utf8mb4_czech_ci', 'utf8mb4_danish_ci',\n 'utf8mb4_lithuanian_ci', 'utf8mb4_slovak_ci', 'utf8mb4_spanish2_ci',\n 'utf8mb4_roman_ci', 'utf8mb4_persian_ci', 'utf8mb4_esperanto_ci',\n 'utf8mb4_hungarian_ci', 'utf8mb4_sinhala_ci', 'utf8mb4_german2_ci',\n 'utf8mb4_croatian_ci', 'utf8mb4_unicode_520_ci',\n 'utf8mb4_vietnamese_ci'], 'cp1251': ['cp1251_general_ci',\n 'cp1251_bulgarian_ci', 'cp1251_ukrainian_ci', 'cp1251_bin',\n 'cp1251_general_cs'], 'utf16': ['utf16_general_ci', 'utf16_bin',\n 'utf16_unicode_ci', 'utf16_icelandic_ci', 'utf16_latvian_ci',\n 'utf16_romanian_ci', 'utf16_slovenian_ci', 'utf16_polish_ci',\n 'utf16_estonian_ci', 'utf16_spanish_ci', 'utf16_swedish_ci',\n 'utf16_turkish_ci', 'utf16_czech_ci', 'utf16_danish_ci',\n 'utf16_lithuanian_ci', 'utf16_slovak_ci', 'utf16_spanish2_ci',\n 'utf16_roman_ci', 'utf16_persian_ci', 'utf16_esperanto_ci',\n 'utf16_hungarian_ci', 'utf16_sinhala_ci', 'utf16_german2_ci',\n 'utf16_croatian_ci', 'utf16_unicode_520_ci', 'utf16_vietnamese_ci'],\n 'utf16le': ['utf16le_general_ci', 'utf16le_bin'], 'cp1256': [\n 'cp1256_general_ci', 'cp1256_bin'], 'cp1257': ['cp1257_general_ci',\n 'cp1257_lithuanian_ci', 'cp1257_bin'], 'utf32': ['utf32_general_ci',\n 'utf32_bin', 'utf32_unicode_ci', 'utf32_icelandic_ci',\n 'utf32_latvian_ci', 'utf32_romanian_ci', 'utf32_slovenian_ci',\n 'utf32_polish_ci', 'utf32_estonian_ci', 'utf32_spanish_ci',\n 'utf32_swedish_ci', 'utf32_turkish_ci', 'utf32_czech_ci',\n 'utf32_danish_ci', 'utf32_lithuanian_ci', 'utf32_slovak_ci',\n 'utf32_spanish2_ci', 'utf32_roman_ci', 'utf32_persian_ci',\n 'utf32_esperanto_ci', 'utf32_hungarian_ci', 'utf32_sinhala_ci',\n 'utf32_german2_ci', 'utf32_croatian_ci', 'utf32_unicode_520_ci',\n 'utf32_vietnamese_ci'], 'binary': ['binary'], 'geostd8': [\n 'geostd8_general_ci', 'geostd8_bin'], 'cp932': ['cp932_japanese_ci',\n 'cp932_bin'], 'eucjpms': ['eucjpms_japanese_ci', 'eucjpms_bin'],\n 'gb18030': ['gb18030_chinese_ci', 'gb18030_bin', 'gb18030_unicode_520_ci']}\ncollation = {'big5_chinese_ci': 'big5', 'big5_bin': 'big5',\n 'dec8_swedish_ci': 'dec8', 'dec8_bin': 'dec8', 'cp850_general_ci':\n 'cp850', 'cp850_bin': 'cp850', 'hp8_english_ci': 'hp8', 'hp8_bin':\n 'hp8', 'koi8r_general_ci': 'koi8r', 'koi8r_bin': 'koi8r',\n 'latin1_german1_ci': 'latin1', 'latin1_swedish_ci': 'latin1',\n 'latin1_danish_ci': 'latin1', 'latin1_german2_ci': 'latin1',\n 'latin1_bin': 'latin1', 'latin1_general_ci': 'latin1',\n 'latin1_general_cs': 'latin1', 'latin1_spanish_ci': 'latin1',\n 'latin2_czech_cs': 'latin2', 'latin2_general_ci': 'latin2',\n 'latin2_hungarian_ci': 'latin2', 'latin2_croatian_ci': 'latin2',\n 'latin2_bin': 'latin2', 'swe7_swedish_ci': 'swe7', 'swe7_bin': 'swe7',\n 'ascii_general_ci': 'ascii', 'ascii_bin': 'ascii', 'ujis_japanese_ci':\n 'ujis', 'ujis_bin': 'ujis', 'sjis_japanese_ci': 'sjis', 'sjis_bin':\n 'sjis', 'hebrew_general_ci': 'hebrew', 'hebrew_bin': 'hebrew',\n 'tis620_thai_ci': 'tis620', 'tis620_bin': 'tis620', 'euckr_korean_ci':\n 'euckr', 'euckr_bin': 'euckr', 'koi8u_general_ci': 'koi8u', 'koi8u_bin':\n 'koi8u', 'gb2312_chinese_ci': 'gb2312', 'gb2312_bin': 'gb2312',\n 'greek_general_ci': 'greek', 'greek_bin': 'greek', 'cp1250_general_ci':\n 'cp1250', 'cp1250_czech_cs': 'cp1250', 'cp1250_croatian_ci': 'cp1250',\n 'cp1250_bin': 'cp1250', 'cp1250_polish_ci': 'cp1250', 'gbk_chinese_ci':\n 'gbk', 'gbk_bin': 'gbk', 'latin5_turkish_ci': 'latin5', 'latin5_bin':\n 'latin5', 'armscii8_general_ci': 'armscii8', 'armscii8_bin': 'armscii8',\n 'utf8_general_ci': 'utf8', 'utf8mb3_general_ci': 'utf8mb3', 'utf8_bin':\n 'utf8', 'utf8_unicode_ci': 'utf8', 'utf8_icelandic_ci': 'utf8',\n 'utf8_latvian_ci': 'utf8', 'utf8_romanian_ci': 'utf8',\n 'utf8_slovenian_ci': 'utf8', 'utf8_polish_ci': 'utf8',\n 'utf8_estonian_ci': 'utf8', 'utf8_spanish_ci': 'utf8',\n 'utf8_swedish_ci': 'utf8', 'utf8_turkish_ci': 'utf8', 'utf8_czech_ci':\n 'utf8', 'utf8_danish_ci': 'utf8', 'utf8_lithuanian_ci': 'utf8',\n 'utf8_slovak_ci': 'utf8', 'utf8_spanish2_ci': 'utf8', 'utf8_roman_ci':\n 'utf8', 'utf8_persian_ci': 'utf8', 'utf8_esperanto_ci': 'utf8',\n 'utf8_hungarian_ci': 'utf8', 'utf8_sinhala_ci': 'utf8',\n 'utf8_german2_ci': 'utf8', 'utf8_croatian_ci': 'utf8',\n 'utf8_unicode_520_ci': 'utf8', 'utf8_vietnamese_ci': 'utf8',\n 'utf8_general_mysql500_ci': 'utf8', 'utf8mb4_0900_ai_ci': 'utf8mb4',\n 'ucs2_general_ci': 'ucs2', 'ucs2_bin': 'ucs2', 'ucs2_unicode_ci':\n 'ucs2', 'ucs2_icelandic_ci': 'ucs2', 'ucs2_latvian_ci': 'ucs2',\n 'ucs2_romanian_ci': 'ucs2', 'ucs2_slovenian_ci': 'ucs2',\n 'ucs2_polish_ci': 'ucs2', 'ucs2_estonian_ci': 'ucs2', 'ucs2_spanish_ci':\n 'ucs2', 'ucs2_swedish_ci': 'ucs2', 'ucs2_turkish_ci': 'ucs2',\n 'ucs2_czech_ci': 'ucs2', 'ucs2_danish_ci': 'ucs2', 'ucs2_lithuanian_ci':\n 'ucs2', 'ucs2_slovak_ci': 'ucs2', 'ucs2_spanish2_ci': 'ucs2',\n 'ucs2_roman_ci': 'ucs2', 'ucs2_persian_ci': 'ucs2', 'ucs2_esperanto_ci':\n 'ucs2', 'ucs2_hungarian_ci': 'ucs2', 'ucs2_sinhala_ci': 'ucs2',\n 'ucs2_german2_ci': 'ucs2', 'ucs2_croatian_ci': 'ucs2',\n 'ucs2_unicode_520_ci': 'ucs2', 'ucs2_vietnamese_ci': 'ucs2',\n 'ucs2_general_mysql500_ci': 'ucs2', 'cp866_general_ci': 'cp866',\n 'cp866_bin': 'cp866', 'keybcs2_general_ci': 'keybcs2', 'keybcs2_bin':\n 'keybcs2', 'macce_general_ci': 'macce', 'macce_bin': 'macce',\n 'macroman_general_ci': 'macroman', 'macroman_bin': 'macroman',\n 'cp852_general_ci': 'cp852', 'cp852_bin': 'cp852', 'latin7_estonian_cs':\n 'latin7', 'latin7_general_ci': 'latin7', 'latin7_general_cs': 'latin7',\n 'latin7_bin': 'latin7', 'utf8mb4_general_ci': 'utf8mb4', 'utf8mb4_bin':\n 'utf8mb4', 'utf8mb4_unicode_ci': 'utf8mb4', 'utf8mb4_icelandic_ci':\n 'utf8mb4', 'utf8mb4_latvian_ci': 'utf8mb4', 'utf8mb4_romanian_ci':\n 'utf8mb4', 'utf8mb4_slovenian_ci': 'utf8mb4', 'utf8mb4_polish_ci':\n 'utf8mb4', 'utf8mb4_estonian_ci': 'utf8mb4', 'utf8mb4_spanish_ci':\n 'utf8mb4', 'utf8mb4_swedish_ci': 'utf8mb4', 'utf8mb4_turkish_ci':\n 'utf8mb4', 'utf8mb4_czech_ci': 'utf8mb4', 'utf8mb4_danish_ci':\n 'utf8mb4', 'utf8mb4_lithuanian_ci': 'utf8mb4', 'utf8mb4_slovak_ci':\n 'utf8mb4', 'utf8mb4_spanish2_ci': 'utf8mb4', 'utf8mb4_roman_ci':\n 'utf8mb4', 'utf8mb4_persian_ci': 'utf8mb4', 'utf8mb4_esperanto_ci':\n 'utf8mb4', 'utf8mb4_hungarian_ci': 'utf8mb4', 'utf8mb4_sinhala_ci':\n 'utf8mb4', 'utf8mb4_german2_ci': 'utf8mb4', 'utf8mb4_croatian_ci':\n 'utf8mb4', 'utf8mb4_unicode_520_ci': 'utf8mb4', 'utf8mb4_vietnamese_ci':\n 'utf8mb4', 'cp1251_bulgarian_ci': 'cp1251', 'cp1251_ukrainian_ci':\n 'cp1251', 'cp1251_bin': 'cp1251', 'cp1251_general_ci': 'cp1251',\n 'cp1251_general_cs': 'cp1251', 'utf16_general_ci': 'utf16', 'utf16_bin':\n 'utf16', 'utf16_unicode_ci': 'utf16', 'utf16_icelandic_ci': 'utf16',\n 'utf16_latvian_ci': 'utf16', 'utf16_romanian_ci': 'utf16',\n 'utf16_slovenian_ci': 'utf16', 'utf16_polish_ci': 'utf16',\n 'utf16_estonian_ci': 'utf16', 'utf16_spanish_ci': 'utf16',\n 'utf16_swedish_ci': 'utf16', 'utf16_turkish_ci': 'utf16',\n 'utf16_czech_ci': 'utf16', 'utf16_danish_ci': 'utf16',\n 'utf16_lithuanian_ci': 'utf16', 'utf16_slovak_ci': 'utf16',\n 'utf16_spanish2_ci': 'utf16', 'utf16_roman_ci': 'utf16',\n 'utf16_persian_ci': 'utf16', 'utf16_esperanto_ci': 'utf16',\n 'utf16_hungarian_ci': 'utf16', 'utf16_sinhala_ci': 'utf16',\n 'utf16_german2_ci': 'utf16', 'utf16_croatian_ci': 'utf16',\n 'utf16_unicode_520_ci': 'utf16', 'utf16_vietnamese_ci': 'utf16',\n 'utf16le_general_ci': 'utf16le', 'utf16le_bin': 'utf16le',\n 'cp1256_general_ci': 'cp1256', 'cp1256_bin': 'cp1256',\n 'cp1257_lithuanian_ci': 'cp1257', 'cp1257_bin': 'cp1257',\n 'cp1257_general_ci': 'cp1257', 'utf32_general_ci': 'utf32', 'utf32_bin':\n 'utf32', 'utf32_unicode_ci': 'utf32', 'utf32_icelandic_ci': 'utf32',\n 'utf32_latvian_ci': 'utf32', 'utf32_romanian_ci': 'utf32',\n 'utf32_slovenian_ci': 'utf32', 'utf32_polish_ci': 'utf32',\n 'utf32_estonian_ci': 'utf32', 'utf32_spanish_ci': 'utf32',\n 'utf32_swedish_ci': 'utf32', 'utf32_turkish_ci': 'utf32',\n 'utf32_czech_ci': 'utf32', 'utf32_danish_ci': 'utf32',\n 'utf32_lithuanian_ci': 'utf32', 'utf32_slovak_ci': 'utf32',\n 'utf32_spanish2_ci': 'utf32', 'utf32_roman_ci': 'utf32',\n 'utf32_persian_ci': 'utf32', 'utf32_esperanto_ci': 'utf32',\n 'utf32_hungarian_ci': 'utf32', 'utf32_sinhala_ci': 'utf32',\n 'utf32_german2_ci': 'utf32', 'utf32_croatian_ci': 'utf32',\n 'utf32_unicode_520_ci': 'utf32', 'utf32_vietnamese_ci': 'utf32',\n 'binary': 'binary', 'geostd8_general_ci': 'geostd8', 'geostd8_bin':\n 'geostd8', 'cp932_japanese_ci': 'cp932', 'cp932_bin': 'cp932',\n 'eucjpms_japanese_ci': 'eucjpms', 'eucjpms_bin': 'eucjpms',\n 'gb18030_chinese_ci': 'gb18030', 'gb18030_bin': 'gb18030',\n 'gb18030_unicode_520_ci': 'gb18030'}\n",
"step-3": "# Copyright 2016 Tesora, Inc.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\ncharset = {\"big5\": [\"big5_chinese_ci\", \"big5_bin\"],\n \"dec8\": [\"dec8_swedish_ci\", \"dec8_bin\"],\n \"cp850\": [\"cp850_general_ci\", \"cp850_bin\"],\n \"hp8\": [\"hp8_english_ci\", \"hp8_bin\"],\n \"koi8r\": [\"koi8r_general_ci\", \"koi8r_bin\"],\n \"latin1\": [\"latin1_swedish_ci\",\n \"latin1_german1_ci\",\n \"latin1_danish_ci\",\n \"latin1_german2_ci\",\n \"latin1_bin\",\n \"latin1_general_ci\",\n \"latin1_general_cs\",\n \"latin1_spanish_ci\"],\n \"latin2\": [\"latin2_general_ci\",\n \"latin2_czech_cs\",\n \"latin2_hungarian_ci\",\n \"latin2_croatian_ci\",\n \"latin2_bin\"],\n \"swe7\": [\"swe7_swedish_ci\", \"swe7_bin\"],\n \"ascii\": [\"ascii_general_ci\", \"ascii_bin\"],\n \"ujis\": [\"ujis_japanese_ci\", \"ujis_bin\"],\n \"sjis\": [\"sjis_japanese_ci\", \"sjis_bin\"],\n \"hebrew\": [\"hebrew_general_ci\", \"hebrew_bin\"],\n \"tis620\": [\"tis620_thai_ci\", \"tis620_bin\"],\n \"euckr\": [\"euckr_korean_ci\", \"euckr_bin\"],\n \"koi8u\": [\"koi8u_general_ci\", \"koi8u_bin\"],\n \"gb2312\": [\"gb2312_chinese_ci\", \"gb2312_bin\"],\n \"greek\": [\"greek_general_ci\", \"greek_bin\"],\n \"cp1250\": [\"cp1250_general_ci\",\n \"cp1250_czech_cs\",\n \"cp1250_croatian_ci\",\n \"cp1250_bin\",\n \"cp1250_polish_ci\"],\n \"gbk\": [\"gbk_chinese_ci\", \"gbk_bin\"],\n \"latin5\": [\"latin5_turkish_ci\", \"latin5_bin\"],\n \"armscii8\": [\"armscii8_general_ci\", \"armscii8_bin\"],\n \"utf8\": [\"utf8_general_ci\",\n \"utf8_bin\",\n \"utf8_unicode_ci\",\n \"utf8_icelandic_ci\",\n \"utf8_latvian_ci\",\n \"utf8_romanian_ci\",\n \"utf8_slovenian_ci\",\n \"utf8_polish_ci\",\n \"utf8_estonian_ci\",\n \"utf8_spanish_ci\",\n \"utf8_swedish_ci\",\n \"utf8_turkish_ci\",\n \"utf8_czech_ci\",\n \"utf8_danish_ci\",\n \"utf8_lithuanian_ci\",\n \"utf8_slovak_ci\",\n \"utf8_spanish2_ci\",\n \"utf8_roman_ci\",\n \"utf8_persian_ci\",\n \"utf8_esperanto_ci\",\n \"utf8_hungarian_ci\",\n \"utf8_sinhala_ci\",\n \"utf8_german2_ci\",\n \"utf8_croatian_ci\",\n \"utf8_unicode_520_ci\",\n \"utf8_vietnamese_ci\",\n \"utf8_general_mysql500_ci\"\n ],\n \"utf8mb4\": [\"utf8mb4_0900_ai_ci\"],\n \"utf8mb3\": [\"utf8mb3_general_ci\"],\n \"ucs2\": [\"ucs2_general_ci\",\n \"ucs2_bin\",\n \"ucs2_unicode_ci\",\n \"ucs2_icelandic_ci\",\n \"ucs2_latvian_ci\",\n \"ucs2_romanian_ci\",\n \"ucs2_slovenian_ci\",\n \"ucs2_polish_ci\",\n \"ucs2_estonian_ci\",\n \"ucs2_spanish_ci\",\n \"ucs2_swedish_ci\",\n \"ucs2_turkish_ci\",\n \"ucs2_czech_ci\",\n \"ucs2_danish_ci\",\n \"ucs2_lithuanian_ci\",\n \"ucs2_slovak_ci\",\n \"ucs2_spanish2_ci\",\n \"ucs2_roman_ci\",\n \"ucs2_persian_ci\",\n \"ucs2_esperanto_ci\",\n \"ucs2_hungarian_ci\",\n \"ucs2_sinhala_ci\",\n \"ucs2_german2_ci\",\n \"ucs2_croatian_ci\",\n \"ucs2_unicode_520_ci\",\n \"ucs2_vietnamese_ci\",\n \"ucs2_general_mysql500_ci\"\n ],\n \"cp866\": [\"cp866_general_ci\", \"cp866_bin\"],\n \"keybcs2\": [\"keybcs2_general_ci\", \"keybcs2_bin\"],\n \"macce\": [\"macce_general_ci\", \"macce_bin\"],\n \"macroman\": [\"macroman_general_ci\", \"macroman_bin\"],\n \"cp852\": [\"cp852_general_ci\", \"cp852_bin\"],\n \"latin7\": [\"latin7_general_ci\",\n \"latin7_estonian_cs\",\n \"latin7_general_cs\",\n \"latin7_bin\"],\n \"utf8mb4\": [\"utf8mb4_general_ci\",\n \"utf8mb4_bin\",\n \"utf8mb4_unicode_ci\",\n \"utf8mb4_icelandic_ci\",\n \"utf8mb4_latvian_ci\",\n \"utf8mb4_romanian_ci\",\n \"utf8mb4_slovenian_ci\",\n \"utf8mb4_polish_ci\",\n \"utf8mb4_estonian_ci\",\n \"utf8mb4_spanish_ci\",\n \"utf8mb4_swedish_ci\",\n \"utf8mb4_turkish_ci\",\n \"utf8mb4_czech_ci\",\n \"utf8mb4_danish_ci\",\n \"utf8mb4_lithuanian_ci\",\n \"utf8mb4_slovak_ci\",\n \"utf8mb4_spanish2_ci\",\n \"utf8mb4_roman_ci\",\n \"utf8mb4_persian_ci\",\n \"utf8mb4_esperanto_ci\",\n \"utf8mb4_hungarian_ci\",\n \"utf8mb4_sinhala_ci\",\n \"utf8mb4_german2_ci\",\n \"utf8mb4_croatian_ci\",\n \"utf8mb4_unicode_520_ci\",\n \"utf8mb4_vietnamese_ci\"],\n \"cp1251\": [\"cp1251_general_ci\",\n \"cp1251_bulgarian_ci\",\n \"cp1251_ukrainian_ci\",\n \"cp1251_bin\",\n \"cp1251_general_cs\"],\n \"utf16\": [\"utf16_general_ci\",\n \"utf16_bin\",\n \"utf16_unicode_ci\",\n \"utf16_icelandic_ci\",\n \"utf16_latvian_ci\",\n \"utf16_romanian_ci\",\n \"utf16_slovenian_ci\",\n \"utf16_polish_ci\",\n \"utf16_estonian_ci\",\n \"utf16_spanish_ci\",\n \"utf16_swedish_ci\",\n \"utf16_turkish_ci\",\n \"utf16_czech_ci\",\n \"utf16_danish_ci\",\n \"utf16_lithuanian_ci\",\n \"utf16_slovak_ci\",\n \"utf16_spanish2_ci\",\n \"utf16_roman_ci\",\n \"utf16_persian_ci\",\n \"utf16_esperanto_ci\",\n \"utf16_hungarian_ci\",\n \"utf16_sinhala_ci\",\n \"utf16_german2_ci\",\n \"utf16_croatian_ci\",\n \"utf16_unicode_520_ci\",\n \"utf16_vietnamese_ci\"],\n \"utf16le\": [\"utf16le_general_ci\",\n \"utf16le_bin\"],\n \"cp1256\": [\"cp1256_general_ci\", \"cp1256_bin\"],\n \"cp1257\": [\"cp1257_general_ci\",\n \"cp1257_lithuanian_ci\",\n \"cp1257_bin\"],\n \"utf32\": [\"utf32_general_ci\",\n \"utf32_bin\",\n \"utf32_unicode_ci\",\n \"utf32_icelandic_ci\",\n \"utf32_latvian_ci\",\n \"utf32_romanian_ci\",\n \"utf32_slovenian_ci\",\n \"utf32_polish_ci\",\n \"utf32_estonian_ci\",\n \"utf32_spanish_ci\",\n \"utf32_swedish_ci\",\n \"utf32_turkish_ci\",\n \"utf32_czech_ci\",\n \"utf32_danish_ci\",\n \"utf32_lithuanian_ci\",\n \"utf32_slovak_ci\",\n \"utf32_spanish2_ci\",\n \"utf32_roman_ci\",\n \"utf32_persian_ci\",\n \"utf32_esperanto_ci\",\n \"utf32_hungarian_ci\",\n \"utf32_sinhala_ci\",\n \"utf32_german2_ci\",\n \"utf32_croatian_ci\",\n \"utf32_unicode_520_ci\",\n \"utf32_vietnamese_ci\"],\n \"binary\": [\"binary\"],\n \"geostd8\": [\"geostd8_general_ci\", \"geostd8_bin\"],\n \"cp932\": [\"cp932_japanese_ci\", \"cp932_bin\"],\n \"eucjpms\": [\"eucjpms_japanese_ci\", \"eucjpms_bin\"],\n \"gb18030\": [\"gb18030_chinese_ci\",\n \"gb18030_bin\",\n \"gb18030_unicode_520_ci\"]}\n\ncollation = {\"big5_chinese_ci\": \"big5\",\n \"big5_bin\": \"big5\",\n \"dec8_swedish_ci\": \"dec8\",\n \"dec8_bin\": \"dec8\",\n \"cp850_general_ci\": \"cp850\",\n \"cp850_bin\": \"cp850\",\n \"hp8_english_ci\": \"hp8\",\n \"hp8_bin\": \"hp8\",\n \"koi8r_general_ci\": \"koi8r\",\n \"koi8r_bin\": \"koi8r\",\n \"latin1_german1_ci\": \"latin1\",\n \"latin1_swedish_ci\": \"latin1\",\n \"latin1_danish_ci\": \"latin1\",\n \"latin1_german2_ci\": \"latin1\",\n \"latin1_bin\": \"latin1\",\n \"latin1_general_ci\": \"latin1\",\n \"latin1_general_cs\": \"latin1\",\n \"latin1_spanish_ci\": \"latin1\",\n \"latin2_czech_cs\": \"latin2\",\n \"latin2_general_ci\": \"latin2\",\n \"latin2_hungarian_ci\": \"latin2\",\n \"latin2_croatian_ci\": \"latin2\",\n \"latin2_bin\": \"latin2\",\n \"swe7_swedish_ci\": \"swe7\",\n \"swe7_bin\": \"swe7\",\n \"ascii_general_ci\": \"ascii\",\n \"ascii_bin\": \"ascii\",\n \"ujis_japanese_ci\": \"ujis\",\n \"ujis_bin\": \"ujis\",\n \"sjis_japanese_ci\": \"sjis\",\n \"sjis_bin\": \"sjis\",\n \"hebrew_general_ci\": \"hebrew\",\n \"hebrew_bin\": \"hebrew\",\n \"tis620_thai_ci\": \"tis620\",\n \"tis620_bin\": \"tis620\",\n \"euckr_korean_ci\": \"euckr\",\n \"euckr_bin\": \"euckr\",\n \"koi8u_general_ci\": \"koi8u\",\n \"koi8u_bin\": \"koi8u\",\n \"gb2312_chinese_ci\": \"gb2312\",\n \"gb2312_bin\": \"gb2312\",\n \"greek_general_ci\": \"greek\",\n \"greek_bin\": \"greek\",\n \"cp1250_general_ci\": \"cp1250\",\n \"cp1250_czech_cs\": \"cp1250\",\n \"cp1250_croatian_ci\": \"cp1250\",\n \"cp1250_bin\": \"cp1250\",\n \"cp1250_polish_ci\": \"cp1250\",\n \"gbk_chinese_ci\": \"gbk\",\n \"gbk_bin\": \"gbk\",\n \"latin5_turkish_ci\": \"latin5\",\n \"latin5_bin\": \"latin5\",\n \"armscii8_general_ci\": \"armscii8\",\n \"armscii8_bin\": \"armscii8\",\n \"utf8_general_ci\": \"utf8\",\n \"utf8mb3_general_ci\": \"utf8mb3\",\n \"utf8_bin\": \"utf8\",\n \"utf8_unicode_ci\": \"utf8\",\n \"utf8_icelandic_ci\": \"utf8\",\n \"utf8_latvian_ci\": \"utf8\",\n \"utf8_romanian_ci\": \"utf8\",\n \"utf8_slovenian_ci\": \"utf8\",\n \"utf8_polish_ci\": \"utf8\",\n \"utf8_estonian_ci\": \"utf8\",\n \"utf8_spanish_ci\": \"utf8\",\n \"utf8_swedish_ci\": \"utf8\",\n \"utf8_turkish_ci\": \"utf8\",\n \"utf8_czech_ci\": \"utf8\",\n \"utf8_danish_ci\": \"utf8\",\n \"utf8_lithuanian_ci\": \"utf8\",\n \"utf8_slovak_ci\": \"utf8\",\n \"utf8_spanish2_ci\": \"utf8\",\n \"utf8_roman_ci\": \"utf8\",\n \"utf8_persian_ci\": \"utf8\",\n \"utf8_esperanto_ci\": \"utf8\",\n \"utf8_hungarian_ci\": \"utf8\",\n \"utf8_sinhala_ci\": \"utf8\",\n \"utf8_german2_ci\": \"utf8\",\n \"utf8_croatian_ci\": \"utf8\",\n \"utf8_unicode_520_ci\": \"utf8\",\n \"utf8_vietnamese_ci\": \"utf8\",\n \"utf8_general_mysql500_ci\": \"utf8\",\n \"utf8mb4_0900_ai_ci\": \"utf8mb4\",\n \"ucs2_general_ci\": \"ucs2\",\n \"ucs2_bin\": \"ucs2\",\n \"ucs2_unicode_ci\": \"ucs2\",\n \"ucs2_icelandic_ci\": \"ucs2\",\n \"ucs2_latvian_ci\": \"ucs2\",\n \"ucs2_romanian_ci\": \"ucs2\",\n \"ucs2_slovenian_ci\": \"ucs2\",\n \"ucs2_polish_ci\": \"ucs2\",\n \"ucs2_estonian_ci\": \"ucs2\",\n \"ucs2_spanish_ci\": \"ucs2\",\n \"ucs2_swedish_ci\": \"ucs2\",\n \"ucs2_turkish_ci\": \"ucs2\",\n \"ucs2_czech_ci\": \"ucs2\",\n \"ucs2_danish_ci\": \"ucs2\",\n \"ucs2_lithuanian_ci\": \"ucs2\",\n \"ucs2_slovak_ci\": \"ucs2\",\n \"ucs2_spanish2_ci\": \"ucs2\",\n \"ucs2_roman_ci\": \"ucs2\",\n \"ucs2_persian_ci\": \"ucs2\",\n \"ucs2_esperanto_ci\": \"ucs2\",\n \"ucs2_hungarian_ci\": \"ucs2\",\n \"ucs2_sinhala_ci\": \"ucs2\",\n \"ucs2_german2_ci\": \"ucs2\",\n \"ucs2_croatian_ci\": \"ucs2\",\n \"ucs2_unicode_520_ci\": \"ucs2\",\n \"ucs2_vietnamese_ci\": \"ucs2\",\n \"ucs2_general_mysql500_ci\": \"ucs2\",\n \"cp866_general_ci\": \"cp866\",\n \"cp866_bin\": \"cp866\",\n \"keybcs2_general_ci\": \"keybcs2\",\n \"keybcs2_bin\": \"keybcs2\",\n \"macce_general_ci\": \"macce\",\n \"macce_bin\": \"macce\",\n \"macroman_general_ci\": \"macroman\",\n \"macroman_bin\": \"macroman\",\n \"cp852_general_ci\": \"cp852\",\n \"cp852_bin\": \"cp852\",\n \"latin7_estonian_cs\": \"latin7\",\n \"latin7_general_ci\": \"latin7\",\n \"latin7_general_cs\": \"latin7\",\n \"latin7_bin\": \"latin7\",\n \"utf8mb4_general_ci\": \"utf8mb4\",\n \"utf8mb4_bin\": \"utf8mb4\",\n \"utf8mb4_unicode_ci\": \"utf8mb4\",\n \"utf8mb4_icelandic_ci\": \"utf8mb4\",\n \"utf8mb4_latvian_ci\": \"utf8mb4\",\n \"utf8mb4_romanian_ci\": \"utf8mb4\",\n \"utf8mb4_slovenian_ci\": \"utf8mb4\",\n \"utf8mb4_polish_ci\": \"utf8mb4\",\n \"utf8mb4_estonian_ci\": \"utf8mb4\",\n \"utf8mb4_spanish_ci\": \"utf8mb4\",\n \"utf8mb4_swedish_ci\": \"utf8mb4\",\n \"utf8mb4_turkish_ci\": \"utf8mb4\",\n \"utf8mb4_czech_ci\": \"utf8mb4\",\n \"utf8mb4_danish_ci\": \"utf8mb4\",\n \"utf8mb4_lithuanian_ci\": \"utf8mb4\",\n \"utf8mb4_slovak_ci\": \"utf8mb4\",\n \"utf8mb4_spanish2_ci\": \"utf8mb4\",\n \"utf8mb4_roman_ci\": \"utf8mb4\",\n \"utf8mb4_persian_ci\": \"utf8mb4\",\n \"utf8mb4_esperanto_ci\": \"utf8mb4\",\n \"utf8mb4_hungarian_ci\": \"utf8mb4\",\n \"utf8mb4_sinhala_ci\": \"utf8mb4\",\n \"utf8mb4_german2_ci\": \"utf8mb4\",\n \"utf8mb4_croatian_ci\": \"utf8mb4\",\n \"utf8mb4_unicode_520_ci\": \"utf8mb4\",\n \"utf8mb4_vietnamese_ci\": \"utf8mb4\",\n \"cp1251_bulgarian_ci\": \"cp1251\",\n \"cp1251_ukrainian_ci\": \"cp1251\",\n \"cp1251_bin\": \"cp1251\",\n \"cp1251_general_ci\": \"cp1251\",\n \"cp1251_general_cs\": \"cp1251\",\n \"utf16_general_ci\": \"utf16\",\n \"utf16_bin\": \"utf16\",\n \"utf16_unicode_ci\": \"utf16\",\n \"utf16_icelandic_ci\": \"utf16\",\n \"utf16_latvian_ci\": \"utf16\",\n \"utf16_romanian_ci\": \"utf16\",\n \"utf16_slovenian_ci\": \"utf16\",\n \"utf16_polish_ci\": \"utf16\",\n \"utf16_estonian_ci\": \"utf16\",\n \"utf16_spanish_ci\": \"utf16\",\n \"utf16_swedish_ci\": \"utf16\",\n \"utf16_turkish_ci\": \"utf16\",\n \"utf16_czech_ci\": \"utf16\",\n \"utf16_danish_ci\": \"utf16\",\n \"utf16_lithuanian_ci\": \"utf16\",\n \"utf16_slovak_ci\": \"utf16\",\n \"utf16_spanish2_ci\": \"utf16\",\n \"utf16_roman_ci\": \"utf16\",\n \"utf16_persian_ci\": \"utf16\",\n \"utf16_esperanto_ci\": \"utf16\",\n \"utf16_hungarian_ci\": \"utf16\",\n \"utf16_sinhala_ci\": \"utf16\",\n \"utf16_german2_ci\": \"utf16\",\n \"utf16_croatian_ci\": \"utf16\",\n \"utf16_unicode_520_ci\": \"utf16\",\n \"utf16_vietnamese_ci\": \"utf16\",\n \"utf16le_general_ci\": \"utf16le\",\n \"utf16le_bin\": \"utf16le\",\n \"cp1256_general_ci\": \"cp1256\",\n \"cp1256_bin\": \"cp1256\",\n \"cp1257_lithuanian_ci\": \"cp1257\",\n \"cp1257_bin\": \"cp1257\",\n \"cp1257_general_ci\": \"cp1257\",\n \"utf32_general_ci\": \"utf32\",\n \"utf32_bin\": \"utf32\",\n \"utf32_unicode_ci\": \"utf32\",\n \"utf32_icelandic_ci\": \"utf32\",\n \"utf32_latvian_ci\": \"utf32\",\n \"utf32_romanian_ci\": \"utf32\",\n \"utf32_slovenian_ci\": \"utf32\",\n \"utf32_polish_ci\": \"utf32\",\n \"utf32_estonian_ci\": \"utf32\",\n \"utf32_spanish_ci\": \"utf32\",\n \"utf32_swedish_ci\": \"utf32\",\n \"utf32_turkish_ci\": \"utf32\",\n \"utf32_czech_ci\": \"utf32\",\n \"utf32_danish_ci\": \"utf32\",\n \"utf32_lithuanian_ci\": \"utf32\",\n \"utf32_slovak_ci\": \"utf32\",\n \"utf32_spanish2_ci\": \"utf32\",\n \"utf32_roman_ci\": \"utf32\",\n \"utf32_persian_ci\": \"utf32\",\n \"utf32_esperanto_ci\": \"utf32\",\n \"utf32_hungarian_ci\": \"utf32\",\n \"utf32_sinhala_ci\": \"utf32\",\n \"utf32_german2_ci\": \"utf32\",\n \"utf32_croatian_ci\": \"utf32\",\n \"utf32_unicode_520_ci\": \"utf32\",\n \"utf32_vietnamese_ci\": \"utf32\",\n \"binary\": \"binary\",\n \"geostd8_general_ci\": \"geostd8\",\n \"geostd8_bin\": \"geostd8\",\n \"cp932_japanese_ci\": \"cp932\",\n \"cp932_bin\": \"cp932\",\n \"eucjpms_japanese_ci\": \"eucjpms\",\n \"eucjpms_bin\": \"eucjpms\",\n \"gb18030_chinese_ci\": \"gb18030\",\n \"gb18030_bin\": \"gb18030\",\n \"gb18030_unicode_520_ci\": \"gb18030\"}\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
#coding=utf-8
'''
Created on 2013-3-28
@author: jemmy
'''
import telnetlib
import getpass
import sys
import os
import time
import xlrd
from pyExcelerator import *
import
#define
Host = "192.168.0.1"
Port = "70001"
#Host = raw_iput("IP",)
username = "admin"
password = "admin"
filename = str(time.strftime('%Y%m%d%H%M%S'))
def telnet():
# product:
tn = telnetlib.Telnet(Host)
telnetlib.Telnet(Host, Port)
tn.read_until("Login: ")
tn.write(username + "\n")
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("meminfo \n")
tn.write("sh \n")
tn.write("cat /proc/meminfo \n")
tn.write("mpstat -P ALL \n")
tn.write("date \n")
tn.write("exit \n")
tn.write("exit \n")
return tn.read_all()
telnet()
time.sleep(5)
#define
def getlog(s):
print "getlog!---------------------------------------"
f = open('/home/' + filename, 'a')
f.write(s)
f.close()
#define
for i in range(1, 10000000):
print i
telnet()
log = str(telnet())
getlog(log)
time.sleep(5)
|
normal
|
{
"blob_id": "153c02585e5d536616ec4b69757328803ac2fb71",
"index": 3394,
"step-1": "#coding=utf-8\n'''\nCreated on 2013-3-28\n\n@author: jemmy\n'''\nimport telnetlib\nimport getpass\nimport sys\nimport os\nimport time\nimport xlrd\nfrom pyExcelerator import *\nimport\n#define\nHost = \"192.168.0.1\"\nPort = \"70001\"\n#Host = raw_iput(\"IP\",)\nusername = \"admin\"\npassword = \"admin\"\n\nfilename = str(time.strftime('%Y%m%d%H%M%S'))\n\n\ndef telnet():\n# product:\n tn = telnetlib.Telnet(Host)\n telnetlib.Telnet(Host, Port)\n tn.read_until(\"Login: \")\n tn.write(username + \"\\n\")\n tn.read_until(\"Password: \")\n tn.write(password + \"\\n\")\n tn.write(\"meminfo \\n\")\n tn.write(\"sh \\n\")\n tn.write(\"cat /proc/meminfo \\n\")\n tn.write(\"mpstat -P ALL \\n\")\n tn.write(\"date \\n\")\n tn.write(\"exit \\n\")\n tn.write(\"exit \\n\")\n return tn.read_all()\n\n\ntelnet()\ntime.sleep(5)\n\n#define \ndef getlog(s):\n print \"getlog!---------------------------------------\"\n f = open('/home/' + filename, 'a')\n f.write(s)\n f.close()\n\n#define\nfor i in range(1, 10000000):\n print i\n telnet()\n log = str(telnet())\n getlog(log)\n time.sleep(5)",
"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|>
class Map(BaseCommand):
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Map(BaseCommand):
def run(self):
from lib.models import Mapping
from lib.models import Migration
migration = Migration.load(self.options['MIGRATION_FILE'])
mapping = Mapping(self.options)
migration.mappings.append(mapping)
migration.write()
<|reserved_special_token_1|>
<|reserved_special_token_0|>
from json import dumps
from .base_command import BaseCommand
class Map(BaseCommand):
def run(self):
from lib.models import Mapping
from lib.models import Migration
migration = Migration.load(self.options['MIGRATION_FILE'])
mapping = Mapping(self.options)
migration.mappings.append(mapping)
migration.write()
<|reserved_special_token_1|>
"""
commands/map.py
description:
Generates a blank configuration file in the current directory
"""
from json import dumps
from .base_command import BaseCommand
class Map(BaseCommand):
def run(self):
from lib.models import Mapping
from lib.models import Migration
migration = Migration.load(self.options['MIGRATION_FILE'])
mapping = Mapping(self.options)
migration.mappings.append(mapping)
migration.write()
|
flexible
|
{
"blob_id": "07783921da2fb4ae9452324f833b08b3f92ba294",
"index": 546,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Map(BaseCommand):\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Map(BaseCommand):\n\n def run(self):\n from lib.models import Mapping\n from lib.models import Migration\n migration = Migration.load(self.options['MIGRATION_FILE'])\n mapping = Mapping(self.options)\n migration.mappings.append(mapping)\n migration.write()\n",
"step-4": "<mask token>\nfrom json import dumps\nfrom .base_command import BaseCommand\n\n\nclass Map(BaseCommand):\n\n def run(self):\n from lib.models import Mapping\n from lib.models import Migration\n migration = Migration.load(self.options['MIGRATION_FILE'])\n mapping = Mapping(self.options)\n migration.mappings.append(mapping)\n migration.write()\n",
"step-5": "\"\"\"\n\ncommands/map.py\n\ndescription:\n\tGenerates a blank configuration file in the current directory\n\n\"\"\"\n\nfrom json import dumps\nfrom .base_command import BaseCommand\n\nclass Map(BaseCommand):\n\tdef run(self):\n\t\tfrom lib.models import Mapping\n\t\tfrom lib.models import Migration\n\n\t\tmigration = Migration.load(self.options['MIGRATION_FILE'])\n\n\t\tmapping = Mapping(self.options)\n\n\t\tmigration.mappings.append(mapping)\n\n\t\tmigration.write()",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import urllib2
#this is executed by a cron job on the pi inside the pooltable
secret ='secret'
baseurl='https://pooltable.mysite.com/'
url = baseurl + 'gettrans.php?secret=' + secret
req = urllib2.Request(url)
f = urllib2.urlopen(req)
response = f.read()
f.close()
print response
#check if there is a transaction
if response != 'error' and response != 'false' and response != False:
obj = json.loads(response)
trans = str(obj['transaction_hash'])
#move the transaction to the processed table and delete from unprocessed
url = baseurl + 'deltrans.php?secret=' + secret + '&trans=' + trans
req = urllib2.Request(url)
f = urllib2.urlopen(req)
response = f.read()
f.close()
#if transaction was moved correctly, set off the solanoid
if response == '*ok*':
print response
#run solanoid script
|
normal
|
{
"blob_id": "9baf55eb2fb70e9fa0d92df22d307962b8d6c6d4",
"index": 5883,
"step-1": "#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\n\r\nimport json\r\nimport urllib2\r\n#this is executed by a cron job on the pi inside the pooltable\r\nsecret ='secret'\r\nbaseurl='https://pooltable.mysite.com/'\r\nurl = baseurl + 'gettrans.php?secret=' + secret\r\nreq = urllib2.Request(url)\r\nf = urllib2.urlopen(req)\r\nresponse = f.read()\r\nf.close()\r\nprint response\r\n#check if there is a transaction\r\nif response != 'error' and response != 'false' and response != False:\r\n obj = json.loads(response)\r\n trans = str(obj['transaction_hash'])\r\n#move the transaction to the processed table and delete from unprocessed\r\n url = baseurl + 'deltrans.php?secret=' + secret + '&trans=' + trans \r\n req = urllib2.Request(url)\r\n f = urllib2.urlopen(req)\r\n response = f.read()\r\n f.close()\r\n#if transaction was moved correctly, set off the solanoid\r\n if response == '*ok*':\r\n print response\r\n #run solanoid script\r\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|>
bind = '0.0.0.0:8000'
workers = os.environ['GET_KEYS_ACCOUNTS_WORKERS']
<|reserved_special_token_1|>
import os
bind = '0.0.0.0:8000'
workers = os.environ['GET_KEYS_ACCOUNTS_WORKERS']
|
flexible
|
{
"blob_id": "d84a7e16471c604283c81412653e037ecdb19102",
"index": 3530,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nbind = '0.0.0.0:8000'\nworkers = os.environ['GET_KEYS_ACCOUNTS_WORKERS']\n",
"step-3": "import os\nbind = '0.0.0.0:8000'\nworkers = os.environ['GET_KEYS_ACCOUNTS_WORKERS']\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
<|reserved_special_token_0|>
@api.route('/get/<key_name>', methods=['GET'])
def get(key_name):
li = db_handle(key_name)
if li[1] is None:
abort(404)
else:
result = matchtyper(li)
return make_response(jsonify(result))
@api.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
@api.route('/get/<key_name>', methods=['GET'])
def get(key_name):
li = db_handle(key_name)
if li[1] is None:
abort(404)
else:
result = matchtyper(li)
return make_response(jsonify(result))
@api.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
if __name__ == '__main__':
api.debug = True
api.run(host='localhost', port=8080)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
api = Flask(__name__)
@api.route('/get/<key_name>', methods=['GET'])
def get(key_name):
li = db_handle(key_name)
if li[1] is None:
abort(404)
else:
result = matchtyper(li)
return make_response(jsonify(result))
@api.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
if __name__ == '__main__':
api.debug = True
api.run(host='localhost', port=8080)
<|reserved_special_token_1|>
from flask import Flask, jsonify, abort, make_response
from matchtype import matchtyper
from db import db_handle
import sys
api = Flask(__name__)
@api.route('/get/<key_name>', methods=['GET'])
def get(key_name):
li = db_handle(key_name)
if li[1] is None:
abort(404)
else:
result = matchtyper(li)
return make_response(jsonify(result))
@api.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
if __name__ == '__main__':
api.debug = True
api.run(host='localhost', port=8080)
|
flexible
|
{
"blob_id": "44e9fd355bfab3f007c5428e8a5f0930c4011646",
"index": 3853,
"step-1": "<mask token>\n\n\n@api.route('/get/<key_name>', methods=['GET'])\ndef get(key_name):\n li = db_handle(key_name)\n if li[1] is None:\n abort(404)\n else:\n result = matchtyper(li)\n return make_response(jsonify(result))\n\n\n@api.errorhandler(404)\ndef not_found(error):\n return make_response(jsonify({'error': 'Not found'}), 404)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\n@api.route('/get/<key_name>', methods=['GET'])\ndef get(key_name):\n li = db_handle(key_name)\n if li[1] is None:\n abort(404)\n else:\n result = matchtyper(li)\n return make_response(jsonify(result))\n\n\n@api.errorhandler(404)\ndef not_found(error):\n return make_response(jsonify({'error': 'Not found'}), 404)\n\n\nif __name__ == '__main__':\n api.debug = True\n api.run(host='localhost', port=8080)\n",
"step-3": "<mask token>\napi = Flask(__name__)\n\n\n@api.route('/get/<key_name>', methods=['GET'])\ndef get(key_name):\n li = db_handle(key_name)\n if li[1] is None:\n abort(404)\n else:\n result = matchtyper(li)\n return make_response(jsonify(result))\n\n\n@api.errorhandler(404)\ndef not_found(error):\n return make_response(jsonify({'error': 'Not found'}), 404)\n\n\nif __name__ == '__main__':\n api.debug = True\n api.run(host='localhost', port=8080)\n",
"step-4": "from flask import Flask, jsonify, abort, make_response\nfrom matchtype import matchtyper\nfrom db import db_handle\nimport sys\napi = Flask(__name__)\n\n\n@api.route('/get/<key_name>', methods=['GET'])\ndef get(key_name):\n li = db_handle(key_name)\n if li[1] is None:\n abort(404)\n else:\n result = matchtyper(li)\n return make_response(jsonify(result))\n\n\n@api.errorhandler(404)\ndef not_found(error):\n return make_response(jsonify({'error': 'Not found'}), 404)\n\n\nif __name__ == '__main__':\n api.debug = True\n api.run(host='localhost', port=8080)\n",
"step-5": null,
"step-ids": [
2,
3,
4,
5
]
}
|
[
2,
3,
4,
5
] |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('courses', '0015_auto_20151216_1136'),
]
operations = [
migrations.AlterField(
model_name='duration',
name='duration',
field=models.DecimalField(default=60, verbose_name='duration', max_digits=10, decimal_places=0),
),
]
|
normal
|
{
"blob_id": "0cba18ca7126dda548a09f34dc26b83d6471bf68",
"index": 1652,
"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 = [('courses', '0015_auto_20151216_1136')]\n operations = [migrations.AlterField(model_name='duration', name=\n 'duration', field=models.DecimalField(default=60, verbose_name=\n 'duration', max_digits=10, decimal_places=0))]\n",
"step-4": "from __future__ import unicode_literals\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('courses', '0015_auto_20151216_1136')]\n operations = [migrations.AlterField(model_name='duration', name=\n 'duration', field=models.DecimalField(default=60, verbose_name=\n 'duration', max_digits=10, decimal_places=0))]\n",
"step-5": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('courses', '0015_auto_20151216_1136'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='duration',\n name='duration',\n field=models.DecimalField(default=60, verbose_name='duration', max_digits=10, decimal_places=0),\n ),\n ]\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
n=int(0)
import random
def doubleEven(n):
if n % 2 == 0:
n = n*2
return (n)
else:
return "-1"
print(doubleEven(n = int(input("put in a number"))))
g=int(0)
def grade(g):
if g < 50:
return "F"
if g < 66:
return "C"
if g > 92:
return "A+"
else:
print("error")
print(grade(g = int(input("put in your percent"))))
num1 = 0
num2 = 0
num3 = 0
def largestNum(num1, num2, num3):
num1 = int(input("input number 1"))
num2 = int(input("input number 2"))
num3 = int(input("input number 3"))
if num1 > num2:
if num1 > num3:
return num1
if num3 > num1:
return num3
if num2 > num3:
return num2
if num3 > num2:
return num3
print(largestNum(10, 20, 30))
def sumDice(Dice, numRolls):
|
normal
|
{
"blob_id": "5251724656e1d971900fff3d8fa0210c6cfc27bb",
"index": 5505,
"step-1": "n=int(0)\nimport random\ndef doubleEven(n):\n if n % 2 == 0:\n n = n*2\n return (n)\n else:\n return \"-1\"\n\n\nprint(doubleEven(n = int(input(\"put in a number\"))))\n\ng=int(0)\n\ndef grade(g):\n if g < 50:\n return \"F\"\n if g < 66:\n return \"C\"\n if g > 92:\n return \"A+\"\n\n else:\n print(\"error\")\n\n\nprint(grade(g = int(input(\"put in your percent\"))))\n\nnum1 = 0\nnum2 = 0\nnum3 = 0\n\ndef largestNum(num1, num2, num3):\n num1 = int(input(\"input number 1\"))\n num2 = int(input(\"input number 2\"))\n num3 = int(input(\"input number 3\"))\n if num1 > num2:\n if num1 > num3:\n return num1\n if num3 > num1:\n return num3\n if num2 > num3:\n return num2\n if num3 > num2:\n return num3\n\n\nprint(largestNum(10, 20, 30))\n\n\ndef sumDice(Dice, numRolls):",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
<|reserved_special_token_0|>
class Game(object):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def render_field(self):
"""Метод отрисовки поля"""
print(tabulate.tabulate(self.rendered_field, tablefmt='grid'))
def check_free_place(self, i, j):
"""Метод проверки клетки на занятость"""
return self.field[i][j] == -10
<|reserved_special_token_0|>
@staticmethod
def validate_number(number):
"""Метод проверки номера клеточки"""
if not isinstance(number, str):
return 'TypeError'
try:
value = int(number)
except ValueError:
return 'Error'
except TypeError:
return 'Error'
except ZeroDivisionError:
return 'Error'
else:
if value < 1 or value > 9:
return 'Error'
return value
<|reserved_special_token_0|>
def game_logic(self):
"""Метод реализации игровой логики"""
symbols = 'X', 'O'
move_counter = 0
start = True
while not self.check_win() and move_counter != 9 or start:
start = False
num_for_validation = input(
'Введите номер клеточки, куда поставить {}\n'.format(
symbols[move_counter % 2]))
number = Game.validate_number(num_for_validation)
if number == 'Error':
print('Да введите число от 1 до 9, сложно что ли?')
else:
our_index = number - 1
index = our_index // 3, our_index % 3
if not self.check_free_place(index[0], index[1]):
print(
'Эта клеточка уже занята, пожалуйста, посмотрите другие варианты'
)
else:
self.field[index[0]][index[1]] = move_counter % 2 + 1
self.rendered_field[index[0]][index[1]] = symbols[
move_counter % 2]
move_counter += 1
print('Ситуация на поле боя: (ходов произведено {})'.
format(move_counter))
self.render_field()
print('Окончание игры')
if not self.check_win() and move_counter == 9:
print('Это ничья. Но это ожидаемый результат')
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Game(object):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def render_field(self):
"""Метод отрисовки поля"""
print(tabulate.tabulate(self.rendered_field, tablefmt='grid'))
def check_free_place(self, i, j):
"""Метод проверки клетки на занятость"""
return self.field[i][j] == -10
<|reserved_special_token_0|>
@staticmethod
def validate_number(number):
"""Метод проверки номера клеточки"""
if not isinstance(number, str):
return 'TypeError'
try:
value = int(number)
except ValueError:
return 'Error'
except TypeError:
return 'Error'
except ZeroDivisionError:
return 'Error'
else:
if value < 1 or value > 9:
return 'Error'
return value
def main(self):
"""Метод main()"""
print("Приветствую вас в игре 'крестики-нолики'")
answer = True
while answer:
self.render_field()
self.game_logic()
answer = None
while answer is None:
print(
"Хотите ли продолжить игровой сеанс? 'y(д)' - да, 'n(н)' - нет"
)
str_answer = input().lower()
answer = (True if str_answer == 'y' or str_answer == 'д' else
False if str_answer == 'n' or str_answer == 'н' else None)
def game_logic(self):
"""Метод реализации игровой логики"""
symbols = 'X', 'O'
move_counter = 0
start = True
while not self.check_win() and move_counter != 9 or start:
start = False
num_for_validation = input(
'Введите номер клеточки, куда поставить {}\n'.format(
symbols[move_counter % 2]))
number = Game.validate_number(num_for_validation)
if number == 'Error':
print('Да введите число от 1 до 9, сложно что ли?')
else:
our_index = number - 1
index = our_index // 3, our_index % 3
if not self.check_free_place(index[0], index[1]):
print(
'Эта клеточка уже занята, пожалуйста, посмотрите другие варианты'
)
else:
self.field[index[0]][index[1]] = move_counter % 2 + 1
self.rendered_field[index[0]][index[1]] = symbols[
move_counter % 2]
move_counter += 1
print('Ситуация на поле боя: (ходов произведено {})'.
format(move_counter))
self.render_field()
print('Окончание игры')
if not self.check_win() and move_counter == 9:
print('Это ничья. Но это ожидаемый результат')
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Game(object):
"""Класс игры"""
def __init__(self):
self.field = numpy.array([(-10, -10, -10), (-10, -10, -10), (-10, -
10, -10)])
self.rendered_field = [['-', '-', '-'], ['-', '-', '-'], ['-', '-',
'-']]
def render_field(self):
"""Метод отрисовки поля"""
print(tabulate.tabulate(self.rendered_field, tablefmt='grid'))
def check_free_place(self, i, j):
"""Метод проверки клетки на занятость"""
return self.field[i][j] == -10
def check_win(self):
"""Метод проверки на чью-либо победу"""
return any(summa % 3 == 0 and summa > 0 for summa in list(chain(*[
tuple(list(self.field.sum(axis=0))), tuple(list(self.field.sum(
axis=1))), (sum(self.field.diagonal()), sum(numpy.fliplr(self.
field).diagonal()))])))
@staticmethod
def validate_number(number):
"""Метод проверки номера клеточки"""
if not isinstance(number, str):
return 'TypeError'
try:
value = int(number)
except ValueError:
return 'Error'
except TypeError:
return 'Error'
except ZeroDivisionError:
return 'Error'
else:
if value < 1 or value > 9:
return 'Error'
return value
def main(self):
"""Метод main()"""
print("Приветствую вас в игре 'крестики-нолики'")
answer = True
while answer:
self.render_field()
self.game_logic()
answer = None
while answer is None:
print(
"Хотите ли продолжить игровой сеанс? 'y(д)' - да, 'n(н)' - нет"
)
str_answer = input().lower()
answer = (True if str_answer == 'y' or str_answer == 'д' else
False if str_answer == 'n' or str_answer == 'н' else None)
def game_logic(self):
"""Метод реализации игровой логики"""
symbols = 'X', 'O'
move_counter = 0
start = True
while not self.check_win() and move_counter != 9 or start:
start = False
num_for_validation = input(
'Введите номер клеточки, куда поставить {}\n'.format(
symbols[move_counter % 2]))
number = Game.validate_number(num_for_validation)
if number == 'Error':
print('Да введите число от 1 до 9, сложно что ли?')
else:
our_index = number - 1
index = our_index // 3, our_index % 3
if not self.check_free_place(index[0], index[1]):
print(
'Эта клеточка уже занята, пожалуйста, посмотрите другие варианты'
)
else:
self.field[index[0]][index[1]] = move_counter % 2 + 1
self.rendered_field[index[0]][index[1]] = symbols[
move_counter % 2]
move_counter += 1
print('Ситуация на поле боя: (ходов произведено {})'.
format(move_counter))
self.render_field()
print('Окончание игры')
if not self.check_win() and move_counter == 9:
print('Это ничья. Но это ожидаемый результат')
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
from __future__ import print_function
from itertools import chain
import tabulate
import numpy
class Game(object):
"""Класс игры"""
def __init__(self):
self.field = numpy.array([(-10, -10, -10), (-10, -10, -10), (-10, -
10, -10)])
self.rendered_field = [['-', '-', '-'], ['-', '-', '-'], ['-', '-',
'-']]
def render_field(self):
"""Метод отрисовки поля"""
print(tabulate.tabulate(self.rendered_field, tablefmt='grid'))
def check_free_place(self, i, j):
"""Метод проверки клетки на занятость"""
return self.field[i][j] == -10
def check_win(self):
"""Метод проверки на чью-либо победу"""
return any(summa % 3 == 0 and summa > 0 for summa in list(chain(*[
tuple(list(self.field.sum(axis=0))), tuple(list(self.field.sum(
axis=1))), (sum(self.field.diagonal()), sum(numpy.fliplr(self.
field).diagonal()))])))
@staticmethod
def validate_number(number):
"""Метод проверки номера клеточки"""
if not isinstance(number, str):
return 'TypeError'
try:
value = int(number)
except ValueError:
return 'Error'
except TypeError:
return 'Error'
except ZeroDivisionError:
return 'Error'
else:
if value < 1 or value > 9:
return 'Error'
return value
def main(self):
"""Метод main()"""
print("Приветствую вас в игре 'крестики-нолики'")
answer = True
while answer:
self.render_field()
self.game_logic()
answer = None
while answer is None:
print(
"Хотите ли продолжить игровой сеанс? 'y(д)' - да, 'n(н)' - нет"
)
str_answer = input().lower()
answer = (True if str_answer == 'y' or str_answer == 'д' else
False if str_answer == 'n' or str_answer == 'н' else None)
def game_logic(self):
"""Метод реализации игровой логики"""
symbols = 'X', 'O'
move_counter = 0
start = True
while not self.check_win() and move_counter != 9 or start:
start = False
num_for_validation = input(
'Введите номер клеточки, куда поставить {}\n'.format(
symbols[move_counter % 2]))
number = Game.validate_number(num_for_validation)
if number == 'Error':
print('Да введите число от 1 до 9, сложно что ли?')
else:
our_index = number - 1
index = our_index // 3, our_index % 3
if not self.check_free_place(index[0], index[1]):
print(
'Эта клеточка уже занята, пожалуйста, посмотрите другие варианты'
)
else:
self.field[index[0]][index[1]] = move_counter % 2 + 1
self.rendered_field[index[0]][index[1]] = symbols[
move_counter % 2]
move_counter += 1
print('Ситуация на поле боя: (ходов произведено {})'.
format(move_counter))
self.render_field()
print('Окончание игры')
if not self.check_win() and move_counter == 9:
print('Это ничья. Но это ожидаемый результат')
if __name__ == '__main__':
a = Game()
a.main()
<|reserved_special_token_1|>
"""Module just for fun game"""
# -*- coding: utf-8 -*-
from __future__ import print_function
from itertools import chain
import tabulate
import numpy
class Game(object):
"""Класс игры"""
def __init__(self):
self.field = numpy.array([(-10, -10, -10), (-10, -10, -10), (-10, -10, -10)])
self.rendered_field = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
def render_field(self):
"""Метод отрисовки поля"""
print(tabulate.tabulate(self.rendered_field, tablefmt='grid'))
def check_free_place(self, i, j):
"""Метод проверки клетки на занятость"""
return self.field[i][j] == -10
def check_win(self):
"""Метод проверки на чью-либо победу"""
return any(summa % 3 == 0 and \
summa > 0 for summa in list(chain(*[tuple(list((self.field.sum(axis=0)))), \
tuple(list((self.field.sum(axis=1)))), (sum(self.field.diagonal()), \
sum(numpy.fliplr(self.field).diagonal()))])))
@staticmethod
def validate_number(number):
"""Метод проверки номера клеточки"""
if not isinstance(number, str):
return 'TypeError'
try:
value = int(number)
except ValueError:
return 'Error'
except TypeError:
return 'Error'
except ZeroDivisionError:
return 'Error'
else:
if (value < 1 or value > 9):
return 'Error'
return value
def main(self):
"""Метод main()"""
print("Приветствую вас в игре 'крестики-нолики'")
answer = True
while answer:
#current_game = Game()
self.render_field()
self.game_logic()
answer = None
while answer is None:
print("Хотите ли продолжить игровой сеанс? 'y(д)' - да, 'n(н)' - нет")
str_answer = input().lower()
answer = True if str_answer == 'y' or str_answer == 'д' else \
(False if str_answer == 'n' or str_answer == 'н' else None)
def game_logic(self):
"""Метод реализации игровой логики"""
symbols = ('X', 'O')
move_counter = 0
start = True
while not self.check_win() and move_counter != 9 or start:
start = False
num_for_validation = input('Введите номер клеточки, куда поставить {}\n' \
.format(symbols[move_counter % 2]))
number = Game.validate_number(num_for_validation)
if number == 'Error':
print('Да введите число от 1 до 9, сложно что ли?')
else:
our_index = number - 1 # у нас же индексы от 1 до 9
index = (our_index // 3, our_index % 3)
if not self.check_free_place(index[0], index[1]):
print('Эта клеточка уже занята, пожалуйста, посмотрите другие варианты')
else:
self.field[index[0]][index[1]] = move_counter % 2 + 1 # 'X' - 1, 'O' - 2
self.rendered_field[index[0]][index[1]] = symbols[move_counter % 2]
move_counter += 1
print('Ситуация на поле боя: (ходов произведено {})'.format(move_counter))
self.render_field()
print('Окончание игры')
if not self.check_win() and move_counter == 9:
print('Это ничья. Но это ожидаемый результат')
if __name__ == '__main__':
a = Game()
a.main()
|
flexible
|
{
"blob_id": "23ba9e498dd153be408e973253d5f2a858d4771b",
"index": 6922,
"step-1": "<mask token>\n\n\nclass Game(object):\n <mask token>\n <mask token>\n\n def render_field(self):\n \"\"\"Метод отрисовки поля\"\"\"\n print(tabulate.tabulate(self.rendered_field, tablefmt='grid'))\n\n def check_free_place(self, i, j):\n \"\"\"Метод проверки клетки на занятость\"\"\"\n return self.field[i][j] == -10\n <mask token>\n\n @staticmethod\n def validate_number(number):\n \"\"\"Метод проверки номера клеточки\"\"\"\n if not isinstance(number, str):\n return 'TypeError'\n try:\n value = int(number)\n except ValueError:\n return 'Error'\n except TypeError:\n return 'Error'\n except ZeroDivisionError:\n return 'Error'\n else:\n if value < 1 or value > 9:\n return 'Error'\n return value\n <mask token>\n\n def game_logic(self):\n \"\"\"Метод реализации игровой логики\"\"\"\n symbols = 'X', 'O'\n move_counter = 0\n start = True\n while not self.check_win() and move_counter != 9 or start:\n start = False\n num_for_validation = input(\n 'Введите номер клеточки, куда поставить {}\\n'.format(\n symbols[move_counter % 2]))\n number = Game.validate_number(num_for_validation)\n if number == 'Error':\n print('Да введите число от 1 до 9, сложно что ли?')\n else:\n our_index = number - 1\n index = our_index // 3, our_index % 3\n if not self.check_free_place(index[0], index[1]):\n print(\n 'Эта клеточка уже занята, пожалуйста, посмотрите другие варианты'\n )\n else:\n self.field[index[0]][index[1]] = move_counter % 2 + 1\n self.rendered_field[index[0]][index[1]] = symbols[\n move_counter % 2]\n move_counter += 1\n print('Ситуация на поле боя: (ходов произведено {})'.\n format(move_counter))\n self.render_field()\n print('Окончание игры')\n if not self.check_win() and move_counter == 9:\n print('Это ничья. Но это ожидаемый результат')\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass Game(object):\n <mask token>\n <mask token>\n\n def render_field(self):\n \"\"\"Метод отрисовки поля\"\"\"\n print(tabulate.tabulate(self.rendered_field, tablefmt='grid'))\n\n def check_free_place(self, i, j):\n \"\"\"Метод проверки клетки на занятость\"\"\"\n return self.field[i][j] == -10\n <mask token>\n\n @staticmethod\n def validate_number(number):\n \"\"\"Метод проверки номера клеточки\"\"\"\n if not isinstance(number, str):\n return 'TypeError'\n try:\n value = int(number)\n except ValueError:\n return 'Error'\n except TypeError:\n return 'Error'\n except ZeroDivisionError:\n return 'Error'\n else:\n if value < 1 or value > 9:\n return 'Error'\n return value\n\n def main(self):\n \"\"\"Метод main()\"\"\"\n print(\"Приветствую вас в игре 'крестики-нолики'\")\n answer = True\n while answer:\n self.render_field()\n self.game_logic()\n answer = None\n while answer is None:\n print(\n \"Хотите ли продолжить игровой сеанс? 'y(д)' - да, 'n(н)' - нет\"\n )\n str_answer = input().lower()\n answer = (True if str_answer == 'y' or str_answer == 'д' else\n False if str_answer == 'n' or str_answer == 'н' else None)\n\n def game_logic(self):\n \"\"\"Метод реализации игровой логики\"\"\"\n symbols = 'X', 'O'\n move_counter = 0\n start = True\n while not self.check_win() and move_counter != 9 or start:\n start = False\n num_for_validation = input(\n 'Введите номер клеточки, куда поставить {}\\n'.format(\n symbols[move_counter % 2]))\n number = Game.validate_number(num_for_validation)\n if number == 'Error':\n print('Да введите число от 1 до 9, сложно что ли?')\n else:\n our_index = number - 1\n index = our_index // 3, our_index % 3\n if not self.check_free_place(index[0], index[1]):\n print(\n 'Эта клеточка уже занята, пожалуйста, посмотрите другие варианты'\n )\n else:\n self.field[index[0]][index[1]] = move_counter % 2 + 1\n self.rendered_field[index[0]][index[1]] = symbols[\n move_counter % 2]\n move_counter += 1\n print('Ситуация на поле боя: (ходов произведено {})'.\n format(move_counter))\n self.render_field()\n print('Окончание игры')\n if not self.check_win() and move_counter == 9:\n print('Это ничья. Но это ожидаемый результат')\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass Game(object):\n \"\"\"Класс игры\"\"\"\n\n def __init__(self):\n self.field = numpy.array([(-10, -10, -10), (-10, -10, -10), (-10, -\n 10, -10)])\n self.rendered_field = [['-', '-', '-'], ['-', '-', '-'], ['-', '-',\n '-']]\n\n def render_field(self):\n \"\"\"Метод отрисовки поля\"\"\"\n print(tabulate.tabulate(self.rendered_field, tablefmt='grid'))\n\n def check_free_place(self, i, j):\n \"\"\"Метод проверки клетки на занятость\"\"\"\n return self.field[i][j] == -10\n\n def check_win(self):\n \"\"\"Метод проверки на чью-либо победу\"\"\"\n return any(summa % 3 == 0 and summa > 0 for summa in list(chain(*[\n tuple(list(self.field.sum(axis=0))), tuple(list(self.field.sum(\n axis=1))), (sum(self.field.diagonal()), sum(numpy.fliplr(self.\n field).diagonal()))])))\n\n @staticmethod\n def validate_number(number):\n \"\"\"Метод проверки номера клеточки\"\"\"\n if not isinstance(number, str):\n return 'TypeError'\n try:\n value = int(number)\n except ValueError:\n return 'Error'\n except TypeError:\n return 'Error'\n except ZeroDivisionError:\n return 'Error'\n else:\n if value < 1 or value > 9:\n return 'Error'\n return value\n\n def main(self):\n \"\"\"Метод main()\"\"\"\n print(\"Приветствую вас в игре 'крестики-нолики'\")\n answer = True\n while answer:\n self.render_field()\n self.game_logic()\n answer = None\n while answer is None:\n print(\n \"Хотите ли продолжить игровой сеанс? 'y(д)' - да, 'n(н)' - нет\"\n )\n str_answer = input().lower()\n answer = (True if str_answer == 'y' or str_answer == 'д' else\n False if str_answer == 'n' or str_answer == 'н' else None)\n\n def game_logic(self):\n \"\"\"Метод реализации игровой логики\"\"\"\n symbols = 'X', 'O'\n move_counter = 0\n start = True\n while not self.check_win() and move_counter != 9 or start:\n start = False\n num_for_validation = input(\n 'Введите номер клеточки, куда поставить {}\\n'.format(\n symbols[move_counter % 2]))\n number = Game.validate_number(num_for_validation)\n if number == 'Error':\n print('Да введите число от 1 до 9, сложно что ли?')\n else:\n our_index = number - 1\n index = our_index // 3, our_index % 3\n if not self.check_free_place(index[0], index[1]):\n print(\n 'Эта клеточка уже занята, пожалуйста, посмотрите другие варианты'\n )\n else:\n self.field[index[0]][index[1]] = move_counter % 2 + 1\n self.rendered_field[index[0]][index[1]] = symbols[\n move_counter % 2]\n move_counter += 1\n print('Ситуация на поле боя: (ходов произведено {})'.\n format(move_counter))\n self.render_field()\n print('Окончание игры')\n if not self.check_win() and move_counter == 9:\n print('Это ничья. Но это ожидаемый результат')\n\n\n<mask token>\n",
"step-4": "<mask token>\nfrom __future__ import print_function\nfrom itertools import chain\nimport tabulate\nimport numpy\n\n\nclass Game(object):\n \"\"\"Класс игры\"\"\"\n\n def __init__(self):\n self.field = numpy.array([(-10, -10, -10), (-10, -10, -10), (-10, -\n 10, -10)])\n self.rendered_field = [['-', '-', '-'], ['-', '-', '-'], ['-', '-',\n '-']]\n\n def render_field(self):\n \"\"\"Метод отрисовки поля\"\"\"\n print(tabulate.tabulate(self.rendered_field, tablefmt='grid'))\n\n def check_free_place(self, i, j):\n \"\"\"Метод проверки клетки на занятость\"\"\"\n return self.field[i][j] == -10\n\n def check_win(self):\n \"\"\"Метод проверки на чью-либо победу\"\"\"\n return any(summa % 3 == 0 and summa > 0 for summa in list(chain(*[\n tuple(list(self.field.sum(axis=0))), tuple(list(self.field.sum(\n axis=1))), (sum(self.field.diagonal()), sum(numpy.fliplr(self.\n field).diagonal()))])))\n\n @staticmethod\n def validate_number(number):\n \"\"\"Метод проверки номера клеточки\"\"\"\n if not isinstance(number, str):\n return 'TypeError'\n try:\n value = int(number)\n except ValueError:\n return 'Error'\n except TypeError:\n return 'Error'\n except ZeroDivisionError:\n return 'Error'\n else:\n if value < 1 or value > 9:\n return 'Error'\n return value\n\n def main(self):\n \"\"\"Метод main()\"\"\"\n print(\"Приветствую вас в игре 'крестики-нолики'\")\n answer = True\n while answer:\n self.render_field()\n self.game_logic()\n answer = None\n while answer is None:\n print(\n \"Хотите ли продолжить игровой сеанс? 'y(д)' - да, 'n(н)' - нет\"\n )\n str_answer = input().lower()\n answer = (True if str_answer == 'y' or str_answer == 'д' else\n False if str_answer == 'n' or str_answer == 'н' else None)\n\n def game_logic(self):\n \"\"\"Метод реализации игровой логики\"\"\"\n symbols = 'X', 'O'\n move_counter = 0\n start = True\n while not self.check_win() and move_counter != 9 or start:\n start = False\n num_for_validation = input(\n 'Введите номер клеточки, куда поставить {}\\n'.format(\n symbols[move_counter % 2]))\n number = Game.validate_number(num_for_validation)\n if number == 'Error':\n print('Да введите число от 1 до 9, сложно что ли?')\n else:\n our_index = number - 1\n index = our_index // 3, our_index % 3\n if not self.check_free_place(index[0], index[1]):\n print(\n 'Эта клеточка уже занята, пожалуйста, посмотрите другие варианты'\n )\n else:\n self.field[index[0]][index[1]] = move_counter % 2 + 1\n self.rendered_field[index[0]][index[1]] = symbols[\n move_counter % 2]\n move_counter += 1\n print('Ситуация на поле боя: (ходов произведено {})'.\n format(move_counter))\n self.render_field()\n print('Окончание игры')\n if not self.check_win() and move_counter == 9:\n print('Это ничья. Но это ожидаемый результат')\n\n\nif __name__ == '__main__':\n a = Game()\n a.main()\n",
"step-5": "\"\"\"Module just for fun game\"\"\"\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nfrom itertools import chain\nimport tabulate\nimport numpy\n\nclass Game(object):\n \"\"\"Класс игры\"\"\"\n def __init__(self):\n self.field = numpy.array([(-10, -10, -10), (-10, -10, -10), (-10, -10, -10)])\n self.rendered_field = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]\n\n def render_field(self):\n \"\"\"Метод отрисовки поля\"\"\"\n print(tabulate.tabulate(self.rendered_field, tablefmt='grid'))\n\n def check_free_place(self, i, j):\n \"\"\"Метод проверки клетки на занятость\"\"\"\n return self.field[i][j] == -10\n\n def check_win(self):\n \"\"\"Метод проверки на чью-либо победу\"\"\"\n return any(summa % 3 == 0 and \\\nsumma > 0 for summa in list(chain(*[tuple(list((self.field.sum(axis=0)))), \\\ntuple(list((self.field.sum(axis=1)))), (sum(self.field.diagonal()), \\\nsum(numpy.fliplr(self.field).diagonal()))])))\n\n @staticmethod\n def validate_number(number):\n \"\"\"Метод проверки номера клеточки\"\"\"\n if not isinstance(number, str):\n return 'TypeError'\n try:\n value = int(number)\n except ValueError:\n return 'Error'\n except TypeError:\n return 'Error'\n except ZeroDivisionError:\n return 'Error'\n else:\n if (value < 1 or value > 9):\n return 'Error'\n return value\n\n def main(self):\n \"\"\"Метод main()\"\"\"\n print(\"Приветствую вас в игре 'крестики-нолики'\")\n answer = True\n while answer:\n #current_game = Game()\n self.render_field()\n self.game_logic()\n answer = None\n while answer is None:\n print(\"Хотите ли продолжить игровой сеанс? 'y(д)' - да, 'n(н)' - нет\")\n str_answer = input().lower()\n answer = True if str_answer == 'y' or str_answer == 'д' else \\\n(False if str_answer == 'n' or str_answer == 'н' else None)\n\n def game_logic(self):\n \"\"\"Метод реализации игровой логики\"\"\"\n symbols = ('X', 'O')\n move_counter = 0\n start = True\n while not self.check_win() and move_counter != 9 or start:\n start = False\n num_for_validation = input('Введите номер клеточки, куда поставить {}\\n' \\\n.format(symbols[move_counter % 2]))\n number = Game.validate_number(num_for_validation)\n if number == 'Error':\n print('Да введите число от 1 до 9, сложно что ли?')\n else:\n our_index = number - 1 # у нас же индексы от 1 до 9\n index = (our_index // 3, our_index % 3)\n if not self.check_free_place(index[0], index[1]):\n print('Эта клеточка уже занята, пожалуйста, посмотрите другие варианты')\n else:\n self.field[index[0]][index[1]] = move_counter % 2 + 1 # 'X' - 1, 'O' - 2\n self.rendered_field[index[0]][index[1]] = symbols[move_counter % 2]\n move_counter += 1\n print('Ситуация на поле боя: (ходов произведено {})'.format(move_counter))\n self.render_field()\n print('Окончание игры')\n if not self.check_win() and move_counter == 9:\n print('Это ничья. Но это ожидаемый результат')\n\nif __name__ == '__main__':\n a = Game()\n a.main()\n",
"step-ids": [
5,
6,
9,
11,
12
]
}
|
[
5,
6,
9,
11,
12
] |
#!/usr/bin/env python
import cgitb
import cgi
import pymysql
form = cgi.FieldStorage()
c.execute("SELECT * FROM example")
recs = c.fetchall()
records1 = """
<body>
<table>
<tbody>
<tr>
<th>Full Name</th>
<th>Average Score</th>
</tr>"""
records_dyn = [
f"<tr><td>{name}</td><td>{avg}</td></tr>" for recs[1], recs[2] in recs]
records2 = """
<form method="POST" action="index.py">
<input type="submit" value="Go Back">
</form>
</body>
</table>
</body>
</html>"""
print("Content-Type:text/html; charset=utf-8")
print()
for i in records1.split("\n"):
print(i)
for i in records_dyn:
print(i)
for i in records1.split("\n"):
print(i)
|
normal
|
{
"blob_id": "b5fee01582a28085983c56b9c266ef7fd5c3c927",
"index": 5132,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nc.execute('SELECT * FROM example')\n<mask token>\nprint('Content-Type:text/html; charset=utf-8')\nprint()\nfor i in records1.split('\\n'):\n print(i)\nfor i in records_dyn:\n print(i)\nfor i in records1.split('\\n'):\n print(i)\n",
"step-3": "<mask token>\nform = cgi.FieldStorage()\nc.execute('SELECT * FROM example')\nrecs = c.fetchall()\nrecords1 = \"\"\"\n<body>\n\t<table>\n\t\t<tbody>\n\t\t\t<tr>\n\t\t\t\t<th>Full Name</th>\n\t\t\t\t<th>Average Score</th>\n\t\t\t</tr>\"\"\"\nrecords_dyn = [f'<tr><td>{name}</td><td>{avg}</td></tr>' for recs[1], recs[\n 2] in recs]\nrecords2 = \"\"\"\n<form method=\"POST\" action=\"index.py\">\n<input type=\"submit\" value=\"Go Back\">\n</form>\n\t\t</body>\n\t</table>\n</body>\n</html>\"\"\"\nprint('Content-Type:text/html; charset=utf-8')\nprint()\nfor i in records1.split('\\n'):\n print(i)\nfor i in records_dyn:\n print(i)\nfor i in records1.split('\\n'):\n print(i)\n",
"step-4": "import cgitb\nimport cgi\nimport pymysql\nform = cgi.FieldStorage()\nc.execute('SELECT * FROM example')\nrecs = c.fetchall()\nrecords1 = \"\"\"\n<body>\n\t<table>\n\t\t<tbody>\n\t\t\t<tr>\n\t\t\t\t<th>Full Name</th>\n\t\t\t\t<th>Average Score</th>\n\t\t\t</tr>\"\"\"\nrecords_dyn = [f'<tr><td>{name}</td><td>{avg}</td></tr>' for recs[1], recs[\n 2] in recs]\nrecords2 = \"\"\"\n<form method=\"POST\" action=\"index.py\">\n<input type=\"submit\" value=\"Go Back\">\n</form>\n\t\t</body>\n\t</table>\n</body>\n</html>\"\"\"\nprint('Content-Type:text/html; charset=utf-8')\nprint()\nfor i in records1.split('\\n'):\n print(i)\nfor i in records_dyn:\n print(i)\nfor i in records1.split('\\n'):\n print(i)\n",
"step-5": "#!/usr/bin/env python\r\nimport cgitb\r\nimport cgi\r\nimport pymysql\r\n\r\nform = cgi.FieldStorage()\r\nc.execute(\"SELECT * FROM example\")\r\nrecs = c.fetchall()\r\nrecords1 = \"\"\"\r\n<body>\r\n\t<table>\r\n\t\t<tbody>\r\n\t\t\t<tr>\r\n\t\t\t\t<th>Full Name</th>\r\n\t\t\t\t<th>Average Score</th>\r\n\t\t\t</tr>\"\"\"\r\nrecords_dyn = [\r\n f\"<tr><td>{name}</td><td>{avg}</td></tr>\" for recs[1], recs[2] in recs]\r\nrecords2 = \"\"\"\r\n<form method=\"POST\" action=\"index.py\">\r\n<input type=\"submit\" value=\"Go Back\">\r\n</form>\r\n\t\t</body>\r\n\t</table>\r\n</body>\r\n</html>\"\"\"\r\nprint(\"Content-Type:text/html; charset=utf-8\")\r\nprint()\r\nfor i in records1.split(\"\\n\"):\r\n print(i)\r\nfor i in records_dyn:\r\n print(i)\r\nfor i in records1.split(\"\\n\"):\r\n print(i)\r\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
# Copyright 2018-present Kensho Technologies, LLC.
from .utils import create_vertex_statement, get_random_date, get_uuid
EVENT_NAMES_LIST = (
"Birthday",
"Bar Mitzvah",
"Coronation",
"Re-awakening",
)
def _create_event_statement(event_name):
"""Return a SQL statement to create a Event vertex."""
field_name_to_value = {'name': event_name, 'event_date': get_random_date(), 'uuid': get_uuid()}
return create_vertex_statement('Event', field_name_to_value)
def get_event_generation_commands():
"""Return a list of SQL statements to create all event vertices."""
command_list = []
for event_name in EVENT_NAMES_LIST:
command_list.append(_create_event_statement(event_name))
return command_list
|
normal
|
{
"blob_id": "a521befba58aa85c2fcfe6006db4b161123585f1",
"index": 5341,
"step-1": "<mask token>\n\n\ndef _create_event_statement(event_name):\n \"\"\"Return a SQL statement to create a Event vertex.\"\"\"\n field_name_to_value = {'name': event_name, 'event_date':\n get_random_date(), 'uuid': get_uuid()}\n return create_vertex_statement('Event', field_name_to_value)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef _create_event_statement(event_name):\n \"\"\"Return a SQL statement to create a Event vertex.\"\"\"\n field_name_to_value = {'name': event_name, 'event_date':\n get_random_date(), 'uuid': get_uuid()}\n return create_vertex_statement('Event', field_name_to_value)\n\n\ndef get_event_generation_commands():\n \"\"\"Return a list of SQL statements to create all event vertices.\"\"\"\n command_list = []\n for event_name in EVENT_NAMES_LIST:\n command_list.append(_create_event_statement(event_name))\n return command_list\n",
"step-3": "<mask token>\nEVENT_NAMES_LIST = 'Birthday', 'Bar Mitzvah', 'Coronation', 'Re-awakening'\n\n\ndef _create_event_statement(event_name):\n \"\"\"Return a SQL statement to create a Event vertex.\"\"\"\n field_name_to_value = {'name': event_name, 'event_date':\n get_random_date(), 'uuid': get_uuid()}\n return create_vertex_statement('Event', field_name_to_value)\n\n\ndef get_event_generation_commands():\n \"\"\"Return a list of SQL statements to create all event vertices.\"\"\"\n command_list = []\n for event_name in EVENT_NAMES_LIST:\n command_list.append(_create_event_statement(event_name))\n return command_list\n",
"step-4": "from .utils import create_vertex_statement, get_random_date, get_uuid\nEVENT_NAMES_LIST = 'Birthday', 'Bar Mitzvah', 'Coronation', 'Re-awakening'\n\n\ndef _create_event_statement(event_name):\n \"\"\"Return a SQL statement to create a Event vertex.\"\"\"\n field_name_to_value = {'name': event_name, 'event_date':\n get_random_date(), 'uuid': get_uuid()}\n return create_vertex_statement('Event', field_name_to_value)\n\n\ndef get_event_generation_commands():\n \"\"\"Return a list of SQL statements to create all event vertices.\"\"\"\n command_list = []\n for event_name in EVENT_NAMES_LIST:\n command_list.append(_create_event_statement(event_name))\n return command_list\n",
"step-5": "# Copyright 2018-present Kensho Technologies, LLC.\nfrom .utils import create_vertex_statement, get_random_date, get_uuid\n\n\nEVENT_NAMES_LIST = (\n \"Birthday\",\n \"Bar Mitzvah\",\n \"Coronation\",\n \"Re-awakening\",\n)\n\n\ndef _create_event_statement(event_name):\n \"\"\"Return a SQL statement to create a Event vertex.\"\"\"\n field_name_to_value = {'name': event_name, 'event_date': get_random_date(), 'uuid': get_uuid()}\n return create_vertex_statement('Event', field_name_to_value)\n\n\ndef get_event_generation_commands():\n \"\"\"Return a list of SQL statements to create all event vertices.\"\"\"\n command_list = []\n\n for event_name in EVENT_NAMES_LIST:\n command_list.append(_create_event_statement(event_name))\n\n return command_list\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
IMAGE_SIZE=(640, 480)
|
normal
|
{
"blob_id": "af80cb4d4ce5c071efc39e85f89bb412cff6bf6e",
"index": 4489,
"step-1": "<mask token>\n",
"step-2": "IMAGE_SIZE = 640, 480\n",
"step-3": "IMAGE_SIZE=(640, 480)\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|>
if boxChecked == 'true':
heading = 'Recurring Donation'
customerRequest = {'given_name': firstName, 'family_name': lastName,
'email_address': email}
try:
customerResponse = customers_api_instance.create_customer(
customerRequest)
except ApiException as e:
print('customer creation failed')
print(e)
exit()
customer = customerResponse.customer
customerCardRequest = {'card_nonce': nonce}
try:
customerCardResponse = customers_api_instance.create_customer_card(
customer.id, customerCardRequest)
except:
print('customer card creation failed')
exit()
customerCard = customerCardResponse.card
body = {'customer_id': customer.id, 'customer_card_id': customerCard.id,
'idempotency_key': idempotency_key, 'amount_money': amount}
customersList = customers_api_instance.list_customers()
else:
heading = 'One time Donation'
body = {'idempotency_key': idempotency_key, 'card_nonce': nonce,
'amount_money': amount}
try:
api_response = transactions_api_instance.charge(location_id, body)
res = api_response.transaction
except ApiException as e:
res = 'Exception when calling TransactionApi->charge: {}'.format(e)
print('Content-type:text/html\r\n\r\n')
print('<html>')
print('<head>')
print('<title>Square Payment</title>')
print('</head>')
print('<body>')
print('<h2>Result: </h2>')
print('<h2>{}</h2>'.format(heading))
print('<p>{}</p>'.format(res))
if customersList:
print('<h2>Customers stored on File: </h2>')
for customer in customersList.customers:
print('<p>{}</p>'.format(customer))
print('</body>')
print('</html>')
<|reserved_special_token_1|>
<|reserved_special_token_0|>
form = cgi.FieldStorage()
nonce = form.getvalue('nonce')
donation = form.getvalue('amount')
boxChecked = form.getvalue('boxChecked')
firstName = form.getvalue('firstname')
lastName = form.getvalue('lastname')
email = form.getvalue('email')
squareconnect.configuration.access_token = (
'sandbox-sq0atb-kfvpHvEa9Mz2098Nozk1RQ')
location_id = 'CBASEGLb1fOhVH4Uvvi1aY_bOawgAQ'
transactions_api_instance = TransactionsApi()
customers_api_instance = CustomersApi()
idempotency_key = str(uuid.uuid1())
amount = {'amount': int(donation) * 100, 'currency': 'USD'}
customersList = []
if boxChecked == 'true':
heading = 'Recurring Donation'
customerRequest = {'given_name': firstName, 'family_name': lastName,
'email_address': email}
try:
customerResponse = customers_api_instance.create_customer(
customerRequest)
except ApiException as e:
print('customer creation failed')
print(e)
exit()
customer = customerResponse.customer
customerCardRequest = {'card_nonce': nonce}
try:
customerCardResponse = customers_api_instance.create_customer_card(
customer.id, customerCardRequest)
except:
print('customer card creation failed')
exit()
customerCard = customerCardResponse.card
body = {'customer_id': customer.id, 'customer_card_id': customerCard.id,
'idempotency_key': idempotency_key, 'amount_money': amount}
customersList = customers_api_instance.list_customers()
else:
heading = 'One time Donation'
body = {'idempotency_key': idempotency_key, 'card_nonce': nonce,
'amount_money': amount}
try:
api_response = transactions_api_instance.charge(location_id, body)
res = api_response.transaction
except ApiException as e:
res = 'Exception when calling TransactionApi->charge: {}'.format(e)
print('Content-type:text/html\r\n\r\n')
print('<html>')
print('<head>')
print('<title>Square Payment</title>')
print('</head>')
print('<body>')
print('<h2>Result: </h2>')
print('<h2>{}</h2>'.format(heading))
print('<p>{}</p>'.format(res))
if customersList:
print('<h2>Customers stored on File: </h2>')
for customer in customersList.customers:
print('<p>{}</p>'.format(customer))
print('</body>')
print('</html>')
<|reserved_special_token_1|>
from __future__ import print_function
import uuid
import cgi
import squareconnect
from squareconnect.rest import ApiException
from squareconnect.apis.transactions_api import TransactionsApi
from squareconnect.apis.locations_api import LocationsApi
from squareconnect.apis.customers_api import CustomersApi
form = cgi.FieldStorage()
nonce = form.getvalue('nonce')
donation = form.getvalue('amount')
boxChecked = form.getvalue('boxChecked')
firstName = form.getvalue('firstname')
lastName = form.getvalue('lastname')
email = form.getvalue('email')
squareconnect.configuration.access_token = (
'sandbox-sq0atb-kfvpHvEa9Mz2098Nozk1RQ')
location_id = 'CBASEGLb1fOhVH4Uvvi1aY_bOawgAQ'
transactions_api_instance = TransactionsApi()
customers_api_instance = CustomersApi()
idempotency_key = str(uuid.uuid1())
amount = {'amount': int(donation) * 100, 'currency': 'USD'}
customersList = []
if boxChecked == 'true':
heading = 'Recurring Donation'
customerRequest = {'given_name': firstName, 'family_name': lastName,
'email_address': email}
try:
customerResponse = customers_api_instance.create_customer(
customerRequest)
except ApiException as e:
print('customer creation failed')
print(e)
exit()
customer = customerResponse.customer
customerCardRequest = {'card_nonce': nonce}
try:
customerCardResponse = customers_api_instance.create_customer_card(
customer.id, customerCardRequest)
except:
print('customer card creation failed')
exit()
customerCard = customerCardResponse.card
body = {'customer_id': customer.id, 'customer_card_id': customerCard.id,
'idempotency_key': idempotency_key, 'amount_money': amount}
customersList = customers_api_instance.list_customers()
else:
heading = 'One time Donation'
body = {'idempotency_key': idempotency_key, 'card_nonce': nonce,
'amount_money': amount}
try:
api_response = transactions_api_instance.charge(location_id, body)
res = api_response.transaction
except ApiException as e:
res = 'Exception when calling TransactionApi->charge: {}'.format(e)
print('Content-type:text/html\r\n\r\n')
print('<html>')
print('<head>')
print('<title>Square Payment</title>')
print('</head>')
print('<body>')
print('<h2>Result: </h2>')
print('<h2>{}</h2>'.format(heading))
print('<p>{}</p>'.format(res))
if customersList:
print('<h2>Customers stored on File: </h2>')
for customer in customersList.customers:
print('<p>{}</p>'.format(customer))
print('</body>')
print('</html>')
<|reserved_special_token_1|>
#!/usr/bin/env python
# coding: utf-8
from __future__ import print_function
import uuid
import cgi
import squareconnect
from squareconnect.rest import ApiException
from squareconnect.apis.transactions_api import TransactionsApi
from squareconnect.apis.locations_api import LocationsApi
from squareconnect.apis.customers_api import CustomersApi
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
nonce = form.getvalue('nonce')
# Get amount data
donation = form.getvalue('amount')
boxChecked = form.getvalue('boxChecked')
firstName = form.getvalue('firstname')
lastName = form.getvalue('lastname')
email = form.getvalue('email')
# The access token to use in all Connect API requests. Use your *sandbox* access
# token if you're just testing things out.
squareconnect.configuration.access_token = 'sandbox-sq0atb-kfvpHvEa9Mz2098Nozk1RQ'
# The ID of the business location to associate processed payments with.
# See [Retrieve your business's locations]
# (https://docs.connect.squareup.com/articles/getting-started/#retrievemerchantprofile)
# for an easy way to get your business's location IDs.
# If you're testing things out, use a sandbox location ID.
location_id = 'CBASEGLb1fOhVH4Uvvi1aY_bOawgAQ'
transactions_api_instance = TransactionsApi()
customers_api_instance = CustomersApi()
# Every payment you process with the SDK must have a unique idempotency key.
# If you're unsure whether a particular payment succeeded, you can reattempt
# it with the same idempotency key without worrying about double charging
# the buyer.
idempotency_key = str(uuid.uuid1())
# Monetary amounts are specified in the smallest unit of the applicable currency.
# This amount is in cents. It's also hard-coded for $1.00, which isn't very useful.
amount = {'amount': int(donation) * 100, 'currency': 'USD'}
customersList = []
# Add a customer to file
if boxChecked == "true":
heading = "Recurring Donation"
customerRequest = {'given_name': firstName, 'family_name': lastName, 'email_address': email}
try:
customerResponse = customers_api_instance.create_customer(customerRequest)
except ApiException as e:
print ("customer creation failed")
print (e)
exit()
customer = customerResponse.customer
customerCardRequest = {'card_nonce': nonce}
try:
customerCardResponse = customers_api_instance.create_customer_card(customer.id, customerCardRequest)
except:
print ("customer card creation failed")
exit()
customerCard = customerCardResponse.card
body = {'customer_id': customer.id, 'customer_card_id': customerCard.id, 'idempotency_key': idempotency_key, 'amount_money': amount}
customersList = customers_api_instance.list_customers()
else:
# To learn more about splitting transactions with additional recipients,
# see the Transactions API documentation on our [developer site]
# (https://docs.connect.squareup.com/payments/transactions/overview#mpt-overview).
heading = "One time Donation"
body = {'idempotency_key': idempotency_key, 'card_nonce': nonce, 'amount_money': amount}
# customersList = Non
# The SDK throws an exception if a Connect endpoint responds with anything besides
# a 200-level HTTP code. This block catches any exceptions that occur from the request.
try:
api_response = transactions_api_instance.charge(location_id, body)
res = api_response.transaction
except ApiException as e:
res = "Exception when calling TransactionApi->charge: {}".format(e)
# Display the result
print ('Content-type:text/html\r\n\r\n')
print ('<html>')
print ('<head>')
print ('<title>Square Payment</title>')
print ('</head>')
print ('<body>')
print ('<h2>Result: </h2>')
print( '<h2>{}</h2>'.format(heading))
print ('<p>{}</p>'.format(res))
if customersList:
print( '<h2>Customers stored on File: </h2>')
for customer in customersList.customers:
print ('<p>{}</p>'.format(customer))
print ('</body>')
print ('</html>')
|
flexible
|
{
"blob_id": "bb7910af5334641fd2db7146112afaff7a2e42b9",
"index": 565,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif boxChecked == 'true':\n heading = 'Recurring Donation'\n customerRequest = {'given_name': firstName, 'family_name': lastName,\n 'email_address': email}\n try:\n customerResponse = customers_api_instance.create_customer(\n customerRequest)\n except ApiException as e:\n print('customer creation failed')\n print(e)\n exit()\n customer = customerResponse.customer\n customerCardRequest = {'card_nonce': nonce}\n try:\n customerCardResponse = customers_api_instance.create_customer_card(\n customer.id, customerCardRequest)\n except:\n print('customer card creation failed')\n exit()\n customerCard = customerCardResponse.card\n body = {'customer_id': customer.id, 'customer_card_id': customerCard.id,\n 'idempotency_key': idempotency_key, 'amount_money': amount}\n customersList = customers_api_instance.list_customers()\nelse:\n heading = 'One time Donation'\n body = {'idempotency_key': idempotency_key, 'card_nonce': nonce,\n 'amount_money': amount}\ntry:\n api_response = transactions_api_instance.charge(location_id, body)\n res = api_response.transaction\nexcept ApiException as e:\n res = 'Exception when calling TransactionApi->charge: {}'.format(e)\nprint('Content-type:text/html\\r\\n\\r\\n')\nprint('<html>')\nprint('<head>')\nprint('<title>Square Payment</title>')\nprint('</head>')\nprint('<body>')\nprint('<h2>Result: </h2>')\nprint('<h2>{}</h2>'.format(heading))\nprint('<p>{}</p>'.format(res))\nif customersList:\n print('<h2>Customers stored on File: </h2>')\n for customer in customersList.customers:\n print('<p>{}</p>'.format(customer))\nprint('</body>')\nprint('</html>')\n",
"step-3": "<mask token>\nform = cgi.FieldStorage()\nnonce = form.getvalue('nonce')\ndonation = form.getvalue('amount')\nboxChecked = form.getvalue('boxChecked')\nfirstName = form.getvalue('firstname')\nlastName = form.getvalue('lastname')\nemail = form.getvalue('email')\nsquareconnect.configuration.access_token = (\n 'sandbox-sq0atb-kfvpHvEa9Mz2098Nozk1RQ')\nlocation_id = 'CBASEGLb1fOhVH4Uvvi1aY_bOawgAQ'\ntransactions_api_instance = TransactionsApi()\ncustomers_api_instance = CustomersApi()\nidempotency_key = str(uuid.uuid1())\namount = {'amount': int(donation) * 100, 'currency': 'USD'}\ncustomersList = []\nif boxChecked == 'true':\n heading = 'Recurring Donation'\n customerRequest = {'given_name': firstName, 'family_name': lastName,\n 'email_address': email}\n try:\n customerResponse = customers_api_instance.create_customer(\n customerRequest)\n except ApiException as e:\n print('customer creation failed')\n print(e)\n exit()\n customer = customerResponse.customer\n customerCardRequest = {'card_nonce': nonce}\n try:\n customerCardResponse = customers_api_instance.create_customer_card(\n customer.id, customerCardRequest)\n except:\n print('customer card creation failed')\n exit()\n customerCard = customerCardResponse.card\n body = {'customer_id': customer.id, 'customer_card_id': customerCard.id,\n 'idempotency_key': idempotency_key, 'amount_money': amount}\n customersList = customers_api_instance.list_customers()\nelse:\n heading = 'One time Donation'\n body = {'idempotency_key': idempotency_key, 'card_nonce': nonce,\n 'amount_money': amount}\ntry:\n api_response = transactions_api_instance.charge(location_id, body)\n res = api_response.transaction\nexcept ApiException as e:\n res = 'Exception when calling TransactionApi->charge: {}'.format(e)\nprint('Content-type:text/html\\r\\n\\r\\n')\nprint('<html>')\nprint('<head>')\nprint('<title>Square Payment</title>')\nprint('</head>')\nprint('<body>')\nprint('<h2>Result: </h2>')\nprint('<h2>{}</h2>'.format(heading))\nprint('<p>{}</p>'.format(res))\nif customersList:\n print('<h2>Customers stored on File: </h2>')\n for customer in customersList.customers:\n print('<p>{}</p>'.format(customer))\nprint('</body>')\nprint('</html>')\n",
"step-4": "from __future__ import print_function\nimport uuid\nimport cgi\nimport squareconnect\nfrom squareconnect.rest import ApiException\nfrom squareconnect.apis.transactions_api import TransactionsApi\nfrom squareconnect.apis.locations_api import LocationsApi\nfrom squareconnect.apis.customers_api import CustomersApi\nform = cgi.FieldStorage()\nnonce = form.getvalue('nonce')\ndonation = form.getvalue('amount')\nboxChecked = form.getvalue('boxChecked')\nfirstName = form.getvalue('firstname')\nlastName = form.getvalue('lastname')\nemail = form.getvalue('email')\nsquareconnect.configuration.access_token = (\n 'sandbox-sq0atb-kfvpHvEa9Mz2098Nozk1RQ')\nlocation_id = 'CBASEGLb1fOhVH4Uvvi1aY_bOawgAQ'\ntransactions_api_instance = TransactionsApi()\ncustomers_api_instance = CustomersApi()\nidempotency_key = str(uuid.uuid1())\namount = {'amount': int(donation) * 100, 'currency': 'USD'}\ncustomersList = []\nif boxChecked == 'true':\n heading = 'Recurring Donation'\n customerRequest = {'given_name': firstName, 'family_name': lastName,\n 'email_address': email}\n try:\n customerResponse = customers_api_instance.create_customer(\n customerRequest)\n except ApiException as e:\n print('customer creation failed')\n print(e)\n exit()\n customer = customerResponse.customer\n customerCardRequest = {'card_nonce': nonce}\n try:\n customerCardResponse = customers_api_instance.create_customer_card(\n customer.id, customerCardRequest)\n except:\n print('customer card creation failed')\n exit()\n customerCard = customerCardResponse.card\n body = {'customer_id': customer.id, 'customer_card_id': customerCard.id,\n 'idempotency_key': idempotency_key, 'amount_money': amount}\n customersList = customers_api_instance.list_customers()\nelse:\n heading = 'One time Donation'\n body = {'idempotency_key': idempotency_key, 'card_nonce': nonce,\n 'amount_money': amount}\ntry:\n api_response = transactions_api_instance.charge(location_id, body)\n res = api_response.transaction\nexcept ApiException as e:\n res = 'Exception when calling TransactionApi->charge: {}'.format(e)\nprint('Content-type:text/html\\r\\n\\r\\n')\nprint('<html>')\nprint('<head>')\nprint('<title>Square Payment</title>')\nprint('</head>')\nprint('<body>')\nprint('<h2>Result: </h2>')\nprint('<h2>{}</h2>'.format(heading))\nprint('<p>{}</p>'.format(res))\nif customersList:\n print('<h2>Customers stored on File: </h2>')\n for customer in customersList.customers:\n print('<p>{}</p>'.format(customer))\nprint('</body>')\nprint('</html>')\n",
"step-5": "#!/usr/bin/env python\n# coding: utf-8\nfrom __future__ import print_function\nimport uuid\nimport cgi\n\nimport squareconnect\nfrom squareconnect.rest import ApiException\nfrom squareconnect.apis.transactions_api import TransactionsApi\nfrom squareconnect.apis.locations_api import LocationsApi\nfrom squareconnect.apis.customers_api import CustomersApi\n\n# Create instance of FieldStorage\nform = cgi.FieldStorage()\n\n# Get data from fields\nnonce = form.getvalue('nonce')\n# Get amount data\ndonation = form.getvalue('amount')\n\nboxChecked = form.getvalue('boxChecked')\nfirstName = form.getvalue('firstname')\nlastName = form.getvalue('lastname')\nemail = form.getvalue('email')\n\n\n# The access token to use in all Connect API requests. Use your *sandbox* access\n# token if you're just testing things out.\nsquareconnect.configuration.access_token = 'sandbox-sq0atb-kfvpHvEa9Mz2098Nozk1RQ'\n\n# The ID of the business location to associate processed payments with.\n# See [Retrieve your business's locations]\n# (https://docs.connect.squareup.com/articles/getting-started/#retrievemerchantprofile)\n# for an easy way to get your business's location IDs.\n# If you're testing things out, use a sandbox location ID.\nlocation_id = 'CBASEGLb1fOhVH4Uvvi1aY_bOawgAQ'\n\ntransactions_api_instance = TransactionsApi()\ncustomers_api_instance = CustomersApi()\n\n# Every payment you process with the SDK must have a unique idempotency key.\n# If you're unsure whether a particular payment succeeded, you can reattempt\n# it with the same idempotency key without worrying about double charging\n# the buyer.\nidempotency_key = str(uuid.uuid1())\n\n# Monetary amounts are specified in the smallest unit of the applicable currency.\n# This amount is in cents. It's also hard-coded for $1.00, which isn't very useful.\namount = {'amount': int(donation) * 100, 'currency': 'USD'}\n\ncustomersList = []\n\n# Add a customer to file\nif boxChecked == \"true\": \n\theading = \"Recurring Donation\"\n\tcustomerRequest = {'given_name': firstName, 'family_name': lastName, 'email_address': email}\n\n\ttry:\n\t\tcustomerResponse = customers_api_instance.create_customer(customerRequest)\n\texcept ApiException as e:\n\t\tprint (\"customer creation failed\")\n\t\tprint (e)\n\t\texit()\n\n\tcustomer = customerResponse.customer\n\tcustomerCardRequest = {'card_nonce': nonce}\n\n\ttry:\n\t\tcustomerCardResponse = customers_api_instance.create_customer_card(customer.id, customerCardRequest)\n\texcept:\n\t\tprint (\"customer card creation failed\")\n\t\texit()\n\n\tcustomerCard = customerCardResponse.card\n\n\tbody = {'customer_id': customer.id, 'customer_card_id': customerCard.id, 'idempotency_key': idempotency_key, 'amount_money': amount}\n\tcustomersList = customers_api_instance.list_customers()\nelse:\n\t# To learn more about splitting transactions with additional recipients,\n\t# see the Transactions API documentation on our [developer site]\n\t# (https://docs.connect.squareup.com/payments/transactions/overview#mpt-overview).\n\theading = \"One time Donation\"\n\tbody = {'idempotency_key': idempotency_key, 'card_nonce': nonce, 'amount_money': amount}\n\t# customersList = Non\n\n\n# The SDK throws an exception if a Connect endpoint responds with anything besides\n# a 200-level HTTP code. This block catches any exceptions that occur from the request.\ntry:\n api_response = transactions_api_instance.charge(location_id, body)\n res = api_response.transaction\nexcept ApiException as e:\n res = \"Exception when calling TransactionApi->charge: {}\".format(e)\n\n# Display the result\nprint ('Content-type:text/html\\r\\n\\r\\n')\nprint ('<html>')\nprint ('<head>')\nprint ('<title>Square Payment</title>')\nprint ('</head>')\nprint ('<body>')\nprint ('<h2>Result: </h2>')\nprint( '<h2>{}</h2>'.format(heading))\nprint ('<p>{}</p>'.format(res))\nif customersList:\n\tprint( '<h2>Customers stored on File: </h2>')\n\tfor customer in customersList.customers:\n\t\tprint ('<p>{}</p>'.format(customer))\n\nprint ('</body>')\nprint ('</html>')\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
# from https://github.com/tensorflow/models/tree/master/research/object_detection/dataset_tools
# and https://gist.github.com/saghiralfasly/ee642af0616461145a9a82d7317fb1d6
import tensorflow as tf
from object_detection.utils import dataset_util
import os
import io
import hashlib
import xml.etree.ElementTree as ET
import random
from PIL import Image
def create_example(xml_file):
tree = ET.parse(xml_file)
root = tree.getroot()
image_name = root.find('filename').text
file_name = image_name.encode('utf8')
size=root.find('size')
width = int(size[0].text)
height = int(size[1].text)
xmin = []
ymin = []
xmax = []
ymax = []
classes = []
classes_text = []
truncated = []
poses = []
difficult_obj = []
for member in root.findall('object'):
classes_text.append(member[0].text)
def class_text_to_int(row_label):
if row_label == 'car-red':
return 1
if row_label == 'car-blue':
return 2
if row_label == 'phone':
return 3
classes.append(class_text_to_int(member[0].text))
xmin.append(float(member[4][0].text) / width)
ymin.append(float(member[4][1].text) / height)
xmax.append(float(member[4][2].text) / width)
ymax.append(float(member[4][3].text) / height)
difficult_obj.append(0)
truncated.append(0)
poses.append('Unspecified'.encode('utf8'))
full_path = os.path.join('./data/images', '{}'.format(image_name))
with tf.gfile.GFile(full_path, 'rb') as fid:
encoded_jpg = fid.read()
encoded_jpg_io = io.BytesIO(encoded_jpg)
image = Image.open(encoded_jpg_io)
if image.format != 'JPEG':
raise ValueError('Image format not JPEG')
key = hashlib.sha256(encoded_jpg).hexdigest()
example = tf.train.Example(features=tf.train.Features(feature={
'image/height': dataset_util.int64_feature(height),
'image/width': dataset_util.int64_feature(width),
'image/filename': dataset_util.bytes_feature(file_name),
'image/source_id': dataset_util.bytes_feature(file_name),
'image/key/sha256': dataset_util.bytes_feature(key.encode('utf8')),
'image/encoded': dataset_util.bytes_feature(encoded_jpg),
'image/format': dataset_util.bytes_feature('jpeg'.encode('utf8')),
'image/object/bbox/xmin': dataset_util.float_list_feature(xmin),
'image/object/bbox/xmax': dataset_util.float_list_feature(xmax),
'image/object/bbox/ymin': dataset_util.float_list_feature(ymin),
'image/object/bbox/ymax': dataset_util.float_list_feature(ymax),
'image/object/class/text': dataset_util.bytes_list_feature(classes_text),
'image/object/class/label': dataset_util.int64_list_feature(classes),
'image/object/difficult': dataset_util.int64_list_feature(difficult_obj),
'image/object/truncated': dataset_util.int64_list_feature(truncated),
'image/object/view': dataset_util.bytes_list_feature(poses),
}))
return example
def main(_):
writer_train = tf.python_io.TFRecordWriter('./data/train.record')
writer_test = tf.python_io.TFRecordWriter('./data/test.record')
filename_list=tf.train.match_filenames_once("./data/annotations/*.xml")
init = (tf.global_variables_initializer(), tf.local_variables_initializer())
sess=tf.Session()
sess.run(init)
list=sess.run(filename_list)
random.shuffle(list)
i=1
tst=0
trn=0
for xml_file in list:
example = create_example(xml_file)
if (i%5)==0:
writer_test.write(example.SerializeToString())
tst=tst+1
else:
writer_train.write(example.SerializeToString())
trn=trn+1
i=i+1
print(xml_file)
writer_test.close()
writer_train.close()
print('Successfully converted dataset to TFRecord.')
print('training dataset: # ')
print(trn)
print('test dataset: # ')
print(tst)
if __name__ == '__main__':
tf.app.run()
|
normal
|
{
"blob_id": "8142585827590f6d951f0fcc375e8511aa75e9c8",
"index": 7320,
"step-1": "<mask token>\n\n\ndef main(_):\n writer_train = tf.python_io.TFRecordWriter('./data/train.record')\n writer_test = tf.python_io.TFRecordWriter('./data/test.record')\n filename_list = tf.train.match_filenames_once('./data/annotations/*.xml')\n init = tf.global_variables_initializer(), tf.local_variables_initializer()\n sess = tf.Session()\n sess.run(init)\n list = sess.run(filename_list)\n random.shuffle(list)\n i = 1\n tst = 0\n trn = 0\n for xml_file in list:\n example = create_example(xml_file)\n if i % 5 == 0:\n writer_test.write(example.SerializeToString())\n tst = tst + 1\n else:\n writer_train.write(example.SerializeToString())\n trn = trn + 1\n i = i + 1\n print(xml_file)\n writer_test.close()\n writer_train.close()\n print('Successfully converted dataset to TFRecord.')\n print('training dataset: # ')\n print(trn)\n print('test dataset: # ')\n print(tst)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef create_example(xml_file):\n tree = ET.parse(xml_file)\n root = tree.getroot()\n image_name = root.find('filename').text\n file_name = image_name.encode('utf8')\n size = root.find('size')\n width = int(size[0].text)\n height = int(size[1].text)\n xmin = []\n ymin = []\n xmax = []\n ymax = []\n classes = []\n classes_text = []\n truncated = []\n poses = []\n difficult_obj = []\n for member in root.findall('object'):\n classes_text.append(member[0].text)\n\n def class_text_to_int(row_label):\n if row_label == 'car-red':\n return 1\n if row_label == 'car-blue':\n return 2\n if row_label == 'phone':\n return 3\n classes.append(class_text_to_int(member[0].text))\n xmin.append(float(member[4][0].text) / width)\n ymin.append(float(member[4][1].text) / height)\n xmax.append(float(member[4][2].text) / width)\n ymax.append(float(member[4][3].text) / height)\n difficult_obj.append(0)\n truncated.append(0)\n poses.append('Unspecified'.encode('utf8'))\n full_path = os.path.join('./data/images', '{}'.format(image_name))\n with tf.gfile.GFile(full_path, 'rb') as fid:\n encoded_jpg = fid.read()\n encoded_jpg_io = io.BytesIO(encoded_jpg)\n image = Image.open(encoded_jpg_io)\n if image.format != 'JPEG':\n raise ValueError('Image format not JPEG')\n key = hashlib.sha256(encoded_jpg).hexdigest()\n example = tf.train.Example(features=tf.train.Features(feature={\n 'image/height': dataset_util.int64_feature(height), 'image/width':\n dataset_util.int64_feature(width), 'image/filename': dataset_util.\n bytes_feature(file_name), 'image/source_id': dataset_util.\n bytes_feature(file_name), 'image/key/sha256': dataset_util.\n bytes_feature(key.encode('utf8')), 'image/encoded': dataset_util.\n bytes_feature(encoded_jpg), 'image/format': dataset_util.\n bytes_feature('jpeg'.encode('utf8')), 'image/object/bbox/xmin':\n dataset_util.float_list_feature(xmin), 'image/object/bbox/xmax':\n dataset_util.float_list_feature(xmax), 'image/object/bbox/ymin':\n dataset_util.float_list_feature(ymin), 'image/object/bbox/ymax':\n dataset_util.float_list_feature(ymax), 'image/object/class/text':\n dataset_util.bytes_list_feature(classes_text),\n 'image/object/class/label': dataset_util.int64_list_feature(classes\n ), 'image/object/difficult': dataset_util.int64_list_feature(\n difficult_obj), 'image/object/truncated': dataset_util.\n int64_list_feature(truncated), 'image/object/view': dataset_util.\n bytes_list_feature(poses)}))\n return example\n\n\ndef main(_):\n writer_train = tf.python_io.TFRecordWriter('./data/train.record')\n writer_test = tf.python_io.TFRecordWriter('./data/test.record')\n filename_list = tf.train.match_filenames_once('./data/annotations/*.xml')\n init = tf.global_variables_initializer(), tf.local_variables_initializer()\n sess = tf.Session()\n sess.run(init)\n list = sess.run(filename_list)\n random.shuffle(list)\n i = 1\n tst = 0\n trn = 0\n for xml_file in list:\n example = create_example(xml_file)\n if i % 5 == 0:\n writer_test.write(example.SerializeToString())\n tst = tst + 1\n else:\n writer_train.write(example.SerializeToString())\n trn = trn + 1\n i = i + 1\n print(xml_file)\n writer_test.close()\n writer_train.close()\n print('Successfully converted dataset to TFRecord.')\n print('training dataset: # ')\n print(trn)\n print('test dataset: # ')\n print(tst)\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef create_example(xml_file):\n tree = ET.parse(xml_file)\n root = tree.getroot()\n image_name = root.find('filename').text\n file_name = image_name.encode('utf8')\n size = root.find('size')\n width = int(size[0].text)\n height = int(size[1].text)\n xmin = []\n ymin = []\n xmax = []\n ymax = []\n classes = []\n classes_text = []\n truncated = []\n poses = []\n difficult_obj = []\n for member in root.findall('object'):\n classes_text.append(member[0].text)\n\n def class_text_to_int(row_label):\n if row_label == 'car-red':\n return 1\n if row_label == 'car-blue':\n return 2\n if row_label == 'phone':\n return 3\n classes.append(class_text_to_int(member[0].text))\n xmin.append(float(member[4][0].text) / width)\n ymin.append(float(member[4][1].text) / height)\n xmax.append(float(member[4][2].text) / width)\n ymax.append(float(member[4][3].text) / height)\n difficult_obj.append(0)\n truncated.append(0)\n poses.append('Unspecified'.encode('utf8'))\n full_path = os.path.join('./data/images', '{}'.format(image_name))\n with tf.gfile.GFile(full_path, 'rb') as fid:\n encoded_jpg = fid.read()\n encoded_jpg_io = io.BytesIO(encoded_jpg)\n image = Image.open(encoded_jpg_io)\n if image.format != 'JPEG':\n raise ValueError('Image format not JPEG')\n key = hashlib.sha256(encoded_jpg).hexdigest()\n example = tf.train.Example(features=tf.train.Features(feature={\n 'image/height': dataset_util.int64_feature(height), 'image/width':\n dataset_util.int64_feature(width), 'image/filename': dataset_util.\n bytes_feature(file_name), 'image/source_id': dataset_util.\n bytes_feature(file_name), 'image/key/sha256': dataset_util.\n bytes_feature(key.encode('utf8')), 'image/encoded': dataset_util.\n bytes_feature(encoded_jpg), 'image/format': dataset_util.\n bytes_feature('jpeg'.encode('utf8')), 'image/object/bbox/xmin':\n dataset_util.float_list_feature(xmin), 'image/object/bbox/xmax':\n dataset_util.float_list_feature(xmax), 'image/object/bbox/ymin':\n dataset_util.float_list_feature(ymin), 'image/object/bbox/ymax':\n dataset_util.float_list_feature(ymax), 'image/object/class/text':\n dataset_util.bytes_list_feature(classes_text),\n 'image/object/class/label': dataset_util.int64_list_feature(classes\n ), 'image/object/difficult': dataset_util.int64_list_feature(\n difficult_obj), 'image/object/truncated': dataset_util.\n int64_list_feature(truncated), 'image/object/view': dataset_util.\n bytes_list_feature(poses)}))\n return example\n\n\ndef main(_):\n writer_train = tf.python_io.TFRecordWriter('./data/train.record')\n writer_test = tf.python_io.TFRecordWriter('./data/test.record')\n filename_list = tf.train.match_filenames_once('./data/annotations/*.xml')\n init = tf.global_variables_initializer(), tf.local_variables_initializer()\n sess = tf.Session()\n sess.run(init)\n list = sess.run(filename_list)\n random.shuffle(list)\n i = 1\n tst = 0\n trn = 0\n for xml_file in list:\n example = create_example(xml_file)\n if i % 5 == 0:\n writer_test.write(example.SerializeToString())\n tst = tst + 1\n else:\n writer_train.write(example.SerializeToString())\n trn = trn + 1\n i = i + 1\n print(xml_file)\n writer_test.close()\n writer_train.close()\n print('Successfully converted dataset to TFRecord.')\n print('training dataset: # ')\n print(trn)\n print('test dataset: # ')\n print(tst)\n\n\nif __name__ == '__main__':\n tf.app.run()\n",
"step-4": "import tensorflow as tf\nfrom object_detection.utils import dataset_util\nimport os\nimport io\nimport hashlib\nimport xml.etree.ElementTree as ET\nimport random\nfrom PIL import Image\n\n\ndef create_example(xml_file):\n tree = ET.parse(xml_file)\n root = tree.getroot()\n image_name = root.find('filename').text\n file_name = image_name.encode('utf8')\n size = root.find('size')\n width = int(size[0].text)\n height = int(size[1].text)\n xmin = []\n ymin = []\n xmax = []\n ymax = []\n classes = []\n classes_text = []\n truncated = []\n poses = []\n difficult_obj = []\n for member in root.findall('object'):\n classes_text.append(member[0].text)\n\n def class_text_to_int(row_label):\n if row_label == 'car-red':\n return 1\n if row_label == 'car-blue':\n return 2\n if row_label == 'phone':\n return 3\n classes.append(class_text_to_int(member[0].text))\n xmin.append(float(member[4][0].text) / width)\n ymin.append(float(member[4][1].text) / height)\n xmax.append(float(member[4][2].text) / width)\n ymax.append(float(member[4][3].text) / height)\n difficult_obj.append(0)\n truncated.append(0)\n poses.append('Unspecified'.encode('utf8'))\n full_path = os.path.join('./data/images', '{}'.format(image_name))\n with tf.gfile.GFile(full_path, 'rb') as fid:\n encoded_jpg = fid.read()\n encoded_jpg_io = io.BytesIO(encoded_jpg)\n image = Image.open(encoded_jpg_io)\n if image.format != 'JPEG':\n raise ValueError('Image format not JPEG')\n key = hashlib.sha256(encoded_jpg).hexdigest()\n example = tf.train.Example(features=tf.train.Features(feature={\n 'image/height': dataset_util.int64_feature(height), 'image/width':\n dataset_util.int64_feature(width), 'image/filename': dataset_util.\n bytes_feature(file_name), 'image/source_id': dataset_util.\n bytes_feature(file_name), 'image/key/sha256': dataset_util.\n bytes_feature(key.encode('utf8')), 'image/encoded': dataset_util.\n bytes_feature(encoded_jpg), 'image/format': dataset_util.\n bytes_feature('jpeg'.encode('utf8')), 'image/object/bbox/xmin':\n dataset_util.float_list_feature(xmin), 'image/object/bbox/xmax':\n dataset_util.float_list_feature(xmax), 'image/object/bbox/ymin':\n dataset_util.float_list_feature(ymin), 'image/object/bbox/ymax':\n dataset_util.float_list_feature(ymax), 'image/object/class/text':\n dataset_util.bytes_list_feature(classes_text),\n 'image/object/class/label': dataset_util.int64_list_feature(classes\n ), 'image/object/difficult': dataset_util.int64_list_feature(\n difficult_obj), 'image/object/truncated': dataset_util.\n int64_list_feature(truncated), 'image/object/view': dataset_util.\n bytes_list_feature(poses)}))\n return example\n\n\ndef main(_):\n writer_train = tf.python_io.TFRecordWriter('./data/train.record')\n writer_test = tf.python_io.TFRecordWriter('./data/test.record')\n filename_list = tf.train.match_filenames_once('./data/annotations/*.xml')\n init = tf.global_variables_initializer(), tf.local_variables_initializer()\n sess = tf.Session()\n sess.run(init)\n list = sess.run(filename_list)\n random.shuffle(list)\n i = 1\n tst = 0\n trn = 0\n for xml_file in list:\n example = create_example(xml_file)\n if i % 5 == 0:\n writer_test.write(example.SerializeToString())\n tst = tst + 1\n else:\n writer_train.write(example.SerializeToString())\n trn = trn + 1\n i = i + 1\n print(xml_file)\n writer_test.close()\n writer_train.close()\n print('Successfully converted dataset to TFRecord.')\n print('training dataset: # ')\n print(trn)\n print('test dataset: # ')\n print(tst)\n\n\nif __name__ == '__main__':\n tf.app.run()\n",
"step-5": "# from https://github.com/tensorflow/models/tree/master/research/object_detection/dataset_tools\n# and https://gist.github.com/saghiralfasly/ee642af0616461145a9a82d7317fb1d6\n \nimport tensorflow as tf\nfrom object_detection.utils import dataset_util\nimport os\nimport io\nimport hashlib\nimport xml.etree.ElementTree as ET\nimport random\nfrom PIL import Image\n\ndef create_example(xml_file):\n tree = ET.parse(xml_file)\n root = tree.getroot()\n image_name = root.find('filename').text\n file_name = image_name.encode('utf8')\n size=root.find('size')\n width = int(size[0].text)\n height = int(size[1].text)\n xmin = []\n ymin = []\n xmax = []\n ymax = []\n classes = []\n classes_text = []\n truncated = []\n poses = []\n difficult_obj = []\n for member in root.findall('object'):\n classes_text.append(member[0].text)\n\n def class_text_to_int(row_label):\n if row_label == 'car-red':\n return 1\n if row_label == 'car-blue':\n return 2\n if row_label == 'phone':\n return 3\n\n classes.append(class_text_to_int(member[0].text))\n\n xmin.append(float(member[4][0].text) / width)\n ymin.append(float(member[4][1].text) / height)\n xmax.append(float(member[4][2].text) / width)\n ymax.append(float(member[4][3].text) / height)\n difficult_obj.append(0)\n truncated.append(0)\n poses.append('Unspecified'.encode('utf8'))\n\n full_path = os.path.join('./data/images', '{}'.format(image_name))\n with tf.gfile.GFile(full_path, 'rb') as fid:\n encoded_jpg = fid.read()\n encoded_jpg_io = io.BytesIO(encoded_jpg)\n image = Image.open(encoded_jpg_io)\n if image.format != 'JPEG':\n raise ValueError('Image format not JPEG')\n key = hashlib.sha256(encoded_jpg).hexdigest()\n\t\t\n example = tf.train.Example(features=tf.train.Features(feature={\n 'image/height': dataset_util.int64_feature(height),\n 'image/width': dataset_util.int64_feature(width),\n 'image/filename': dataset_util.bytes_feature(file_name),\n 'image/source_id': dataset_util.bytes_feature(file_name),\n 'image/key/sha256': dataset_util.bytes_feature(key.encode('utf8')),\n 'image/encoded': dataset_util.bytes_feature(encoded_jpg),\n 'image/format': dataset_util.bytes_feature('jpeg'.encode('utf8')),\n 'image/object/bbox/xmin': dataset_util.float_list_feature(xmin),\n 'image/object/bbox/xmax': dataset_util.float_list_feature(xmax),\n 'image/object/bbox/ymin': dataset_util.float_list_feature(ymin),\n 'image/object/bbox/ymax': dataset_util.float_list_feature(ymax),\n 'image/object/class/text': dataset_util.bytes_list_feature(classes_text),\n 'image/object/class/label': dataset_util.int64_list_feature(classes),\n 'image/object/difficult': dataset_util.int64_list_feature(difficult_obj),\n 'image/object/truncated': dataset_util.int64_list_feature(truncated),\n 'image/object/view': dataset_util.bytes_list_feature(poses),\n }))\t\n return example\t\n\t\t\ndef main(_):\n writer_train = tf.python_io.TFRecordWriter('./data/train.record') \n writer_test = tf.python_io.TFRecordWriter('./data/test.record')\n filename_list=tf.train.match_filenames_once(\"./data/annotations/*.xml\")\n init = (tf.global_variables_initializer(), tf.local_variables_initializer())\n sess=tf.Session()\n sess.run(init)\n list=sess.run(filename_list)\n random.shuffle(list) \n i=1 \n tst=0\n trn=0 \n for xml_file in list:\n example = create_example(xml_file)\n if (i%5)==0: \n writer_test.write(example.SerializeToString())\n tst=tst+1\n else: \n writer_train.write(example.SerializeToString())\n trn=trn+1\n i=i+1\n print(xml_file)\n writer_test.close()\n writer_train.close()\n print('Successfully converted dataset to TFRecord.')\n print('training dataset: # ')\n print(trn)\n print('test dataset: # ')\n print(tst)\t\n\t\nif __name__ == '__main__':\n tf.app.run()",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
n=int(input("Digite um número"))
m=n-1
o=n+1
print("Seu número é {} seu antecessor é {} e seu sucessor é {}".format(n,m,o))
|
normal
|
{
"blob_id": "47d72379b894826dad335f098649702ade195f78",
"index": 7337,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('Seu número é {} seu antecessor é {} e seu sucessor é {}'.format(n, m, o)\n )\n",
"step-3": "n = int(input('Digite um número'))\nm = n - 1\no = n + 1\nprint('Seu número é {} seu antecessor é {} e seu sucessor é {}'.format(n, m, o)\n )\n",
"step-4": "n=int(input(\"Digite um número\"))\nm=n-1\no=n+1\nprint(\"Seu número é {} seu antecessor é {} e seu sucessor é {}\".format(n,m,o))",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
def unique(lisst):
setlisst = set(lisst)
return len(setlisst)
print(unique({4, 5, 1, 1, 3}))
|
normal
|
{
"blob_id": "42d26ef51bb4dafc8a0201a828652e166a3905e4",
"index": 7339,
"step-1": "<mask token>\n",
"step-2": "def unique(lisst):\n setlisst = set(lisst)\n return len(setlisst)\n\n\n<mask token>\n",
"step-3": "def unique(lisst):\n setlisst = set(lisst)\n return len(setlisst)\n\n\nprint(unique({4, 5, 1, 1, 3}))\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
#!/usr/bin/env python
"""This script draws a boxplot of each atom contribution to the cavity."""
import sys
if sys.version < "2.7":
print >> sys.stderr, "ERROR: This script requires Python 2.7.x. "\
"Please install it and try again."
exit(1)
try:
import matplotlib.pyplot as pyplot
import numpy
except ImportError:
print >> sys.stderr, "ERROR:",
print >> sys.stderr, "This script requires matplotlib and numpy. "\
"Please make sure you installed it and that "\
"your PYTHONPATH is set adequately."
exit(1)
def parse_args():
import argparse
import os.path
def isfile(path):
Error = argparse.ArgumentTypeError
if not os.path.exists(path):
raise Error("No such file: '{0}'".format(path))
elif not os.path.isfile(path):
raise Error("Not a valid file: '{0}'".format(path))
return path
hf = lambda prog: argparse.HelpFormatter(prog, max_help_position=50)
parser = argparse.ArgumentParser(description=__doc__, formatter_class=hf)
parser.add_argument("filename", type=isfile,
help="contribution data file")
parser.add_argument("-o", "--output",
help="output file name")
parser.add_argument("-n", type=int, default=0,
help="show n greatest contributions")
parser.add_argument("-s", "--stdev", action="store_true",
help="only plot standard deviations")
parser.add_argument("-r", metavar="residue", nargs="+",
help="plot specific residues along time")
return parser.parse_args()
def die(s):
print >> sys.stderr, "ERROR:", s
exit(1)
def show_usage():
print >> sys.stderr, "usage: python " + sys.argv[0] + " <filename.dat>"
def read_contrib(fname):
data = []
with open(fname, "rt") as f:
for line in f:
split = line.split()
k = split[0]
counts = [int(c) for c in split[2:]]
data.append((k, counts))
return data
def med(x):
x = sorted(x)
length = len(x)
if not length % 2:
return (x[length / 2] + x[(length - 1) / 2]) / 2.0
return float(x[length / 2])
def plot_sd(data):
x = numpy.array([i+1 for i in range(len(data[0]))])
d = numpy.std(data[1], axis=1)
pyplot.bar(x, d)
pyplot.xticks(x+.5, data[0], rotation=90)
ylim = pyplot.ylim()
pyplot.ylim((ylim[0]-10, ylim[1]+10))
pyplot.xlim((x[0]-1, x[-1]+1))
pyplot.subplots_adjust(left=0.1, right=0.9, top=0.95, bottom=0.2)
pyplot.title("Residue contribution standard deviations")
def plot_barplot(data):
x = [i+1 for i in range(len(data[0]))]
pyplot.boxplot(data[1])
pyplot.xticks(x, data[0], rotation=90)
ylim = pyplot.ylim()
pyplot.ylim((ylim[0]-10, ylim[1]+10))
pyplot.subplots_adjust(left=0.1, right=0.9, top=0.95, bottom=0.2)
pyplot.title("Residue contribution")
def plot_residues(data, residues):
def running_average(x, N):
return numpy.convolve(x, numpy.ones((N,))/N)[(N-1):]
if "all" in residues:
residues = data[0]
for r in residues:
try:
i = data[0].index(r)
except:
die("No residue named '{0}'".format(r))
# y = running_average(data[1][i], 5)
y = data[1][i]
pyplot.plot(y, label=r)
pyplot.legend(loc="best")
def main():
args = parse_args()
data = read_contrib(args.filename)
if args.n:
data = sorted(data, key=lambda x: med(x[1]), reverse=True)
data = data[:args.n]
data = zip(*data)
if args.r:
plot_residues(data, args.r)
elif args.stdev:
plot_sd(data)
else:
plot_barplot(data)
if args.output:
pyplot.savefig(args.output)
else:
pyplot.show()
if __name__ == '__main__':
main()
|
normal
|
{
"blob_id": "9fdcaf65f070b7081afd327442dd20e3284c71eb",
"index": 7905,
"step-1": "<mask token>\n\n\ndef parse_args():\n import argparse\n import os.path\n\n def isfile(path):\n Error = argparse.ArgumentTypeError\n if not os.path.exists(path):\n raise Error(\"No such file: '{0}'\".format(path))\n elif not os.path.isfile(path):\n raise Error(\"Not a valid file: '{0}'\".format(path))\n return path\n hf = lambda prog: argparse.HelpFormatter(prog, max_help_position=50)\n parser = argparse.ArgumentParser(description=__doc__, formatter_class=hf)\n parser.add_argument('filename', type=isfile, help='contribution data file')\n parser.add_argument('-o', '--output', help='output file name')\n parser.add_argument('-n', type=int, default=0, help=\n 'show n greatest contributions')\n parser.add_argument('-s', '--stdev', action='store_true', help=\n 'only plot standard deviations')\n parser.add_argument('-r', metavar='residue', nargs='+', help=\n 'plot specific residues along time')\n return parser.parse_args()\n\n\ndef die(s):\n print >> sys.stderr, 'ERROR:', s\n exit(1)\n\n\ndef show_usage():\n print >> sys.stderr, 'usage: python ' + sys.argv[0] + ' <filename.dat>'\n\n\ndef read_contrib(fname):\n data = []\n with open(fname, 'rt') as f:\n for line in f:\n split = line.split()\n k = split[0]\n counts = [int(c) for c in split[2:]]\n data.append((k, counts))\n return data\n\n\ndef med(x):\n x = sorted(x)\n length = len(x)\n if not length % 2:\n return (x[length / 2] + x[(length - 1) / 2]) / 2.0\n return float(x[length / 2])\n\n\ndef plot_sd(data):\n x = numpy.array([(i + 1) for i in range(len(data[0]))])\n d = numpy.std(data[1], axis=1)\n pyplot.bar(x, d)\n pyplot.xticks(x + 0.5, data[0], rotation=90)\n ylim = pyplot.ylim()\n pyplot.ylim((ylim[0] - 10, ylim[1] + 10))\n pyplot.xlim((x[0] - 1, x[-1] + 1))\n pyplot.subplots_adjust(left=0.1, right=0.9, top=0.95, bottom=0.2)\n pyplot.title('Residue contribution standard deviations')\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef parse_args():\n import argparse\n import os.path\n\n def isfile(path):\n Error = argparse.ArgumentTypeError\n if not os.path.exists(path):\n raise Error(\"No such file: '{0}'\".format(path))\n elif not os.path.isfile(path):\n raise Error(\"Not a valid file: '{0}'\".format(path))\n return path\n hf = lambda prog: argparse.HelpFormatter(prog, max_help_position=50)\n parser = argparse.ArgumentParser(description=__doc__, formatter_class=hf)\n parser.add_argument('filename', type=isfile, help='contribution data file')\n parser.add_argument('-o', '--output', help='output file name')\n parser.add_argument('-n', type=int, default=0, help=\n 'show n greatest contributions')\n parser.add_argument('-s', '--stdev', action='store_true', help=\n 'only plot standard deviations')\n parser.add_argument('-r', metavar='residue', nargs='+', help=\n 'plot specific residues along time')\n return parser.parse_args()\n\n\ndef die(s):\n print >> sys.stderr, 'ERROR:', s\n exit(1)\n\n\ndef show_usage():\n print >> sys.stderr, 'usage: python ' + sys.argv[0] + ' <filename.dat>'\n\n\ndef read_contrib(fname):\n data = []\n with open(fname, 'rt') as f:\n for line in f:\n split = line.split()\n k = split[0]\n counts = [int(c) for c in split[2:]]\n data.append((k, counts))\n return data\n\n\ndef med(x):\n x = sorted(x)\n length = len(x)\n if not length % 2:\n return (x[length / 2] + x[(length - 1) / 2]) / 2.0\n return float(x[length / 2])\n\n\ndef plot_sd(data):\n x = numpy.array([(i + 1) for i in range(len(data[0]))])\n d = numpy.std(data[1], axis=1)\n pyplot.bar(x, d)\n pyplot.xticks(x + 0.5, data[0], rotation=90)\n ylim = pyplot.ylim()\n pyplot.ylim((ylim[0] - 10, ylim[1] + 10))\n pyplot.xlim((x[0] - 1, x[-1] + 1))\n pyplot.subplots_adjust(left=0.1, right=0.9, top=0.95, bottom=0.2)\n pyplot.title('Residue contribution standard deviations')\n\n\ndef plot_barplot(data):\n x = [(i + 1) for i in range(len(data[0]))]\n pyplot.boxplot(data[1])\n pyplot.xticks(x, data[0], rotation=90)\n ylim = pyplot.ylim()\n pyplot.ylim((ylim[0] - 10, ylim[1] + 10))\n pyplot.subplots_adjust(left=0.1, right=0.9, top=0.95, bottom=0.2)\n pyplot.title('Residue contribution')\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef parse_args():\n import argparse\n import os.path\n\n def isfile(path):\n Error = argparse.ArgumentTypeError\n if not os.path.exists(path):\n raise Error(\"No such file: '{0}'\".format(path))\n elif not os.path.isfile(path):\n raise Error(\"Not a valid file: '{0}'\".format(path))\n return path\n hf = lambda prog: argparse.HelpFormatter(prog, max_help_position=50)\n parser = argparse.ArgumentParser(description=__doc__, formatter_class=hf)\n parser.add_argument('filename', type=isfile, help='contribution data file')\n parser.add_argument('-o', '--output', help='output file name')\n parser.add_argument('-n', type=int, default=0, help=\n 'show n greatest contributions')\n parser.add_argument('-s', '--stdev', action='store_true', help=\n 'only plot standard deviations')\n parser.add_argument('-r', metavar='residue', nargs='+', help=\n 'plot specific residues along time')\n return parser.parse_args()\n\n\ndef die(s):\n print >> sys.stderr, 'ERROR:', s\n exit(1)\n\n\ndef show_usage():\n print >> sys.stderr, 'usage: python ' + sys.argv[0] + ' <filename.dat>'\n\n\ndef read_contrib(fname):\n data = []\n with open(fname, 'rt') as f:\n for line in f:\n split = line.split()\n k = split[0]\n counts = [int(c) for c in split[2:]]\n data.append((k, counts))\n return data\n\n\ndef med(x):\n x = sorted(x)\n length = len(x)\n if not length % 2:\n return (x[length / 2] + x[(length - 1) / 2]) / 2.0\n return float(x[length / 2])\n\n\ndef plot_sd(data):\n x = numpy.array([(i + 1) for i in range(len(data[0]))])\n d = numpy.std(data[1], axis=1)\n pyplot.bar(x, d)\n pyplot.xticks(x + 0.5, data[0], rotation=90)\n ylim = pyplot.ylim()\n pyplot.ylim((ylim[0] - 10, ylim[1] + 10))\n pyplot.xlim((x[0] - 1, x[-1] + 1))\n pyplot.subplots_adjust(left=0.1, right=0.9, top=0.95, bottom=0.2)\n pyplot.title('Residue contribution standard deviations')\n\n\ndef plot_barplot(data):\n x = [(i + 1) for i in range(len(data[0]))]\n pyplot.boxplot(data[1])\n pyplot.xticks(x, data[0], rotation=90)\n ylim = pyplot.ylim()\n pyplot.ylim((ylim[0] - 10, ylim[1] + 10))\n pyplot.subplots_adjust(left=0.1, right=0.9, top=0.95, bottom=0.2)\n pyplot.title('Residue contribution')\n\n\n<mask token>\n\n\ndef main():\n args = parse_args()\n data = read_contrib(args.filename)\n if args.n:\n data = sorted(data, key=lambda x: med(x[1]), reverse=True)\n data = data[:args.n]\n data = zip(*data)\n if args.r:\n plot_residues(data, args.r)\n elif args.stdev:\n plot_sd(data)\n else:\n plot_barplot(data)\n if args.output:\n pyplot.savefig(args.output)\n else:\n pyplot.show()\n\n\n<mask token>\n",
"step-4": "<mask token>\nimport sys\nif sys.version < '2.7':\n print >> sys.stderr, 'ERROR: This script requires Python 2.7.x. Please install it and try again.'\n exit(1)\ntry:\n import matplotlib.pyplot as pyplot\n import numpy\nexcept ImportError:\n print >> sys.stderr, 'ERROR:'\n print >> sys.stderr, 'This script requires matplotlib and numpy. Please make sure you installed it and that your PYTHONPATH is set adequately.'\n exit(1)\n\n\ndef parse_args():\n import argparse\n import os.path\n\n def isfile(path):\n Error = argparse.ArgumentTypeError\n if not os.path.exists(path):\n raise Error(\"No such file: '{0}'\".format(path))\n elif not os.path.isfile(path):\n raise Error(\"Not a valid file: '{0}'\".format(path))\n return path\n hf = lambda prog: argparse.HelpFormatter(prog, max_help_position=50)\n parser = argparse.ArgumentParser(description=__doc__, formatter_class=hf)\n parser.add_argument('filename', type=isfile, help='contribution data file')\n parser.add_argument('-o', '--output', help='output file name')\n parser.add_argument('-n', type=int, default=0, help=\n 'show n greatest contributions')\n parser.add_argument('-s', '--stdev', action='store_true', help=\n 'only plot standard deviations')\n parser.add_argument('-r', metavar='residue', nargs='+', help=\n 'plot specific residues along time')\n return parser.parse_args()\n\n\ndef die(s):\n print >> sys.stderr, 'ERROR:', s\n exit(1)\n\n\ndef show_usage():\n print >> sys.stderr, 'usage: python ' + sys.argv[0] + ' <filename.dat>'\n\n\ndef read_contrib(fname):\n data = []\n with open(fname, 'rt') as f:\n for line in f:\n split = line.split()\n k = split[0]\n counts = [int(c) for c in split[2:]]\n data.append((k, counts))\n return data\n\n\ndef med(x):\n x = sorted(x)\n length = len(x)\n if not length % 2:\n return (x[length / 2] + x[(length - 1) / 2]) / 2.0\n return float(x[length / 2])\n\n\ndef plot_sd(data):\n x = numpy.array([(i + 1) for i in range(len(data[0]))])\n d = numpy.std(data[1], axis=1)\n pyplot.bar(x, d)\n pyplot.xticks(x + 0.5, data[0], rotation=90)\n ylim = pyplot.ylim()\n pyplot.ylim((ylim[0] - 10, ylim[1] + 10))\n pyplot.xlim((x[0] - 1, x[-1] + 1))\n pyplot.subplots_adjust(left=0.1, right=0.9, top=0.95, bottom=0.2)\n pyplot.title('Residue contribution standard deviations')\n\n\ndef plot_barplot(data):\n x = [(i + 1) for i in range(len(data[0]))]\n pyplot.boxplot(data[1])\n pyplot.xticks(x, data[0], rotation=90)\n ylim = pyplot.ylim()\n pyplot.ylim((ylim[0] - 10, ylim[1] + 10))\n pyplot.subplots_adjust(left=0.1, right=0.9, top=0.95, bottom=0.2)\n pyplot.title('Residue contribution')\n\n\ndef plot_residues(data, residues):\n\n def running_average(x, N):\n return numpy.convolve(x, numpy.ones((N,)) / N)[N - 1:]\n if 'all' in residues:\n residues = data[0]\n for r in residues:\n try:\n i = data[0].index(r)\n except:\n die(\"No residue named '{0}'\".format(r))\n y = data[1][i]\n pyplot.plot(y, label=r)\n pyplot.legend(loc='best')\n\n\ndef main():\n args = parse_args()\n data = read_contrib(args.filename)\n if args.n:\n data = sorted(data, key=lambda x: med(x[1]), reverse=True)\n data = data[:args.n]\n data = zip(*data)\n if args.r:\n plot_residues(data, args.r)\n elif args.stdev:\n plot_sd(data)\n else:\n plot_barplot(data)\n if args.output:\n pyplot.savefig(args.output)\n else:\n pyplot.show()\n\n\nif __name__ == '__main__':\n main()\n",
"step-5": "#!/usr/bin/env python\n\n\"\"\"This script draws a boxplot of each atom contribution to the cavity.\"\"\"\n\n\nimport sys\n\nif sys.version < \"2.7\":\n print >> sys.stderr, \"ERROR: This script requires Python 2.7.x. \"\\\n \"Please install it and try again.\"\n exit(1)\n\ntry:\n import matplotlib.pyplot as pyplot\n import numpy\nexcept ImportError:\n print >> sys.stderr, \"ERROR:\",\n print >> sys.stderr, \"This script requires matplotlib and numpy. \"\\\n \"Please make sure you installed it and that \"\\\n \"your PYTHONPATH is set adequately.\"\n exit(1)\n\n\ndef parse_args():\n import argparse\n import os.path\n\n def isfile(path):\n Error = argparse.ArgumentTypeError\n if not os.path.exists(path):\n raise Error(\"No such file: '{0}'\".format(path))\n elif not os.path.isfile(path):\n raise Error(\"Not a valid file: '{0}'\".format(path))\n return path\n\n hf = lambda prog: argparse.HelpFormatter(prog, max_help_position=50)\n parser = argparse.ArgumentParser(description=__doc__, formatter_class=hf)\n parser.add_argument(\"filename\", type=isfile,\n help=\"contribution data file\")\n parser.add_argument(\"-o\", \"--output\",\n help=\"output file name\")\n parser.add_argument(\"-n\", type=int, default=0,\n help=\"show n greatest contributions\")\n parser.add_argument(\"-s\", \"--stdev\", action=\"store_true\",\n help=\"only plot standard deviations\")\n parser.add_argument(\"-r\", metavar=\"residue\", nargs=\"+\",\n help=\"plot specific residues along time\")\n return parser.parse_args()\n\n\ndef die(s):\n print >> sys.stderr, \"ERROR:\", s\n exit(1)\n\n\ndef show_usage():\n print >> sys.stderr, \"usage: python \" + sys.argv[0] + \" <filename.dat>\"\n\n\ndef read_contrib(fname):\n data = []\n with open(fname, \"rt\") as f:\n for line in f:\n split = line.split()\n k = split[0]\n counts = [int(c) for c in split[2:]]\n data.append((k, counts))\n return data\n\n\ndef med(x):\n x = sorted(x)\n length = len(x)\n if not length % 2:\n return (x[length / 2] + x[(length - 1) / 2]) / 2.0\n return float(x[length / 2])\n\n\ndef plot_sd(data):\n x = numpy.array([i+1 for i in range(len(data[0]))])\n d = numpy.std(data[1], axis=1)\n pyplot.bar(x, d)\n pyplot.xticks(x+.5, data[0], rotation=90)\n ylim = pyplot.ylim()\n pyplot.ylim((ylim[0]-10, ylim[1]+10))\n pyplot.xlim((x[0]-1, x[-1]+1))\n pyplot.subplots_adjust(left=0.1, right=0.9, top=0.95, bottom=0.2)\n pyplot.title(\"Residue contribution standard deviations\")\n\n\ndef plot_barplot(data):\n x = [i+1 for i in range(len(data[0]))]\n pyplot.boxplot(data[1])\n pyplot.xticks(x, data[0], rotation=90)\n ylim = pyplot.ylim()\n pyplot.ylim((ylim[0]-10, ylim[1]+10))\n pyplot.subplots_adjust(left=0.1, right=0.9, top=0.95, bottom=0.2)\n pyplot.title(\"Residue contribution\")\n\n\ndef plot_residues(data, residues):\n def running_average(x, N):\n return numpy.convolve(x, numpy.ones((N,))/N)[(N-1):]\n if \"all\" in residues:\n residues = data[0]\n for r in residues:\n try:\n i = data[0].index(r)\n except:\n die(\"No residue named '{0}'\".format(r))\n# y = running_average(data[1][i], 5)\n y = data[1][i]\n pyplot.plot(y, label=r)\n pyplot.legend(loc=\"best\")\n\n\ndef main():\n args = parse_args()\n data = read_contrib(args.filename)\n\n if args.n:\n data = sorted(data, key=lambda x: med(x[1]), reverse=True)\n data = data[:args.n]\n\n data = zip(*data)\n\n if args.r:\n plot_residues(data, args.r)\n elif args.stdev:\n plot_sd(data)\n else:\n plot_barplot(data)\n\n if args.output:\n pyplot.savefig(args.output)\n else:\n pyplot.show()\n\n\nif __name__ == '__main__':\n main()\n",
"step-ids": [
6,
7,
8,
11,
12
]
}
|
[
6,
7,
8,
11,
12
] |
class Node:
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insertAtHead(self, newNode, curNode):
newNode.next = curNode
if curNode is not None: curNode.prev = newNode
self.head = newNode
def insertAtTail(self, newNode, curNode):
if self.head is None:
self.head = newNode
return
while curNode.next is not None:
curNode = curNode.next
curNode.next = newNode
newNode.prev = curNode
def printForward(self, curNode):
while curNode is not None:
print(curNode.data)
curNode = curNode.next
def printReverse(self, curNode):
while curNode.next is not None:
curNode = curNode.next
while curNode is not None:
print(curNode.data)
curNode = curNode.prev
################################################
linkedList = LinkedList()
for i in range(3):
newNode = Node(input("Enter data: "))
#linkedList.insertAtTail(newNode, linkedList.head)
linkedList.insertAtHead(newNode, linkedList.head)
linkedList.printForward(linkedList.head)
print("######################")
linkedList.printReverse(linkedList.head)
|
normal
|
{
"blob_id": "a3cbdecbbfc49e8ac045f4aabbea6b9f54ed3d5f",
"index": 4904,
"step-1": "<mask token>\n\n\nclass LinkedList:\n\n def __init__(self):\n self.head = None\n\n def insertAtHead(self, newNode, curNode):\n newNode.next = curNode\n if curNode is not None:\n curNode.prev = newNode\n self.head = newNode\n <mask token>\n\n def printForward(self, curNode):\n while curNode is not None:\n print(curNode.data)\n curNode = curNode.next\n\n def printReverse(self, curNode):\n while curNode.next is not None:\n curNode = curNode.next\n while curNode is not None:\n print(curNode.data)\n curNode = curNode.prev\n\n\n<mask token>\n",
"step-2": "class Node:\n <mask token>\n\n\nclass LinkedList:\n\n def __init__(self):\n self.head = None\n\n def insertAtHead(self, newNode, curNode):\n newNode.next = curNode\n if curNode is not None:\n curNode.prev = newNode\n self.head = newNode\n\n def insertAtTail(self, newNode, curNode):\n if self.head is None:\n self.head = newNode\n return\n while curNode.next is not None:\n curNode = curNode.next\n curNode.next = newNode\n newNode.prev = curNode\n\n def printForward(self, curNode):\n while curNode is not None:\n print(curNode.data)\n curNode = curNode.next\n\n def printReverse(self, curNode):\n while curNode.next is not None:\n curNode = curNode.next\n while curNode is not None:\n print(curNode.data)\n curNode = curNode.prev\n\n\n<mask token>\n",
"step-3": "class Node:\n\n def __init__(self, data):\n self.data = data\n self.prev = None\n self.next = None\n\n\nclass LinkedList:\n\n def __init__(self):\n self.head = None\n\n def insertAtHead(self, newNode, curNode):\n newNode.next = curNode\n if curNode is not None:\n curNode.prev = newNode\n self.head = newNode\n\n def insertAtTail(self, newNode, curNode):\n if self.head is None:\n self.head = newNode\n return\n while curNode.next is not None:\n curNode = curNode.next\n curNode.next = newNode\n newNode.prev = curNode\n\n def printForward(self, curNode):\n while curNode is not None:\n print(curNode.data)\n curNode = curNode.next\n\n def printReverse(self, curNode):\n while curNode.next is not None:\n curNode = curNode.next\n while curNode is not None:\n print(curNode.data)\n curNode = curNode.prev\n\n\n<mask token>\n",
"step-4": "class Node:\n\n def __init__(self, data):\n self.data = data\n self.prev = None\n self.next = None\n\n\nclass LinkedList:\n\n def __init__(self):\n self.head = None\n\n def insertAtHead(self, newNode, curNode):\n newNode.next = curNode\n if curNode is not None:\n curNode.prev = newNode\n self.head = newNode\n\n def insertAtTail(self, newNode, curNode):\n if self.head is None:\n self.head = newNode\n return\n while curNode.next is not None:\n curNode = curNode.next\n curNode.next = newNode\n newNode.prev = curNode\n\n def printForward(self, curNode):\n while curNode is not None:\n print(curNode.data)\n curNode = curNode.next\n\n def printReverse(self, curNode):\n while curNode.next is not None:\n curNode = curNode.next\n while curNode is not None:\n print(curNode.data)\n curNode = curNode.prev\n\n\n<mask token>\nfor i in range(3):\n newNode = Node(input('Enter data: '))\n linkedList.insertAtHead(newNode, linkedList.head)\nlinkedList.printForward(linkedList.head)\nprint('######################')\nlinkedList.printReverse(linkedList.head)\n",
"step-5": "class Node:\n def __init__(self, data):\n self.data = data\n self.prev = None\n self.next = None\n\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n\n\n def insertAtHead(self, newNode, curNode):\n newNode.next = curNode\n if curNode is not None: curNode.prev = newNode\n self.head = newNode\n\n\n def insertAtTail(self, newNode, curNode):\n if self.head is None:\n self.head = newNode\n return\n \n while curNode.next is not None:\n curNode = curNode.next\n \n curNode.next = newNode\n newNode.prev = curNode\n\n\n def printForward(self, curNode):\n while curNode is not None:\n print(curNode.data)\n curNode = curNode.next\n\n\n def printReverse(self, curNode):\n while curNode.next is not None:\n curNode = curNode.next\n\n while curNode is not None:\n print(curNode.data)\n curNode = curNode.prev\n\n\n################################################\n\n\nlinkedList = LinkedList()\n\nfor i in range(3):\n newNode = Node(input(\"Enter data: \"))\n #linkedList.insertAtTail(newNode, linkedList.head)\n linkedList.insertAtHead(newNode, linkedList.head)\n\nlinkedList.printForward(linkedList.head)\nprint(\"######################\")\nlinkedList.printReverse(linkedList.head)",
"step-ids": [
5,
7,
8,
9,
11
]
}
|
[
5,
7,
8,
9,
11
] |
#!/usr/bin/env python
#
# ConVirt - Copyright (c) 2008 Convirture Corp.
# ======
#
# ConVirt is a Virtualization management tool with a graphical user
# interface that allows for performing the standard set of VM operations
# (start, stop, pause, kill, shutdown, reboot, snapshot, etc...). It
# also attempts to simplify various aspects of VM lifecycle management.
#
#
# This software is subject to the GNU General Public License, Version 2 (GPLv2)
# and for details, please consult it at:
#
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt
#
#
# author : Jd <jd_jedi@users.sourceforge.net>
#
import paramiko
from paramiko import SSHException
import os, sys
import getpass
import socket
from convirt.core.utils.utils import to_unicode,to_str
"""Paramiko helper class. Provides common functions as
-- validating host keys,
-- initializing a new transport,
-- agent based and password based authentication etc.
"""
class HostValidationException(Exception):
def __init__(self, errno, description):
Exception.__init__(self, errno, description)
self.errno = errno
self.description = description
def __repr__(self):
return "[Error %s], %s" % (self.errno, self.description)
def __str__(self):
return self.__repr__()
class AuthenticationException(Exception):
def __init__(self, errno, description):
Exception.__init__(self, errno, description)
self.errno = errno
self.description = description
def __repr__(self):
return "[Error %s], %s" % (self.errno, self.description)
def __str__(self):
return self.__repr__()
class CommunicationException(Exception):
def __init__(self, errno, description):
Exception.__init__(self, errno, description)
self.errno = errno
self.description = description
def __repr__(self):
return "[Error %s], %s" % (self.errno, self.description)
def __str__(self):
return self.__repr__()
class PHelper:
host_keys = {}
# credential helper
credentials_helper = None
## The credendital helper needs to get_credentials(hostname) method
## to return credentials
## the object returned should:
## get_username() and get_password() methods
## This would be used when the transport can not be initialized
## using given methods
@classmethod
def set_credentials_helper(cls, cred_helper):
""" Set the helper class"""
cls.credentials_helper = cred_helper
@classmethod
def load_keys(cls):
# TODO : May be we need to load /etc/ssh/known_hosts and merge it here.
try:
path = os.path.expanduser('~/.ssh/known_hosts')
cls.host_keys = paramiko.util.load_host_keys(path)
except IOError:
try:
path = os.path.expanduser('~/ssh/known_hosts')
cls.host_keys = paramiko.util.load_host_keys(path)
except IOError:
pass
@classmethod
def init_log(cls,log_file_name):
try:
paramiko.util.log_to_file(log_file_name)
except Exception ,ex:
print "Error initializing paramiko log.", ex
@classmethod
def validate_host_key(cls, transport, hostname):
"""
get the remote hosts key and validate against known host keys
throws exception with errno, reason
errno - reason
1 - Host not found
2. - Host found but key not found
3 - Authentication failed (wrong password?)
4 - Host found, key found, but keys do not match
(server changed/spoofed)
"""
# check server's host key -- this is important.
key = transport.get_remote_server_key()
if not PHelper.host_keys.has_key(hostname):
print "Warning : Host not found ! ", hostname
#raise HostValidationException(1, "Host not found")
elif not PHelper.host_keys[hostname].has_key(key.get_name()):
print "Warning: Key not found ! ", hostname
#raise HostValidationException(2, "Key not found.")
elif PHelper.host_keys[hostname][key.get_name()] != key:
raise HostValidationException(3, "Keys mismatch for " + hostname)
return True
## TODO : only for testing purpose
@classmethod
def interactive_auth(cls, transport, username, hostname):
default_auth = 'p'
auth = raw_input('Auth by (p)assword, (r)sa key, or (d)ss key? [%s] ' % default_auth)
if len(auth) == 0:
auth = default_auth
if auth == 'r':
default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
path = raw_input('RSA key [%s]: ' % default_path)
if len(path) == 0:
path = default_path
try:
key = paramiko.RSAKey.from_private_key_file(path)
except paramiko.PasswordRequiredException:
password = getpass.getpass('RSA key password: ')
key = paramiko.RSAKey.from_private_key_file(path, password)
transport.auth_publickey(username, key)
elif auth == 'd':
default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa')
path = raw_input('DSS key [%s]: ' % default_path)
if len(path) == 0:
path = default_path
try:
key = paramiko.DSSKey.from_private_key_file(path)
except paramiko.PasswordRequiredException:
password = getpass.getpass('DSS key password: ')
key = paramiko.DSSKey.from_private_key_file(path, password)
transport.auth_publickey(username, key)
else:
pw = getpass.getpass('Password for %s@%s: ' % (username, hostname))
transport.auth_password(username, pw)
#TODO : refine this.. and test it with passphrase, may be catch
# some other exception, if passphrase is wrong.
@classmethod
def authenticate(cls, transport, authtype,
keyfile=None, passphrase=None,
username=None, password=None):
default_authtype = 'password'
if authtype==None or len(authtype) == 0:
authtype = default_authtype
try:
if authtype == 'rsa':
default_keyfile = os.path.join(os.environ['HOME'],
'.ssh', 'id_rsa')
if keyfile == None or len(keyfile) == 0:
keyfile = default_keyfile
key = paramiko.RSAKey.from_private_key_file(keyfile,
passphrase)
elif authtype == 'dsa':
default_keyfile = os.path.join(os.environ['HOME'],
'.ssh', 'id_dsa')
if keyfile == None or len(keyfile) == 0:
keyfile = default_keyfile
key = paramiko.DSSKey.from_private_key_file(keyfile,
passphrase)
if authtype == 'rsa' or authtype == 'dsa':
transport.auth_publickey(username, key)
else:
transport.auth_password(username, password)
except paramiko.PasswordRequiredException, ex:
raise AuthenticationException(1, "Password required")
except paramiko.BadAuthenticationType, ex:
raise AuthenticationException(2, "Bad authentication type")
except paramiko.AuthenticationException, ex:
raise AuthenticationException(3, "Authentication failed.")
except paramiko.SSHException ,ex:
raise AuthenticationException(4,
"Invalid key file %s" % keyfile)
@classmethod
def agent_auth(cls, transport, username):
"""
Attempt to authenticate to the given transport using any of the private
keys available from an SSH agent.
return True, if the transport is authenticated
raises: AuthenticationException when network errro
"""
agent = paramiko.Agent()
agent_keys = agent.get_keys()
if len(agent_keys) == 0:
#print "Warning: No keys found loaded in ssh-agent. Forgot to use ssh-add ?"
return
for key in agent_keys:
#print 'Trying ssh-agent key %s' % \
# paramiko.util.hexify(key.get_fingerprint()),
try:
transport.auth_publickey(username, key)
if not transport.is_authenticated():
continue
else:
break
except paramiko.AuthenticationException, e:
print "Used key from agent. Auth failed. Will skip it."
pass
except SSHException, ex:
raise CommunicationException(0, "[agent_auth]:" + to_str(ex))
@classmethod
def init_ssh_transport(cls, hostname, ssh_port=22,
authtype=None, keyfile=None,passphrase=None,
username=None, password=None):
try:
### Open SSH transport
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#
#TODO timeout value should be configurable from server pool
#
sock.settimeout(1)
sock.connect((to_str(hostname), ssh_port))
transport = paramiko.Transport(sock)
transport.start_client()
# validate the host key
cls.validate_host_key(transport, hostname)
# if username and password provided assume it is password
# type authentication
if not transport.is_authenticated() and authtype == None:
if username != None and password != None:
try:
cls.authenticate(transport,'password',
keyfile,passphrase,
username, password)
except AuthenticationException ,ex:
if ex.errno == 3 and cls.credentials_helper is not None:
# give a chance to cred helper to prompt
pass
else:
transport.close()
raise
## authenticate with the auth type provided.
if not transport.is_authenticated() and authtype != None:
try:
if authtype == "agent":
cls.agent_auth(transport, username)
if not transport.is_authenticated():
raise AuthenticationException(0,"Agent authentication failed")
else:
cls.authenticate(transport,authtype, keyfile,passphrase,
username, password)
except AuthenticationException ,ex:
if authtype == 'password' and \
ex.errno == 3 and \
cls.credentials_helper is not None:
# give a chance to cred helper to prompt
pass
else:
transport.close()
raise
# authenticate interactive way. just for testing
#if not transport.is_authenticated():
# cls.interactive_auth(transport, username, hostname)
if not transport.is_authenticated() and \
cls.credentials_helper is not None:
creds = cls.credentials_helper.get_credentials(hostname)
if creds is not None:
username = creds.get_username()
password = creds.get_password()
cls.authenticate(transport,'password',
keyfile,passphrase,
username, password)
if not transport.is_authenticated():
transport.close()
raise AuthenticationException("0",
hostname + " is not authenticated")
return transport
except socket.timeout : # clients may wish to treat this differently
raise
except socket.error, ex:
raise CommunicationException(0, to_str(ex))
## pass through method
@classmethod
def open_channel(cls,transport, kind, dest_addr=None, src_addr=None):
try:
ch = transport.open_channel(kind, dest_addr, src_addr)
except SSHException, ex:
raise CommunicationException(0, "[open_channel]" +to_str(ex))
return ch
# initialize key store
PHelper.load_keys()
#TODO : Add some test cases here.
if __name__ == "__main__":
host = "192.168.12.100"
#Test with passphrase
## t = PHelper.init_ssh_transport(host,
## authtype="rsa", passphrase="welcome",
## username = "root")
# Test with ssh-agent
t = PHelper.init_ssh_transport(host, username="root", authtype="agent")
ch = PHelper.open_channel(t, "session")
ch.close()
|
normal
|
{
"blob_id": "3078a0c7e2c711da88846ca3401c7924b1790dbc",
"index": 1251,
"step-1": "#!/usr/bin/env python\n#\n# ConVirt - Copyright (c) 2008 Convirture Corp.\n# ======\n#\n# ConVirt is a Virtualization management tool with a graphical user\n# interface that allows for performing the standard set of VM operations\n# (start, stop, pause, kill, shutdown, reboot, snapshot, etc...). It\n# also attempts to simplify various aspects of VM lifecycle management.\n#\n#\n# This software is subject to the GNU General Public License, Version 2 (GPLv2)\n# and for details, please consult it at:\n#\n# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt\n# \n#\n# author : Jd <jd_jedi@users.sourceforge.net>\n#\n\nimport paramiko\nfrom paramiko import SSHException\nimport os, sys\nimport getpass\nimport socket\nfrom convirt.core.utils.utils import to_unicode,to_str\n\"\"\"Paramiko helper class. Provides common functions as\n -- validating host keys,\n -- initializing a new transport,\n -- agent based and password based authentication etc.\n\"\"\"\nclass HostValidationException(Exception):\n def __init__(self, errno, description):\n Exception.__init__(self, errno, description)\n self.errno = errno\n self.description = description\n\n def __repr__(self):\n return \"[Error %s], %s\" % (self.errno, self.description)\n\n def __str__(self):\n return self.__repr__()\n\nclass AuthenticationException(Exception):\n def __init__(self, errno, description):\n Exception.__init__(self, errno, description)\n self.errno = errno\n self.description = description\n\n def __repr__(self):\n return \"[Error %s], %s\" % (self.errno, self.description)\n \n def __str__(self):\n return self.__repr__()\n\n\nclass CommunicationException(Exception):\n def __init__(self, errno, description):\n Exception.__init__(self, errno, description)\n self.errno = errno\n self.description = description\n\n def __repr__(self):\n return \"[Error %s], %s\" % (self.errno, self.description)\n\n def __str__(self):\n return self.__repr__()\n \n\n\nclass PHelper:\n \n host_keys = {}\n\n # credential helper\n credentials_helper = None\n\n ## The credendital helper needs to get_credentials(hostname) method\n ## to return credentials\n ## the object returned should:\n ## get_username() and get_password() methods\n ## This would be used when the transport can not be initialized\n ## using given methods\n \n @classmethod\n def set_credentials_helper(cls, cred_helper):\n \"\"\" Set the helper class\"\"\"\n cls.credentials_helper = cred_helper\n\n \n @classmethod\n def load_keys(cls):\n # TODO : May be we need to load /etc/ssh/known_hosts and merge it here.\n try:\n path = os.path.expanduser('~/.ssh/known_hosts')\n cls.host_keys = paramiko.util.load_host_keys(path)\n except IOError:\n try:\n path = os.path.expanduser('~/ssh/known_hosts')\n cls.host_keys = paramiko.util.load_host_keys(path)\n except IOError:\n pass\n\n\n @classmethod\n def init_log(cls,log_file_name):\n try:\n paramiko.util.log_to_file(log_file_name)\n except Exception ,ex:\n print \"Error initializing paramiko log.\", ex\n\n\n @classmethod\n def validate_host_key(cls, transport, hostname):\n \"\"\"\n get the remote hosts key and validate against known host keys\n throws exception with errno, reason\n errno - reason\n 1 - Host not found\n 2. - Host found but key not found\n 3 - Authentication failed (wrong password?)\n 4 - Host found, key found, but keys do not match\n (server changed/spoofed)\n \"\"\"\n # check server's host key -- this is important.\n key = transport.get_remote_server_key()\n if not PHelper.host_keys.has_key(hostname):\n print \"Warning : Host not found ! \", hostname\n #raise HostValidationException(1, \"Host not found\")\n elif not PHelper.host_keys[hostname].has_key(key.get_name()):\n print \"Warning: Key not found ! \", hostname\n #raise HostValidationException(2, \"Key not found.\")\n elif PHelper.host_keys[hostname][key.get_name()] != key:\n raise HostValidationException(3, \"Keys mismatch for \" + hostname)\n \n return True\n\n\n ## TODO : only for testing purpose\n @classmethod \n def interactive_auth(cls, transport, username, hostname):\n default_auth = 'p'\n auth = raw_input('Auth by (p)assword, (r)sa key, or (d)ss key? [%s] ' % default_auth)\n if len(auth) == 0:\n auth = default_auth\n\n if auth == 'r':\n default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')\n path = raw_input('RSA key [%s]: ' % default_path)\n if len(path) == 0:\n path = default_path\n try:\n key = paramiko.RSAKey.from_private_key_file(path)\n except paramiko.PasswordRequiredException:\n password = getpass.getpass('RSA key password: ')\n key = paramiko.RSAKey.from_private_key_file(path, password)\n transport.auth_publickey(username, key)\n elif auth == 'd':\n default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa')\n path = raw_input('DSS key [%s]: ' % default_path)\n if len(path) == 0:\n path = default_path\n try:\n key = paramiko.DSSKey.from_private_key_file(path)\n except paramiko.PasswordRequiredException:\n password = getpass.getpass('DSS key password: ')\n key = paramiko.DSSKey.from_private_key_file(path, password)\n transport.auth_publickey(username, key)\n else:\n pw = getpass.getpass('Password for %s@%s: ' % (username, hostname))\n transport.auth_password(username, pw)\n\n #TODO : refine this.. and test it with passphrase, may be catch\n # some other exception, if passphrase is wrong.\n @classmethod\n def authenticate(cls, transport, authtype,\n keyfile=None, passphrase=None,\n username=None, password=None):\n\n default_authtype = 'password'\n\n if authtype==None or len(authtype) == 0:\n authtype = default_authtype\n\n try:\n if authtype == 'rsa':\n default_keyfile = os.path.join(os.environ['HOME'],\n '.ssh', 'id_rsa')\n if keyfile == None or len(keyfile) == 0:\n keyfile = default_keyfile\n\n key = paramiko.RSAKey.from_private_key_file(keyfile,\n passphrase)\n \n elif authtype == 'dsa':\n default_keyfile = os.path.join(os.environ['HOME'],\n '.ssh', 'id_dsa')\n\n if keyfile == None or len(keyfile) == 0:\n keyfile = default_keyfile\n key = paramiko.DSSKey.from_private_key_file(keyfile,\n passphrase)\n \n if authtype == 'rsa' or authtype == 'dsa':\n transport.auth_publickey(username, key)\n else:\n transport.auth_password(username, password)\n \n except paramiko.PasswordRequiredException, ex:\n raise AuthenticationException(1, \"Password required\")\n except paramiko.BadAuthenticationType, ex:\n raise AuthenticationException(2, \"Bad authentication type\")\n except paramiko.AuthenticationException, ex:\n raise AuthenticationException(3, \"Authentication failed.\")\n except paramiko.SSHException ,ex:\n raise AuthenticationException(4,\n \"Invalid key file %s\" % keyfile)\n\n @classmethod\n def agent_auth(cls, transport, username):\n \"\"\"\n Attempt to authenticate to the given transport using any of the private\n keys available from an SSH agent.\n return True, if the transport is authenticated\n raises: AuthenticationException when network errro\n \"\"\"\n\n agent = paramiko.Agent()\n agent_keys = agent.get_keys()\n if len(agent_keys) == 0:\n #print \"Warning: No keys found loaded in ssh-agent. Forgot to use ssh-add ?\"\n return\n\n for key in agent_keys:\n #print 'Trying ssh-agent key %s' % \\\n # paramiko.util.hexify(key.get_fingerprint()),\n try:\n transport.auth_publickey(username, key)\n if not transport.is_authenticated():\n continue\n else:\n break\n except paramiko.AuthenticationException, e:\n print \"Used key from agent. Auth failed. Will skip it.\"\n pass\n except SSHException, ex:\n raise CommunicationException(0, \"[agent_auth]:\" + to_str(ex))\n \n \n @classmethod \n def init_ssh_transport(cls, hostname, ssh_port=22,\n authtype=None, keyfile=None,passphrase=None,\n username=None, password=None):\n\n try:\n ### Open SSH transport\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n #\n #TODO timeout value should be configurable from server pool\n #\n sock.settimeout(1)\n sock.connect((to_str(hostname), ssh_port)) \n\n transport = paramiko.Transport(sock)\n transport.start_client()\n\n # validate the host key\n cls.validate_host_key(transport, hostname)\n\n\n # if username and password provided assume it is password\n # type authentication\n if not transport.is_authenticated() and authtype == None:\n if username != None and password != None:\n try:\n cls.authenticate(transport,'password',\n keyfile,passphrase,\n username, password)\n except AuthenticationException ,ex:\n if ex.errno == 3 and cls.credentials_helper is not None:\n # give a chance to cred helper to prompt\n pass\n else:\n transport.close()\n raise\n \n\n\n ## authenticate with the auth type provided.\n if not transport.is_authenticated() and authtype != None:\n try:\n if authtype == \"agent\":\n cls.agent_auth(transport, username)\n if not transport.is_authenticated():\n raise AuthenticationException(0,\"Agent authentication failed\")\n \n else:\n cls.authenticate(transport,authtype, keyfile,passphrase,\n username, password)\n \n except AuthenticationException ,ex:\n if authtype == 'password' and \\\n ex.errno == 3 and \\\n cls.credentials_helper is not None:\n # give a chance to cred helper to prompt\n pass\n else:\n transport.close()\n raise\n \n\n # authenticate interactive way. just for testing\n #if not transport.is_authenticated():\n # cls.interactive_auth(transport, username, hostname)\n\n if not transport.is_authenticated() and \\\n cls.credentials_helper is not None:\n creds = cls.credentials_helper.get_credentials(hostname)\n if creds is not None:\n username = creds.get_username()\n password = creds.get_password()\n cls.authenticate(transport,'password',\n keyfile,passphrase,\n username, password)\n\n\n if not transport.is_authenticated():\n transport.close()\n raise AuthenticationException(\"0\",\n hostname + \" is not authenticated\")\n return transport\n\n except socket.timeout : # clients may wish to treat this differently\n raise\n except socket.error, ex:\n raise CommunicationException(0, to_str(ex))\n \n\n\n ## pass through method\n @classmethod\n def open_channel(cls,transport, kind, dest_addr=None, src_addr=None):\n try:\n ch = transport.open_channel(kind, dest_addr, src_addr)\n except SSHException, ex:\n raise CommunicationException(0, \"[open_channel]\" +to_str(ex))\n return ch\n \n \n# initialize key store\nPHelper.load_keys()\n\n#TODO : Add some test cases here.\nif __name__ == \"__main__\":\n host = \"192.168.12.100\"\n \n #Test with passphrase\n## t = PHelper.init_ssh_transport(host,\n## authtype=\"rsa\", passphrase=\"welcome\",\n## username = \"root\")\n # Test with ssh-agent\n t = PHelper.init_ssh_transport(host, username=\"root\", authtype=\"agent\")\n ch = PHelper.open_channel(t, \"session\")\n ch.close()\n\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
def multiplica():
one = int(input('1º: '))
two = int(input('2º: '))
print('a multiplicação é: ', one*two)
def soma():
one = int(input('1º: '))
two = int(input('2º: '))
print('a soma é: ', one+two)
def subtra():
one = int(input('1º: '))
two = int(input('2º: '))
print('a subtração é: ', one-two)
ans=True
while ans:
print ("""
1.Multiplicação
2.Soma
3.Subtração
4.Exit/Quit
""")
ans= int(input("What would you like to do? "))
if ans== 1:
multiplica()
elif ans== 2:
print("\n Student Deleted")
elif ans== 3:
print("\n Student Record Found")
elif ans== 4:
print("\n Goodbye")
exit()
else:
print("\n Not Valid Choice Try again")
|
normal
|
{
"blob_id": "414fa4021b21cea0dc49380aebfe67f0204f0574",
"index": 5994,
"step-1": "def multiplica():\n one = int(input('1º: '))\n two = int(input('2º: '))\n print('a multiplicação é: ', one * two)\n\n\ndef soma():\n one = int(input('1º: '))\n two = int(input('2º: '))\n print('a soma é: ', one + two)\n\n\n<mask token>\n",
"step-2": "def multiplica():\n one = int(input('1º: '))\n two = int(input('2º: '))\n print('a multiplicação é: ', one * two)\n\n\ndef soma():\n one = int(input('1º: '))\n two = int(input('2º: '))\n print('a soma é: ', one + two)\n\n\ndef subtra():\n one = int(input('1º: '))\n two = int(input('2º: '))\n print('a subtração é: ', one - two)\n\n\n<mask token>\n",
"step-3": "def multiplica():\n one = int(input('1º: '))\n two = int(input('2º: '))\n print('a multiplicação é: ', one * two)\n\n\ndef soma():\n one = int(input('1º: '))\n two = int(input('2º: '))\n print('a soma é: ', one + two)\n\n\ndef subtra():\n one = int(input('1º: '))\n two = int(input('2º: '))\n print('a subtração é: ', one - two)\n\n\n<mask token>\nwhile ans:\n print(\n \"\"\"\n 1.Multiplicação\n 2.Soma\n 3.Subtração\n 4.Exit/Quit\n \"\"\"\n )\n ans = int(input('What would you like to do? '))\n if ans == 1:\n multiplica()\n elif ans == 2:\n print('\\n Student Deleted')\n elif ans == 3:\n print('\\n Student Record Found')\n elif ans == 4:\n print('\\n Goodbye')\n exit()\n else:\n print('\\n Not Valid Choice Try again')\n",
"step-4": "def multiplica():\n one = int(input('1º: '))\n two = int(input('2º: '))\n print('a multiplicação é: ', one * two)\n\n\ndef soma():\n one = int(input('1º: '))\n two = int(input('2º: '))\n print('a soma é: ', one + two)\n\n\ndef subtra():\n one = int(input('1º: '))\n two = int(input('2º: '))\n print('a subtração é: ', one - two)\n\n\nans = True\nwhile ans:\n print(\n \"\"\"\n 1.Multiplicação\n 2.Soma\n 3.Subtração\n 4.Exit/Quit\n \"\"\"\n )\n ans = int(input('What would you like to do? '))\n if ans == 1:\n multiplica()\n elif ans == 2:\n print('\\n Student Deleted')\n elif ans == 3:\n print('\\n Student Record Found')\n elif ans == 4:\n print('\\n Goodbye')\n exit()\n else:\n print('\\n Not Valid Choice Try again')\n",
"step-5": "def multiplica():\r\n one = int(input('1º: '))\r\n two = int(input('2º: '))\r\n\r\n print('a multiplicação é: ', one*two)\r\n\r\ndef soma():\r\n one = int(input('1º: '))\r\n two = int(input('2º: '))\r\n\r\n print('a soma é: ', one+two)\r\n \r\ndef subtra():\r\n one = int(input('1º: '))\r\n two = int(input('2º: '))\r\n\r\n print('a subtração é: ', one-two)\r\n\r\nans=True\r\nwhile ans:\r\n print (\"\"\"\r\n 1.Multiplicação\r\n 2.Soma\r\n 3.Subtração\r\n 4.Exit/Quit\r\n \"\"\")\r\n ans= int(input(\"What would you like to do? \"))\r\n if ans== 1: \r\n multiplica() \r\n elif ans== 2:\r\n print(\"\\n Student Deleted\") \r\n elif ans== 3:\r\n print(\"\\n Student Record Found\") \r\n elif ans== 4:\r\n print(\"\\n Goodbye\") \r\n exit()\r\n else:\r\n print(\"\\n Not Valid Choice Try again\") \r\n\r\n",
"step-ids": [
2,
3,
4,
5,
6
]
}
|
[
2,
3,
4,
5,
6
] |
from pyspark import SparkContext, RDD
from pyspark.sql import SparkSession, DataFrame
from pyspark.streaming import StreamingContext
from pyspark.streaming.kafka import KafkaUtils
import string
from kafka import KafkaProducer
import time
import pyspark
sc = SparkContext(master='local[4]')
ssc = StreamingContext(sc, batchDuration=10)
# producer = df \
# .selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)") \
# .writeStream \
# .format("kafka") \
# .option("kafka.bootstrap.servers", "host1:port1,host2:port2") \
# .option("topic", "topic1") \
# .start()
producer = KafkaProducer(bootstrap_servers=['mipt-node06.atp-fivt.org:9092'],
value_serializer=lambda x:
x.encode('utf-8'))
dstream = KafkaUtils.createDirectStream(
ssc, topics=['had2020011-topic'],
kafkaParams = {'metadata.broker.list': 'mipt-node06.atp-fivt.org:9092'}
)
import sys
keywords = ['lol', 'kek'] if len(sys.argv) <= 1 else sys.argv[1:]
remove = dict.fromkeys(map(ord, '\n ' + string.punctuation))
def send_rdd(rdd):
out_list = rdd.collect()
for word in out_list:
producer.send('had2020011-out', value=str(word))
initialized = False
def aggregator(values, old):
return (old or 0) + sum(values)
initState = sc.parallelize(list(zip(keywords, [0] * len(keywords))))
result = dstream \
.flatMap(lambda pair: pair[1].split(" ")) \
.map(lambda word: word.translate(remove)) \
.filter(lambda word: word in keywords) \
.map(lambda word: (word.lower(), 1)) \
.reduceByKeyAndWindow(lambda x, y: x + y, lambda x, y: x - y, 60, 60) \
.updateStateByKey(aggregator, initialRDD=initState) \
.foreachRDD(lambda rdd : send_rdd(rdd))
# \
ssc.checkpoint('./checkpoint{}'.format(time.strftime("%Y_%m_%d_%H_%M_%s", time.gmtime())))
ssc.start()
ssc.awaitTermination()
|
normal
|
{
"blob_id": "12fdeae0ae1618139b20176846e7df5b82f7aa01",
"index": 8274,
"step-1": "<mask token>\n\n\ndef send_rdd(rdd):\n out_list = rdd.collect()\n for word in out_list:\n producer.send('had2020011-out', value=str(word))\n\n\n<mask token>\n\n\ndef aggregator(values, old):\n return (old or 0) + sum(values)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef send_rdd(rdd):\n out_list = rdd.collect()\n for word in out_list:\n producer.send('had2020011-out', value=str(word))\n\n\n<mask token>\n\n\ndef aggregator(values, old):\n return (old or 0) + sum(values)\n\n\n<mask token>\nssc.checkpoint('./checkpoint{}'.format(time.strftime('%Y_%m_%d_%H_%M_%s',\n time.gmtime())))\nssc.start()\nssc.awaitTermination()\n",
"step-3": "<mask token>\nsc = SparkContext(master='local[4]')\nssc = StreamingContext(sc, batchDuration=10)\nproducer = KafkaProducer(bootstrap_servers=['mipt-node06.atp-fivt.org:9092'\n ], value_serializer=lambda x: x.encode('utf-8'))\ndstream = KafkaUtils.createDirectStream(ssc, topics=['had2020011-topic'],\n kafkaParams={'metadata.broker.list': 'mipt-node06.atp-fivt.org:9092'})\n<mask token>\nkeywords = ['lol', 'kek'] if len(sys.argv) <= 1 else sys.argv[1:]\nremove = dict.fromkeys(map(ord, '\\n ' + string.punctuation))\n\n\ndef send_rdd(rdd):\n out_list = rdd.collect()\n for word in out_list:\n producer.send('had2020011-out', value=str(word))\n\n\ninitialized = False\n\n\ndef aggregator(values, old):\n return (old or 0) + sum(values)\n\n\ninitState = sc.parallelize(list(zip(keywords, [0] * len(keywords))))\nresult = dstream.flatMap(lambda pair: pair[1].split(' ')).map(lambda word:\n word.translate(remove)).filter(lambda word: word in keywords).map(lambda\n word: (word.lower(), 1)).reduceByKeyAndWindow(lambda x, y: x + y, lambda\n x, y: x - y, 60, 60).updateStateByKey(aggregator, initialRDD=initState\n ).foreachRDD(lambda rdd: send_rdd(rdd))\nssc.checkpoint('./checkpoint{}'.format(time.strftime('%Y_%m_%d_%H_%M_%s',\n time.gmtime())))\nssc.start()\nssc.awaitTermination()\n",
"step-4": "from pyspark import SparkContext, RDD\nfrom pyspark.sql import SparkSession, DataFrame\nfrom pyspark.streaming import StreamingContext\nfrom pyspark.streaming.kafka import KafkaUtils\nimport string\nfrom kafka import KafkaProducer\nimport time\nimport pyspark\nsc = SparkContext(master='local[4]')\nssc = StreamingContext(sc, batchDuration=10)\nproducer = KafkaProducer(bootstrap_servers=['mipt-node06.atp-fivt.org:9092'\n ], value_serializer=lambda x: x.encode('utf-8'))\ndstream = KafkaUtils.createDirectStream(ssc, topics=['had2020011-topic'],\n kafkaParams={'metadata.broker.list': 'mipt-node06.atp-fivt.org:9092'})\nimport sys\nkeywords = ['lol', 'kek'] if len(sys.argv) <= 1 else sys.argv[1:]\nremove = dict.fromkeys(map(ord, '\\n ' + string.punctuation))\n\n\ndef send_rdd(rdd):\n out_list = rdd.collect()\n for word in out_list:\n producer.send('had2020011-out', value=str(word))\n\n\ninitialized = False\n\n\ndef aggregator(values, old):\n return (old or 0) + sum(values)\n\n\ninitState = sc.parallelize(list(zip(keywords, [0] * len(keywords))))\nresult = dstream.flatMap(lambda pair: pair[1].split(' ')).map(lambda word:\n word.translate(remove)).filter(lambda word: word in keywords).map(lambda\n word: (word.lower(), 1)).reduceByKeyAndWindow(lambda x, y: x + y, lambda\n x, y: x - y, 60, 60).updateStateByKey(aggregator, initialRDD=initState\n ).foreachRDD(lambda rdd: send_rdd(rdd))\nssc.checkpoint('./checkpoint{}'.format(time.strftime('%Y_%m_%d_%H_%M_%s',\n time.gmtime())))\nssc.start()\nssc.awaitTermination()\n",
"step-5": "from pyspark import SparkContext, RDD\nfrom pyspark.sql import SparkSession, DataFrame\nfrom pyspark.streaming import StreamingContext\nfrom pyspark.streaming.kafka import KafkaUtils\nimport string\nfrom kafka import KafkaProducer\nimport time\nimport pyspark\n\n\nsc = SparkContext(master='local[4]')\nssc = StreamingContext(sc, batchDuration=10)\n\n# producer = df \\\n# .selectExpr(\"CAST(key AS STRING)\", \"CAST(value AS STRING)\") \\\n# .writeStream \\\n# .format(\"kafka\") \\\n# .option(\"kafka.bootstrap.servers\", \"host1:port1,host2:port2\") \\\n# .option(\"topic\", \"topic1\") \\\n# .start()\n\nproducer = KafkaProducer(bootstrap_servers=['mipt-node06.atp-fivt.org:9092'],\n value_serializer=lambda x:\n x.encode('utf-8'))\n\n\ndstream = KafkaUtils.createDirectStream(\n ssc, topics=['had2020011-topic'],\n kafkaParams = {'metadata.broker.list': 'mipt-node06.atp-fivt.org:9092'}\n)\n\nimport sys\nkeywords = ['lol', 'kek'] if len(sys.argv) <= 1 else sys.argv[1:]\nremove = dict.fromkeys(map(ord, '\\n ' + string.punctuation))\n\ndef send_rdd(rdd):\n out_list = rdd.collect()\n for word in out_list:\n producer.send('had2020011-out', value=str(word))\n\ninitialized = False\n\ndef aggregator(values, old):\n return (old or 0) + sum(values)\n\ninitState = sc.parallelize(list(zip(keywords, [0] * len(keywords))))\n\nresult = dstream \\\n .flatMap(lambda pair: pair[1].split(\" \")) \\\n .map(lambda word: word.translate(remove)) \\\n .filter(lambda word: word in keywords) \\\n .map(lambda word: (word.lower(), 1)) \\\n .reduceByKeyAndWindow(lambda x, y: x + y, lambda x, y: x - y, 60, 60) \\\n .updateStateByKey(aggregator, initialRDD=initState) \\\n .foreachRDD(lambda rdd : send_rdd(rdd))\n # \\\n\n\n\nssc.checkpoint('./checkpoint{}'.format(time.strftime(\"%Y_%m_%d_%H_%M_%s\", time.gmtime())))\nssc.start()\nssc.awaitTermination()\n\n\n",
"step-ids": [
2,
3,
4,
5,
6
]
}
|
[
2,
3,
4,
5,
6
] |
# Generated by Django 3.0.4 on 2020-04-04 11:07
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('product', '0003_cost'),
]
operations = [
migrations.AlterField(
model_name='cost',
name='name',
field=models.CharField(max_length=50, unique=True),
),
migrations.AlterField(
model_name='product',
name='author',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='product',
name='description',
field=models.TextField(default=''),
),
migrations.AlterField(
model_name='product',
name='name',
field=models.CharField(max_length=100, unique=True),
),
migrations.AlterField(
model_name='product',
name='passport_link',
field=models.CharField(default='', max_length=200),
),
migrations.AlterField(
model_name='product',
name='site_link',
field=models.CharField(default='', max_length=200),
),
]
|
normal
|
{
"blob_id": "a4f2ca3155f2bb4c17be5bb56dd889abb5d20293",
"index": 3791,
"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 = [migrations.swappable_dependency(settings.\n AUTH_USER_MODEL), ('product', '0003_cost')]\n operations = [migrations.AlterField(model_name='cost', name='name',\n field=models.CharField(max_length=50, unique=True)), migrations.\n AlterField(model_name='product', name='author', field=models.\n ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings\n .AUTH_USER_MODEL)), migrations.AlterField(model_name='product',\n name='description', field=models.TextField(default='')), migrations\n .AlterField(model_name='product', name='name', field=models.\n CharField(max_length=100, unique=True)), migrations.AlterField(\n model_name='product', name='passport_link', field=models.CharField(\n default='', max_length=200)), migrations.AlterField(model_name=\n 'product', name='site_link', field=models.CharField(default='',\n max_length=200))]\n",
"step-4": "from django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n dependencies = [migrations.swappable_dependency(settings.\n AUTH_USER_MODEL), ('product', '0003_cost')]\n operations = [migrations.AlterField(model_name='cost', name='name',\n field=models.CharField(max_length=50, unique=True)), migrations.\n AlterField(model_name='product', name='author', field=models.\n ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings\n .AUTH_USER_MODEL)), migrations.AlterField(model_name='product',\n name='description', field=models.TextField(default='')), migrations\n .AlterField(model_name='product', name='name', field=models.\n CharField(max_length=100, unique=True)), migrations.AlterField(\n model_name='product', name='passport_link', field=models.CharField(\n default='', max_length=200)), migrations.AlterField(model_name=\n 'product', name='site_link', field=models.CharField(default='',\n max_length=200))]\n",
"step-5": "# Generated by Django 3.0.4 on 2020-04-04 11:07\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('product', '0003_cost'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='cost',\n name='name',\n field=models.CharField(max_length=50, unique=True),\n ),\n migrations.AlterField(\n model_name='product',\n name='author',\n field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL),\n ),\n migrations.AlterField(\n model_name='product',\n name='description',\n field=models.TextField(default=''),\n ),\n migrations.AlterField(\n model_name='product',\n name='name',\n field=models.CharField(max_length=100, unique=True),\n ),\n migrations.AlterField(\n model_name='product',\n name='passport_link',\n field=models.CharField(default='', max_length=200),\n ),\n migrations.AlterField(\n model_name='product',\n name='site_link',\n field=models.CharField(default='', max_length=200),\n ),\n ]\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
"""David's first approach when I exposed the problem.
Reasonable to add in the comparison?
"""
import numpy as np
from sklearn.linear_model import RidgeCV
from sklearn.model_selection import ShuffleSplit
def correlation(x, y):
a = (x - x.mean(0)) / x.std(0)
b = (y - y.mean(0)) / y.std(0)
return a.T @ b / x.shape[0]
def partial_correlation_bagging(solver, x, y, z, ensemble=None):
if ensemble is None:
ensemble = [(range(len(x)), range(len(x))), ]
r = []
for set1, set2 in ensemble:
p_x = solver.fit(z[set1], x[set1]).predict(z[set2])
p_y = solver.fit(z[set1], y[set1]).predict(z[set2])
r.append(correlation(x[set2] - p_x, y[set2] - p_y))
return np.mean(r, 0)
def partial_correlation_loop(solver, x, y, ensemble=None):
e_hat = np.zeros(y.shape[1])
for i in range(y.shape[1]):
y_i = y[:, i].reshape(-1, 1)
y_not_i = np.delete(y, i, axis=1)
r = partial_correlation_bagging(solver, x, y_i, y_not_i, ensemble)
e_hat[i] = np.sum(r**2)
return e_hat
class PartialCorrelation(object):
def __init__(self, solver=None, bagging=False):
self.solver = RidgeCV() if solver is None else solver
self.bagging = bagging
def fit(self, X, Y):
ensemble = None
if self.bagging:
cv = ShuffleSplit(test_size=.5)
ensemble = [(train, test) for train, test in cv.split(X, Y)]
self.E_ = partial_correlation_loop(self.solver, X, Y, ensemble)
return self
if __name__ == '__main__':
from sklearn.preprocessing import scale
from sklearn.metrics import roc_auc_score
# Simulate data
"""Y = F(EX+N)"""
np.random.seed(0)
# Problem dimensionality
n = 1000
nE = nX = 10
nY = 10
snr = 25 # signal to noise ratio
selected = .5 # number of X feature selected by E
selected = min(int(np.floor(selected*nX)) + 1, nX-1)
E = np.identity(nX)
E[selected:] = 0
# X covariance
Cx = np.random.randn(nX, nX)
Cx = Cx.dot(Cx.T) / nX # sym pos-semidefin
X = np.random.multivariate_normal(np.zeros(nX), Cx, n)
# Noise (homosedastic in source space)
N = np.random.randn(n, nE)
# Forward operator (linear mixture)
F = np.random.randn(nY, nE)
Y = ((X @ E.T) * snr + N) @ F.T
X = scale(X)
Y = scale(Y)
# Fit method
partialcorr = PartialCorrelation()
train, test = range(0, n, 2), range(1, n, 2)
E_hat = partialcorr.fit(X[train], Y[train]).E_
# score = partialcorr.score(X[test], Y[test]) # TODO
print('E_auc', roc_auc_score(np.diag(E), E_hat))
|
normal
|
{
"blob_id": "dfd2b515e08f285345c750bf00f6a55f43d60039",
"index": 8379,
"step-1": "<mask token>\n\n\ndef partial_correlation_loop(solver, x, y, ensemble=None):\n e_hat = np.zeros(y.shape[1])\n for i in range(y.shape[1]):\n y_i = y[:, i].reshape(-1, 1)\n y_not_i = np.delete(y, i, axis=1)\n r = partial_correlation_bagging(solver, x, y_i, y_not_i, ensemble)\n e_hat[i] = np.sum(r ** 2)\n return e_hat\n\n\nclass PartialCorrelation(object):\n\n def __init__(self, solver=None, bagging=False):\n self.solver = RidgeCV() if solver is None else solver\n self.bagging = bagging\n\n def fit(self, X, Y):\n ensemble = None\n if self.bagging:\n cv = ShuffleSplit(test_size=0.5)\n ensemble = [(train, test) for train, test in cv.split(X, Y)]\n self.E_ = partial_correlation_loop(self.solver, X, Y, ensemble)\n return self\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef correlation(x, y):\n a = (x - x.mean(0)) / x.std(0)\n b = (y - y.mean(0)) / y.std(0)\n return a.T @ b / x.shape[0]\n\n\n<mask token>\n\n\ndef partial_correlation_loop(solver, x, y, ensemble=None):\n e_hat = np.zeros(y.shape[1])\n for i in range(y.shape[1]):\n y_i = y[:, i].reshape(-1, 1)\n y_not_i = np.delete(y, i, axis=1)\n r = partial_correlation_bagging(solver, x, y_i, y_not_i, ensemble)\n e_hat[i] = np.sum(r ** 2)\n return e_hat\n\n\nclass PartialCorrelation(object):\n\n def __init__(self, solver=None, bagging=False):\n self.solver = RidgeCV() if solver is None else solver\n self.bagging = bagging\n\n def fit(self, X, Y):\n ensemble = None\n if self.bagging:\n cv = ShuffleSplit(test_size=0.5)\n ensemble = [(train, test) for train, test in cv.split(X, Y)]\n self.E_ = partial_correlation_loop(self.solver, X, Y, ensemble)\n return self\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef correlation(x, y):\n a = (x - x.mean(0)) / x.std(0)\n b = (y - y.mean(0)) / y.std(0)\n return a.T @ b / x.shape[0]\n\n\ndef partial_correlation_bagging(solver, x, y, z, ensemble=None):\n if ensemble is None:\n ensemble = [(range(len(x)), range(len(x)))]\n r = []\n for set1, set2 in ensemble:\n p_x = solver.fit(z[set1], x[set1]).predict(z[set2])\n p_y = solver.fit(z[set1], y[set1]).predict(z[set2])\n r.append(correlation(x[set2] - p_x, y[set2] - p_y))\n return np.mean(r, 0)\n\n\ndef partial_correlation_loop(solver, x, y, ensemble=None):\n e_hat = np.zeros(y.shape[1])\n for i in range(y.shape[1]):\n y_i = y[:, i].reshape(-1, 1)\n y_not_i = np.delete(y, i, axis=1)\n r = partial_correlation_bagging(solver, x, y_i, y_not_i, ensemble)\n e_hat[i] = np.sum(r ** 2)\n return e_hat\n\n\nclass PartialCorrelation(object):\n\n def __init__(self, solver=None, bagging=False):\n self.solver = RidgeCV() if solver is None else solver\n self.bagging = bagging\n\n def fit(self, X, Y):\n ensemble = None\n if self.bagging:\n cv = ShuffleSplit(test_size=0.5)\n ensemble = [(train, test) for train, test in cv.split(X, Y)]\n self.E_ = partial_correlation_loop(self.solver, X, Y, ensemble)\n return self\n\n\n<mask token>\n",
"step-4": "<mask token>\n\n\ndef correlation(x, y):\n a = (x - x.mean(0)) / x.std(0)\n b = (y - y.mean(0)) / y.std(0)\n return a.T @ b / x.shape[0]\n\n\ndef partial_correlation_bagging(solver, x, y, z, ensemble=None):\n if ensemble is None:\n ensemble = [(range(len(x)), range(len(x)))]\n r = []\n for set1, set2 in ensemble:\n p_x = solver.fit(z[set1], x[set1]).predict(z[set2])\n p_y = solver.fit(z[set1], y[set1]).predict(z[set2])\n r.append(correlation(x[set2] - p_x, y[set2] - p_y))\n return np.mean(r, 0)\n\n\ndef partial_correlation_loop(solver, x, y, ensemble=None):\n e_hat = np.zeros(y.shape[1])\n for i in range(y.shape[1]):\n y_i = y[:, i].reshape(-1, 1)\n y_not_i = np.delete(y, i, axis=1)\n r = partial_correlation_bagging(solver, x, y_i, y_not_i, ensemble)\n e_hat[i] = np.sum(r ** 2)\n return e_hat\n\n\nclass PartialCorrelation(object):\n\n def __init__(self, solver=None, bagging=False):\n self.solver = RidgeCV() if solver is None else solver\n self.bagging = bagging\n\n def fit(self, X, Y):\n ensemble = None\n if self.bagging:\n cv = ShuffleSplit(test_size=0.5)\n ensemble = [(train, test) for train, test in cv.split(X, Y)]\n self.E_ = partial_correlation_loop(self.solver, X, Y, ensemble)\n return self\n\n\nif __name__ == '__main__':\n from sklearn.preprocessing import scale\n from sklearn.metrics import roc_auc_score\n \"\"\"Y = F(EX+N)\"\"\"\n np.random.seed(0)\n n = 1000\n nE = nX = 10\n nY = 10\n snr = 25\n selected = 0.5\n selected = min(int(np.floor(selected * nX)) + 1, nX - 1)\n E = np.identity(nX)\n E[selected:] = 0\n Cx = np.random.randn(nX, nX)\n Cx = Cx.dot(Cx.T) / nX\n X = np.random.multivariate_normal(np.zeros(nX), Cx, n)\n N = np.random.randn(n, nE)\n F = np.random.randn(nY, nE)\n Y = (X @ E.T * snr + N) @ F.T\n X = scale(X)\n Y = scale(Y)\n partialcorr = PartialCorrelation()\n train, test = range(0, n, 2), range(1, n, 2)\n E_hat = partialcorr.fit(X[train], Y[train]).E_\n print('E_auc', roc_auc_score(np.diag(E), E_hat))\n",
"step-5": "\"\"\"David's first approach when I exposed the problem.\nReasonable to add in the comparison?\n\"\"\"\nimport numpy as np\nfrom sklearn.linear_model import RidgeCV\nfrom sklearn.model_selection import ShuffleSplit\n\n\ndef correlation(x, y):\n a = (x - x.mean(0)) / x.std(0)\n b = (y - y.mean(0)) / y.std(0)\n return a.T @ b / x.shape[0]\n\n\ndef partial_correlation_bagging(solver, x, y, z, ensemble=None):\n if ensemble is None:\n ensemble = [(range(len(x)), range(len(x))), ]\n r = []\n for set1, set2 in ensemble:\n p_x = solver.fit(z[set1], x[set1]).predict(z[set2])\n p_y = solver.fit(z[set1], y[set1]).predict(z[set2])\n r.append(correlation(x[set2] - p_x, y[set2] - p_y))\n return np.mean(r, 0)\n\n\ndef partial_correlation_loop(solver, x, y, ensemble=None):\n e_hat = np.zeros(y.shape[1])\n for i in range(y.shape[1]):\n y_i = y[:, i].reshape(-1, 1)\n y_not_i = np.delete(y, i, axis=1)\n r = partial_correlation_bagging(solver, x, y_i, y_not_i, ensemble)\n e_hat[i] = np.sum(r**2)\n return e_hat\n\n\nclass PartialCorrelation(object):\n\n def __init__(self, solver=None, bagging=False):\n self.solver = RidgeCV() if solver is None else solver\n self.bagging = bagging\n\n def fit(self, X, Y):\n ensemble = None\n if self.bagging:\n cv = ShuffleSplit(test_size=.5)\n ensemble = [(train, test) for train, test in cv.split(X, Y)]\n self.E_ = partial_correlation_loop(self.solver, X, Y, ensemble)\n return self\n\n\nif __name__ == '__main__':\n from sklearn.preprocessing import scale\n from sklearn.metrics import roc_auc_score\n # Simulate data\n \"\"\"Y = F(EX+N)\"\"\"\n\n np.random.seed(0)\n\n # Problem dimensionality\n n = 1000\n nE = nX = 10\n nY = 10\n snr = 25 # signal to noise ratio\n selected = .5 # number of X feature selected by E\n\n selected = min(int(np.floor(selected*nX)) + 1, nX-1)\n E = np.identity(nX)\n E[selected:] = 0\n\n # X covariance\n Cx = np.random.randn(nX, nX)\n Cx = Cx.dot(Cx.T) / nX # sym pos-semidefin\n X = np.random.multivariate_normal(np.zeros(nX), Cx, n)\n\n # Noise (homosedastic in source space)\n N = np.random.randn(n, nE)\n\n # Forward operator (linear mixture)\n F = np.random.randn(nY, nE)\n\n Y = ((X @ E.T) * snr + N) @ F.T\n\n X = scale(X)\n Y = scale(Y)\n\n # Fit method\n partialcorr = PartialCorrelation()\n train, test = range(0, n, 2), range(1, n, 2)\n E_hat = partialcorr.fit(X[train], Y[train]).E_\n # score = partialcorr.score(X[test], Y[test]) # TODO\n\n print('E_auc', roc_auc_score(np.diag(E), E_hat))\n",
"step-ids": [
4,
5,
6,
7,
9
]
}
|
[
4,
5,
6,
7,
9
] |
import Net
import mnist_parser
import numpy as np
#To use this model it is required to download the MNIST database
#The donwloaded base is then needet parse to numpy using mnist_parser.parse_to_npy method
#The files genetared using mnist_parser.parse_to_npy are then loaded using np.load
in_values = np.load("MNIST/mnist_train_images.npy")
out_values = np.load("MNIST/mnist_train_labels.npy")
out_gt_numbers=mnist_parser.one_hots_to_ints(out_values)
in_testing_values = np.load("MNIST/mnist_test_images.npy")
out_testing_values = np.load("MNIST/mnist_test_labels.npy")
out_gt_numbers_test=mnist_parser.one_hots_to_ints(out_testing_values)
while(True):
net = Net.FeedForwardNet(input_count=784, layers=[100, 10], activation_function=Net.FeedForwardNet.leaky_relu)
try:
epoch_num=int(input("Epoch_num:"))
batch_size=int(input("Batch_size:")) #30
learning_rate=float(input("Learning rate:")) #0.001
inertion_factor=float(input("Inertion factor:")) #0.5
# max_error=float(input("Maximum error"))
except:
print("Parse error")
continue
for i in range(epoch_num):
batch_in,batch_out=net.generate_random_batch(in_values,out_values,batch_size)
net.forward_propagation(batch_in)
net.backpropagation(batch_out, learning_rate=learning_rate, inertion_factor=inertion_factor)
# print("X:",net.X[-1])
# net.stochastic_backpropagation(batch_out, learning_rate=learning_rate)
if i % 50 == 0:
print()
output=net.forward_propagation(in_testing_values)
if net.check_total_squared_error(output_values=out_testing_values, epsilon=1000, verbose=True):
break
output_numbers=mnist_parser.one_hots_to_ints(output)
correct=np.sum( out_gt_numbers_test == output_numbers)
print("Epoch: ", i, " br tocnih:",correct,"/",output_numbers.size,"(",correct/output_numbers.size,"%)")
output=net.forward_propagation(in_testing_values)
conf_mat=net.calculate_confusion_matrix(out_testing_values)
output_numbers = mnist_parser.one_hots_to_ints(output)
correct=np.sum(out_gt_numbers_test == output_numbers)
print("Correct:",correct,"/",output_numbers.size,"(",correct/output_numbers.size ,"%)")
print(conf_mat)
save=int(input("Save?(1/0)"))
if(save == 1):
name=input("Save as?")
net.save_state(name)
exit=int(input("Exit?(1/0)"))
if(exit == 1):
break
|
normal
|
{
"blob_id": "49005500b299ca276f663fe8431bb955e5585bbd",
"index": 335,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwhile True:\n net = Net.FeedForwardNet(input_count=784, layers=[100, 10],\n activation_function=Net.FeedForwardNet.leaky_relu)\n try:\n epoch_num = int(input('Epoch_num:'))\n batch_size = int(input('Batch_size:'))\n learning_rate = float(input('Learning rate:'))\n inertion_factor = float(input('Inertion factor:'))\n except:\n print('Parse error')\n continue\n for i in range(epoch_num):\n batch_in, batch_out = net.generate_random_batch(in_values,\n out_values, batch_size)\n net.forward_propagation(batch_in)\n net.backpropagation(batch_out, learning_rate=learning_rate,\n inertion_factor=inertion_factor)\n if i % 50 == 0:\n print()\n output = net.forward_propagation(in_testing_values)\n if net.check_total_squared_error(output_values=\n out_testing_values, epsilon=1000, verbose=True):\n break\n output_numbers = mnist_parser.one_hots_to_ints(output)\n correct = np.sum(out_gt_numbers_test == output_numbers)\n print('Epoch: ', i, ' br tocnih:', correct, '/', output_numbers\n .size, '(', correct / output_numbers.size, '%)')\n output = net.forward_propagation(in_testing_values)\n conf_mat = net.calculate_confusion_matrix(out_testing_values)\n output_numbers = mnist_parser.one_hots_to_ints(output)\n correct = np.sum(out_gt_numbers_test == output_numbers)\n print('Correct:', correct, '/', output_numbers.size, '(', correct /\n output_numbers.size, '%)')\n print(conf_mat)\n save = int(input('Save?(1/0)'))\n if save == 1:\n name = input('Save as?')\n net.save_state(name)\n exit = int(input('Exit?(1/0)'))\n if exit == 1:\n break\n",
"step-3": "<mask token>\nin_values = np.load('MNIST/mnist_train_images.npy')\nout_values = np.load('MNIST/mnist_train_labels.npy')\nout_gt_numbers = mnist_parser.one_hots_to_ints(out_values)\nin_testing_values = np.load('MNIST/mnist_test_images.npy')\nout_testing_values = np.load('MNIST/mnist_test_labels.npy')\nout_gt_numbers_test = mnist_parser.one_hots_to_ints(out_testing_values)\nwhile True:\n net = Net.FeedForwardNet(input_count=784, layers=[100, 10],\n activation_function=Net.FeedForwardNet.leaky_relu)\n try:\n epoch_num = int(input('Epoch_num:'))\n batch_size = int(input('Batch_size:'))\n learning_rate = float(input('Learning rate:'))\n inertion_factor = float(input('Inertion factor:'))\n except:\n print('Parse error')\n continue\n for i in range(epoch_num):\n batch_in, batch_out = net.generate_random_batch(in_values,\n out_values, batch_size)\n net.forward_propagation(batch_in)\n net.backpropagation(batch_out, learning_rate=learning_rate,\n inertion_factor=inertion_factor)\n if i % 50 == 0:\n print()\n output = net.forward_propagation(in_testing_values)\n if net.check_total_squared_error(output_values=\n out_testing_values, epsilon=1000, verbose=True):\n break\n output_numbers = mnist_parser.one_hots_to_ints(output)\n correct = np.sum(out_gt_numbers_test == output_numbers)\n print('Epoch: ', i, ' br tocnih:', correct, '/', output_numbers\n .size, '(', correct / output_numbers.size, '%)')\n output = net.forward_propagation(in_testing_values)\n conf_mat = net.calculate_confusion_matrix(out_testing_values)\n output_numbers = mnist_parser.one_hots_to_ints(output)\n correct = np.sum(out_gt_numbers_test == output_numbers)\n print('Correct:', correct, '/', output_numbers.size, '(', correct /\n output_numbers.size, '%)')\n print(conf_mat)\n save = int(input('Save?(1/0)'))\n if save == 1:\n name = input('Save as?')\n net.save_state(name)\n exit = int(input('Exit?(1/0)'))\n if exit == 1:\n break\n",
"step-4": "import Net\nimport mnist_parser\nimport numpy as np\nin_values = np.load('MNIST/mnist_train_images.npy')\nout_values = np.load('MNIST/mnist_train_labels.npy')\nout_gt_numbers = mnist_parser.one_hots_to_ints(out_values)\nin_testing_values = np.load('MNIST/mnist_test_images.npy')\nout_testing_values = np.load('MNIST/mnist_test_labels.npy')\nout_gt_numbers_test = mnist_parser.one_hots_to_ints(out_testing_values)\nwhile True:\n net = Net.FeedForwardNet(input_count=784, layers=[100, 10],\n activation_function=Net.FeedForwardNet.leaky_relu)\n try:\n epoch_num = int(input('Epoch_num:'))\n batch_size = int(input('Batch_size:'))\n learning_rate = float(input('Learning rate:'))\n inertion_factor = float(input('Inertion factor:'))\n except:\n print('Parse error')\n continue\n for i in range(epoch_num):\n batch_in, batch_out = net.generate_random_batch(in_values,\n out_values, batch_size)\n net.forward_propagation(batch_in)\n net.backpropagation(batch_out, learning_rate=learning_rate,\n inertion_factor=inertion_factor)\n if i % 50 == 0:\n print()\n output = net.forward_propagation(in_testing_values)\n if net.check_total_squared_error(output_values=\n out_testing_values, epsilon=1000, verbose=True):\n break\n output_numbers = mnist_parser.one_hots_to_ints(output)\n correct = np.sum(out_gt_numbers_test == output_numbers)\n print('Epoch: ', i, ' br tocnih:', correct, '/', output_numbers\n .size, '(', correct / output_numbers.size, '%)')\n output = net.forward_propagation(in_testing_values)\n conf_mat = net.calculate_confusion_matrix(out_testing_values)\n output_numbers = mnist_parser.one_hots_to_ints(output)\n correct = np.sum(out_gt_numbers_test == output_numbers)\n print('Correct:', correct, '/', output_numbers.size, '(', correct /\n output_numbers.size, '%)')\n print(conf_mat)\n save = int(input('Save?(1/0)'))\n if save == 1:\n name = input('Save as?')\n net.save_state(name)\n exit = int(input('Exit?(1/0)'))\n if exit == 1:\n break\n",
"step-5": "import Net\nimport mnist_parser\nimport numpy as np\n#To use this model it is required to download the MNIST database\n#The donwloaded base is then needet parse to numpy using mnist_parser.parse_to_npy method\n#The files genetared using mnist_parser.parse_to_npy are then loaded using np.load\nin_values = np.load(\"MNIST/mnist_train_images.npy\")\nout_values = np.load(\"MNIST/mnist_train_labels.npy\")\nout_gt_numbers=mnist_parser.one_hots_to_ints(out_values)\n\nin_testing_values = np.load(\"MNIST/mnist_test_images.npy\")\nout_testing_values = np.load(\"MNIST/mnist_test_labels.npy\")\nout_gt_numbers_test=mnist_parser.one_hots_to_ints(out_testing_values)\n\nwhile(True):\n\n net = Net.FeedForwardNet(input_count=784, layers=[100, 10], activation_function=Net.FeedForwardNet.leaky_relu)\n\n try:\n epoch_num=int(input(\"Epoch_num:\"))\n batch_size=int(input(\"Batch_size:\")) #30\n learning_rate=float(input(\"Learning rate:\")) #0.001\n inertion_factor=float(input(\"Inertion factor:\")) #0.5\n # max_error=float(input(\"Maximum error\"))\n except:\n print(\"Parse error\")\n continue\n\n for i in range(epoch_num):\n batch_in,batch_out=net.generate_random_batch(in_values,out_values,batch_size)\n net.forward_propagation(batch_in)\n net.backpropagation(batch_out, learning_rate=learning_rate, inertion_factor=inertion_factor)\n # print(\"X:\",net.X[-1])\n # net.stochastic_backpropagation(batch_out, learning_rate=learning_rate)\n\n if i % 50 == 0:\n print()\n output=net.forward_propagation(in_testing_values)\n if net.check_total_squared_error(output_values=out_testing_values, epsilon=1000, verbose=True):\n break\n output_numbers=mnist_parser.one_hots_to_ints(output)\n correct=np.sum( out_gt_numbers_test == output_numbers)\n print(\"Epoch: \", i, \" br tocnih:\",correct,\"/\",output_numbers.size,\"(\",correct/output_numbers.size,\"%)\")\n\n\n output=net.forward_propagation(in_testing_values)\n conf_mat=net.calculate_confusion_matrix(out_testing_values)\n\n output_numbers = mnist_parser.one_hots_to_ints(output)\n correct=np.sum(out_gt_numbers_test == output_numbers)\n print(\"Correct:\",correct,\"/\",output_numbers.size,\"(\",correct/output_numbers.size ,\"%)\")\n print(conf_mat)\n\n\n save=int(input(\"Save?(1/0)\"))\n if(save == 1):\n name=input(\"Save as?\")\n net.save_state(name)\n exit=int(input(\"Exit?(1/0)\"))\n if(exit == 1):\n break\n\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class AutomationserverConfig(AppConfig):
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class AutomationserverConfig(AppConfig):
name = 'automationserver'
<|reserved_special_token_1|>
from django.apps import AppConfig
class AutomationserverConfig(AppConfig):
name = 'automationserver'
|
flexible
|
{
"blob_id": "3153218fe1d67fdc1c1957ffcfdb380688c159c1",
"index": 6483,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass AutomationserverConfig(AppConfig):\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass AutomationserverConfig(AppConfig):\n name = 'automationserver'\n",
"step-4": "from django.apps import AppConfig\n\n\nclass AutomationserverConfig(AppConfig):\n name = 'automationserver'\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
from utils import create_data_lists
if __name__ == '__main__':
create_data_lists(ICDAR_path=
'../ICDAR_Dataset/0325updated.task1train(626p)', output_folder=
'../ICDAR_Dataset/0325updated.task1train(626p)')
|
normal
|
{
"blob_id": "6334a8a052d72b0f13395b301bd5a766acf4399b",
"index": 3437,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif __name__ == '__main__':\n create_data_lists(ICDAR_path=\n '../ICDAR_Dataset/0325updated.task1train(626p)', output_folder=\n '../ICDAR_Dataset/0325updated.task1train(626p)')\n",
"step-3": "from utils import create_data_lists\nif __name__ == '__main__':\n create_data_lists(ICDAR_path=\n '../ICDAR_Dataset/0325updated.task1train(626p)', output_folder=\n '../ICDAR_Dataset/0325updated.task1train(626p)')\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
<|reserved_special_token_0|>
def sieve(n):
sieve = [1] * (n + 1)
sieve[1] = 0
sieve[0] = 0
for i in range(2, int(math.sqrt(n) + 1)):
if sieve[i] == 1:
for j in range(i * i, n + 1, i):
sieve[j] = 0
return sieve
def odd_prime(a):
while a != 0:
y = a % 10
if y == 3 or y == 5 or y == 7:
return False
else:
a = a // 10
return True
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def sieve(n):
sieve = [1] * (n + 1)
sieve[1] = 0
sieve[0] = 0
for i in range(2, int(math.sqrt(n) + 1)):
if sieve[i] == 1:
for j in range(i * i, n + 1, i):
sieve[j] = 0
return sieve
def odd_prime(a):
while a != 0:
y = a % 10
if y == 3 or y == 5 or y == 7:
return False
else:
a = a // 10
return True
def main():
t = int(input())
for j in range(t):
x = int(input())
n = 75000
arr = sieve(n)
result = []
final = []
sum = 0
for i in range(len(arr)):
if arr[i] == 1:
result.append(i)
for i in range(len(result)):
if odd_prime(result[i]):
final.append(result[i])
for i in range(x):
sum = sum + final[i]
print(sum)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def sieve(n):
sieve = [1] * (n + 1)
sieve[1] = 0
sieve[0] = 0
for i in range(2, int(math.sqrt(n) + 1)):
if sieve[i] == 1:
for j in range(i * i, n + 1, i):
sieve[j] = 0
return sieve
def odd_prime(a):
while a != 0:
y = a % 10
if y == 3 or y == 5 or y == 7:
return False
else:
a = a // 10
return True
def main():
t = int(input())
for j in range(t):
x = int(input())
n = 75000
arr = sieve(n)
result = []
final = []
sum = 0
for i in range(len(arr)):
if arr[i] == 1:
result.append(i)
for i in range(len(result)):
if odd_prime(result[i]):
final.append(result[i])
for i in range(x):
sum = sum + final[i]
print(sum)
if __name__ == '__main__':
main()
<|reserved_special_token_1|>
import math
def sieve(n):
sieve = [1] * (n + 1)
sieve[1] = 0
sieve[0] = 0
for i in range(2, int(math.sqrt(n) + 1)):
if sieve[i] == 1:
for j in range(i * i, n + 1, i):
sieve[j] = 0
return sieve
def odd_prime(a):
while a != 0:
y = a % 10
if y == 3 or y == 5 or y == 7:
return False
else:
a = a // 10
return True
def main():
t = int(input())
for j in range(t):
x = int(input())
n = 75000
arr = sieve(n)
result = []
final = []
sum = 0
for i in range(len(arr)):
if arr[i] == 1:
result.append(i)
for i in range(len(result)):
if odd_prime(result[i]):
final.append(result[i])
for i in range(x):
sum = sum + final[i]
print(sum)
if __name__ == '__main__':
main()
<|reserved_special_token_1|>
import math
def sieve(n):
sieve = [1] * (n+1)
sieve[1] = 0
sieve[0] = 0
for i in range(2, int(math.sqrt(n) + 1)):
if sieve[i] == 1:
for j in range(i*i, n + 1, i):
sieve[j] = 0
return sieve
def odd_prime(a):
while a != 0:
y = a % 10
if y == 3 or y == 5 or y ==7:
return False
else:
a = a // 10
return True
def main():
t = int(input())
for j in range(t):
x = int(input())
n = 75000
arr = sieve(n)
result = []
final = []
sum = 0
for i in range(len(arr)):
if arr[i] == 1:
result.append(i)
for i in range(len(result)):
if (odd_prime(result[i])):
final.append(result[i])
for i in range(x):
sum = sum + final[i]
print(sum)
if __name__ == '__main__':
main()
|
flexible
|
{
"blob_id": "60617ff6eda880e5467b3b79d3df13a7147f5990",
"index": 3329,
"step-1": "<mask token>\n\n\ndef sieve(n):\n sieve = [1] * (n + 1)\n sieve[1] = 0\n sieve[0] = 0\n for i in range(2, int(math.sqrt(n) + 1)):\n if sieve[i] == 1:\n for j in range(i * i, n + 1, i):\n sieve[j] = 0\n return sieve\n\n\ndef odd_prime(a):\n while a != 0:\n y = a % 10\n if y == 3 or y == 5 or y == 7:\n return False\n else:\n a = a // 10\n return True\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef sieve(n):\n sieve = [1] * (n + 1)\n sieve[1] = 0\n sieve[0] = 0\n for i in range(2, int(math.sqrt(n) + 1)):\n if sieve[i] == 1:\n for j in range(i * i, n + 1, i):\n sieve[j] = 0\n return sieve\n\n\ndef odd_prime(a):\n while a != 0:\n y = a % 10\n if y == 3 or y == 5 or y == 7:\n return False\n else:\n a = a // 10\n return True\n\n\ndef main():\n t = int(input())\n for j in range(t):\n x = int(input())\n n = 75000\n arr = sieve(n)\n result = []\n final = []\n sum = 0\n for i in range(len(arr)):\n if arr[i] == 1:\n result.append(i)\n for i in range(len(result)):\n if odd_prime(result[i]):\n final.append(result[i])\n for i in range(x):\n sum = sum + final[i]\n print(sum)\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef sieve(n):\n sieve = [1] * (n + 1)\n sieve[1] = 0\n sieve[0] = 0\n for i in range(2, int(math.sqrt(n) + 1)):\n if sieve[i] == 1:\n for j in range(i * i, n + 1, i):\n sieve[j] = 0\n return sieve\n\n\ndef odd_prime(a):\n while a != 0:\n y = a % 10\n if y == 3 or y == 5 or y == 7:\n return False\n else:\n a = a // 10\n return True\n\n\ndef main():\n t = int(input())\n for j in range(t):\n x = int(input())\n n = 75000\n arr = sieve(n)\n result = []\n final = []\n sum = 0\n for i in range(len(arr)):\n if arr[i] == 1:\n result.append(i)\n for i in range(len(result)):\n if odd_prime(result[i]):\n final.append(result[i])\n for i in range(x):\n sum = sum + final[i]\n print(sum)\n\n\nif __name__ == '__main__':\n main()\n",
"step-4": "import math\n\n\ndef sieve(n):\n sieve = [1] * (n + 1)\n sieve[1] = 0\n sieve[0] = 0\n for i in range(2, int(math.sqrt(n) + 1)):\n if sieve[i] == 1:\n for j in range(i * i, n + 1, i):\n sieve[j] = 0\n return sieve\n\n\ndef odd_prime(a):\n while a != 0:\n y = a % 10\n if y == 3 or y == 5 or y == 7:\n return False\n else:\n a = a // 10\n return True\n\n\ndef main():\n t = int(input())\n for j in range(t):\n x = int(input())\n n = 75000\n arr = sieve(n)\n result = []\n final = []\n sum = 0\n for i in range(len(arr)):\n if arr[i] == 1:\n result.append(i)\n for i in range(len(result)):\n if odd_prime(result[i]):\n final.append(result[i])\n for i in range(x):\n sum = sum + final[i]\n print(sum)\n\n\nif __name__ == '__main__':\n main()\n",
"step-5": "import math\n\n\ndef sieve(n):\n sieve = [1] * (n+1)\n sieve[1] = 0\n sieve[0] = 0\n for i in range(2, int(math.sqrt(n) + 1)):\n if sieve[i] == 1:\n for j in range(i*i, n + 1, i):\n sieve[j] = 0\n return sieve\ndef odd_prime(a):\n while a != 0:\n y = a % 10\n if y == 3 or y == 5 or y ==7:\n return False\n else:\n a = a // 10\n return True\n\ndef main():\n t = int(input())\n for j in range(t):\n x = int(input())\n n = 75000\n arr = sieve(n)\n result = []\n final = []\n sum = 0\n for i in range(len(arr)):\n if arr[i] == 1:\n result.append(i)\n for i in range(len(result)):\n if (odd_prime(result[i])):\n final.append(result[i])\n for i in range(x):\n sum = sum + final[i]\n print(sum)\n\n\nif __name__ == '__main__':\n main()",
"step-ids": [
2,
3,
4,
5,
6
]
}
|
[
2,
3,
4,
5,
6
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class external(terrascript.Provider):
pass
<|reserved_special_token_1|>
import terrascript
class external(terrascript.Provider):
pass
<|reserved_special_token_1|>
# terrascript/external/__init__.py
import terrascript
class external(terrascript.Provider):
pass
|
flexible
|
{
"blob_id": "04e57739e6fb98cd237fbe09caecd17c728c1797",
"index": 5548,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass external(terrascript.Provider):\n pass\n",
"step-3": "import terrascript\n\n\nclass external(terrascript.Provider):\n pass\n",
"step-4": "# terrascript/external/__init__.py\n\nimport terrascript\n\nclass external(terrascript.Provider):\n pass",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'ecommerce.settings.development')
application = get_asgi_application()
|
normal
|
{
"blob_id": "1cb320cf57823511b0398adce097b770b2131eb6",
"index": 9307,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nos.environ.setdefault('DJANGO_SETTINGS_MODULE',\n 'ecommerce.settings.development')\n<mask token>\n",
"step-3": "<mask token>\nos.environ.setdefault('DJANGO_SETTINGS_MODULE',\n 'ecommerce.settings.development')\napplication = get_asgi_application()\n",
"step-4": "import os\nfrom django.core.asgi import get_asgi_application\nos.environ.setdefault('DJANGO_SETTINGS_MODULE',\n 'ecommerce.settings.development')\napplication = get_asgi_application()\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
from Receiver import Receiver
import time
import Image
class Sender:
ACK = []
size = None
windowSize = None
tableOfFrames = []
ChosenSumAlgorithm = None
def __init__(self, receiver):
self.receiver = receiver
pass
def send_frame(self, frame):
self.receiver.receiver_frame(frame)
pass
def send_frame_selective(self):
#stworzenie tablicy z ramkami
self.tableOfFrames = Image.gruop_into_frames(self.image, self.size, self.ChosenSumAlgorithm)
# zapisuje ilosc ramek dopedli wysylania
sizeoftable = len(self.tableOfFrames)
# tworzy tablice o rozmiarze ilosci ramek z potwierdzeniami lub odrzuceniami pakietów
for i in range(0, sizeoftable):
self.ACK.append(False)
# przenoszenie do receivera potrzebnych wartosci
Receiver.numberOfFrames = sizeoftable
Receiver.reset_Data(Receiver)
endOfWindow = self.windowSize - 1
i = 0
# petla wysylajaca ramki zgodnie z regulami algotrytmu selektywnego
while i < sizeoftable:
isCorrectFrame = True
# petla operujaca oknem i wysylajaca te ramki ktore sender od nas chce
for j in range(i, endOfWindow + 1):
if j == sizeoftable:
break
if self.ACK[j] == False:
# time.sleep(0.2)
print(f'SENDER: wysłano obiekt nr "{j}"')
self.ACK[j] = self.receiver.recieve_frame(self.tableOfFrames[j], j)
else:
pass
# petla sprawdzajaca czy cala ramka zostala przeslana bez zarzutów
for j in range(i, endOfWindow + 1):
if j == sizeoftable:
break
if self.ACK[j] == False:
isCorrectFrame = False
# warunki odpowiadajace za przesuwanie sie okna gdy ramka jest dobra lub gdy ktorys z pakietow jest uszkodzony
if isCorrectFrame:
if (endOfWindow + self.windowSize) >= sizeoftable:
endOfWindow = sizeoftable
else:
endOfWindow += self.windowSize
i += self.windowSize
else:
count = 0
for j in range(i, endOfWindow + 1):
if self.ACK[j] == True:
count += 1
else:
break
endOfWindow += count
i += count
def send_frame_go_back_n(self, delay):
# self.image = interfere(self.image)
# przygotowanie ramek fo wysłania
# 1. stworzenie tablicy ramek z sumą kontrolną
self.tableOfFrames = Image.gruop_into_frames(self.image, self.size, self.ChosenSumAlgorithm)
# pokazuje ilość ramek
size_of_table = len(self.tableOfFrames)
# tworzy tablice o rozmiarze ilości ramek z potwierdzeniami lub odrzuceniami pakietów
for i in range(0, size_of_table):
self.ACK.append(False)
# przenoszenie do receivera potrzebnych wartości
self.receiver.numberOfValues = self.image.size
self.receiver.numberOfFrames = len(self.tableOfFrames)
self.receiver.reset_Data()
# rozpoczęcie przesyłania
i = 0
win_start = i
win_end = i + self.windowSize
length_table_of_frames = len(self.tableOfFrames)
while i < length_table_of_frames:
while i < win_end and i < length_table_of_frames:
# pobranie ramki do wysłania
data = self.tableOfFrames[i]
sequence_number = i
# wysyłanie ramki
print(f'\nSENDER: wysłano obiekt nr "{i}"')
self.ACK[i] = self.receiver.recieve_frame(frame=data, sequence_number=sequence_number)
time.sleep(delay)
if self.ACK[win_start]:
print(f'SENDER: odebrano ATK "{win_start}"\n')
win_end += 1
win_start += 1
# i = win_start
else:
if win_end > length_table_of_frames:
win_end = length_table_of_frames
for k in range(win_start + 1, win_end):
if self.ACK[k]:
print(f'SENDER: odebrano ATK "{k}, Pominięto ATK "{win_start}"\n')
i = win_start - 1
break
i += 1
time.sleep(delay)
pass
pass
time.sleep(delay)
if i == win_end:
i = win_start
pass
print('SENDER: koniec wysyłania\n')
pass
# Metoda wysyłająca dla protokołu stop-and-wait
def send_frame_stop_and_wait(self):
# test
# print(self.image)
self.tableOfFrames = Image.gruop_into_frames(self.image, self.size, self.ChosenSumAlgorithm)
#wyświetlenie tablicy zawierającej wszystkie ramki
print(self.tableOfFrames)
#zapis ilości ramek
sizeoftable = len(self.tableOfFrames)
#tworzy tablice o rozmiarze ilosci ramek z potwierdzeniami lub odrzuceniami pakietów
for i in range(0, sizeoftable):
self.ACK.append(False)
#przenoszenie do receivera potrzebnych wartosci
Receiver.numberOfValues = number
Receiver.numberOfFrames = sizeoftable
Receiver.reset_Data(Receiver)
i = 0
endOfWindow = self.windowSize -1
print("Rozmiar tablicy ramek:")
print(sizeoftable)
#wysyłanie poszczególnych ramek
while i < sizeoftable:
self.ACK[i] = self.receiver.receive_frame_stop_and_wait(self.tableOfFrames[i], i)
if self.ACK[i]:
i += 1
else:
self.ACK[i] = False
continue
class Frame:
value = None
seq_number = 0
pass
|
normal
|
{
"blob_id": "ecbcd023b8fec5763c6ff7f4cd0999426fae4a50",
"index": 9093,
"step-1": "<mask token>\n\n\nclass Sender:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def send_frame(self, frame):\n self.receiver.receiver_frame(frame)\n pass\n\n def send_frame_selective(self):\n self.tableOfFrames = Image.gruop_into_frames(self.image, self.size,\n self.ChosenSumAlgorithm)\n sizeoftable = len(self.tableOfFrames)\n for i in range(0, sizeoftable):\n self.ACK.append(False)\n Receiver.numberOfFrames = sizeoftable\n Receiver.reset_Data(Receiver)\n endOfWindow = self.windowSize - 1\n i = 0\n while i < sizeoftable:\n isCorrectFrame = True\n for j in range(i, endOfWindow + 1):\n if j == sizeoftable:\n break\n if self.ACK[j] == False:\n print(f'SENDER: wysłano obiekt nr \"{j}\"')\n self.ACK[j] = self.receiver.recieve_frame(self.\n tableOfFrames[j], j)\n else:\n pass\n for j in range(i, endOfWindow + 1):\n if j == sizeoftable:\n break\n if self.ACK[j] == False:\n isCorrectFrame = False\n if isCorrectFrame:\n if endOfWindow + self.windowSize >= sizeoftable:\n endOfWindow = sizeoftable\n else:\n endOfWindow += self.windowSize\n i += self.windowSize\n else:\n count = 0\n for j in range(i, endOfWindow + 1):\n if self.ACK[j] == True:\n count += 1\n else:\n break\n endOfWindow += count\n i += count\n <mask token>\n <mask token>\n\n\nclass Frame:\n value = None\n seq_number = 0\n pass\n",
"step-2": "<mask token>\n\n\nclass Sender:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, receiver):\n self.receiver = receiver\n pass\n\n def send_frame(self, frame):\n self.receiver.receiver_frame(frame)\n pass\n\n def send_frame_selective(self):\n self.tableOfFrames = Image.gruop_into_frames(self.image, self.size,\n self.ChosenSumAlgorithm)\n sizeoftable = len(self.tableOfFrames)\n for i in range(0, sizeoftable):\n self.ACK.append(False)\n Receiver.numberOfFrames = sizeoftable\n Receiver.reset_Data(Receiver)\n endOfWindow = self.windowSize - 1\n i = 0\n while i < sizeoftable:\n isCorrectFrame = True\n for j in range(i, endOfWindow + 1):\n if j == sizeoftable:\n break\n if self.ACK[j] == False:\n print(f'SENDER: wysłano obiekt nr \"{j}\"')\n self.ACK[j] = self.receiver.recieve_frame(self.\n tableOfFrames[j], j)\n else:\n pass\n for j in range(i, endOfWindow + 1):\n if j == sizeoftable:\n break\n if self.ACK[j] == False:\n isCorrectFrame = False\n if isCorrectFrame:\n if endOfWindow + self.windowSize >= sizeoftable:\n endOfWindow = sizeoftable\n else:\n endOfWindow += self.windowSize\n i += self.windowSize\n else:\n count = 0\n for j in range(i, endOfWindow + 1):\n if self.ACK[j] == True:\n count += 1\n else:\n break\n endOfWindow += count\n i += count\n\n def send_frame_go_back_n(self, delay):\n self.tableOfFrames = Image.gruop_into_frames(self.image, self.size,\n self.ChosenSumAlgorithm)\n size_of_table = len(self.tableOfFrames)\n for i in range(0, size_of_table):\n self.ACK.append(False)\n self.receiver.numberOfValues = self.image.size\n self.receiver.numberOfFrames = len(self.tableOfFrames)\n self.receiver.reset_Data()\n i = 0\n win_start = i\n win_end = i + self.windowSize\n length_table_of_frames = len(self.tableOfFrames)\n while i < length_table_of_frames:\n while i < win_end and i < length_table_of_frames:\n data = self.tableOfFrames[i]\n sequence_number = i\n print(f'\\nSENDER: wysłano obiekt nr \"{i}\"')\n self.ACK[i] = self.receiver.recieve_frame(frame=data,\n sequence_number=sequence_number)\n time.sleep(delay)\n if self.ACK[win_start]:\n print(f'SENDER: odebrano ATK \"{win_start}\"\\n')\n win_end += 1\n win_start += 1\n else:\n if win_end > length_table_of_frames:\n win_end = length_table_of_frames\n for k in range(win_start + 1, win_end):\n if self.ACK[k]:\n print(\n f'SENDER: odebrano ATK \"{k}, Pominięto ATK \"{win_start}\"\\n'\n )\n i = win_start - 1\n break\n i += 1\n time.sleep(delay)\n pass\n pass\n time.sleep(delay)\n if i == win_end:\n i = win_start\n pass\n print('SENDER: koniec wysyłania\\n')\n pass\n <mask token>\n\n\nclass Frame:\n value = None\n seq_number = 0\n pass\n",
"step-3": "<mask token>\n\n\nclass Sender:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, receiver):\n self.receiver = receiver\n pass\n\n def send_frame(self, frame):\n self.receiver.receiver_frame(frame)\n pass\n\n def send_frame_selective(self):\n self.tableOfFrames = Image.gruop_into_frames(self.image, self.size,\n self.ChosenSumAlgorithm)\n sizeoftable = len(self.tableOfFrames)\n for i in range(0, sizeoftable):\n self.ACK.append(False)\n Receiver.numberOfFrames = sizeoftable\n Receiver.reset_Data(Receiver)\n endOfWindow = self.windowSize - 1\n i = 0\n while i < sizeoftable:\n isCorrectFrame = True\n for j in range(i, endOfWindow + 1):\n if j == sizeoftable:\n break\n if self.ACK[j] == False:\n print(f'SENDER: wysłano obiekt nr \"{j}\"')\n self.ACK[j] = self.receiver.recieve_frame(self.\n tableOfFrames[j], j)\n else:\n pass\n for j in range(i, endOfWindow + 1):\n if j == sizeoftable:\n break\n if self.ACK[j] == False:\n isCorrectFrame = False\n if isCorrectFrame:\n if endOfWindow + self.windowSize >= sizeoftable:\n endOfWindow = sizeoftable\n else:\n endOfWindow += self.windowSize\n i += self.windowSize\n else:\n count = 0\n for j in range(i, endOfWindow + 1):\n if self.ACK[j] == True:\n count += 1\n else:\n break\n endOfWindow += count\n i += count\n\n def send_frame_go_back_n(self, delay):\n self.tableOfFrames = Image.gruop_into_frames(self.image, self.size,\n self.ChosenSumAlgorithm)\n size_of_table = len(self.tableOfFrames)\n for i in range(0, size_of_table):\n self.ACK.append(False)\n self.receiver.numberOfValues = self.image.size\n self.receiver.numberOfFrames = len(self.tableOfFrames)\n self.receiver.reset_Data()\n i = 0\n win_start = i\n win_end = i + self.windowSize\n length_table_of_frames = len(self.tableOfFrames)\n while i < length_table_of_frames:\n while i < win_end and i < length_table_of_frames:\n data = self.tableOfFrames[i]\n sequence_number = i\n print(f'\\nSENDER: wysłano obiekt nr \"{i}\"')\n self.ACK[i] = self.receiver.recieve_frame(frame=data,\n sequence_number=sequence_number)\n time.sleep(delay)\n if self.ACK[win_start]:\n print(f'SENDER: odebrano ATK \"{win_start}\"\\n')\n win_end += 1\n win_start += 1\n else:\n if win_end > length_table_of_frames:\n win_end = length_table_of_frames\n for k in range(win_start + 1, win_end):\n if self.ACK[k]:\n print(\n f'SENDER: odebrano ATK \"{k}, Pominięto ATK \"{win_start}\"\\n'\n )\n i = win_start - 1\n break\n i += 1\n time.sleep(delay)\n pass\n pass\n time.sleep(delay)\n if i == win_end:\n i = win_start\n pass\n print('SENDER: koniec wysyłania\\n')\n pass\n\n def send_frame_stop_and_wait(self):\n self.tableOfFrames = Image.gruop_into_frames(self.image, self.size,\n self.ChosenSumAlgorithm)\n print(self.tableOfFrames)\n sizeoftable = len(self.tableOfFrames)\n for i in range(0, sizeoftable):\n self.ACK.append(False)\n Receiver.numberOfValues = number\n Receiver.numberOfFrames = sizeoftable\n Receiver.reset_Data(Receiver)\n i = 0\n endOfWindow = self.windowSize - 1\n print('Rozmiar tablicy ramek:')\n print(sizeoftable)\n while i < sizeoftable:\n self.ACK[i] = self.receiver.receive_frame_stop_and_wait(self.\n tableOfFrames[i], i)\n if self.ACK[i]:\n i += 1\n else:\n self.ACK[i] = False\n continue\n\n\nclass Frame:\n value = None\n seq_number = 0\n pass\n",
"step-4": "from Receiver import Receiver\nimport time\nimport Image\n\n\nclass Sender:\n ACK = []\n size = None\n windowSize = None\n tableOfFrames = []\n ChosenSumAlgorithm = None\n\n def __init__(self, receiver):\n self.receiver = receiver\n pass\n\n def send_frame(self, frame):\n self.receiver.receiver_frame(frame)\n pass\n\n def send_frame_selective(self):\n self.tableOfFrames = Image.gruop_into_frames(self.image, self.size,\n self.ChosenSumAlgorithm)\n sizeoftable = len(self.tableOfFrames)\n for i in range(0, sizeoftable):\n self.ACK.append(False)\n Receiver.numberOfFrames = sizeoftable\n Receiver.reset_Data(Receiver)\n endOfWindow = self.windowSize - 1\n i = 0\n while i < sizeoftable:\n isCorrectFrame = True\n for j in range(i, endOfWindow + 1):\n if j == sizeoftable:\n break\n if self.ACK[j] == False:\n print(f'SENDER: wysłano obiekt nr \"{j}\"')\n self.ACK[j] = self.receiver.recieve_frame(self.\n tableOfFrames[j], j)\n else:\n pass\n for j in range(i, endOfWindow + 1):\n if j == sizeoftable:\n break\n if self.ACK[j] == False:\n isCorrectFrame = False\n if isCorrectFrame:\n if endOfWindow + self.windowSize >= sizeoftable:\n endOfWindow = sizeoftable\n else:\n endOfWindow += self.windowSize\n i += self.windowSize\n else:\n count = 0\n for j in range(i, endOfWindow + 1):\n if self.ACK[j] == True:\n count += 1\n else:\n break\n endOfWindow += count\n i += count\n\n def send_frame_go_back_n(self, delay):\n self.tableOfFrames = Image.gruop_into_frames(self.image, self.size,\n self.ChosenSumAlgorithm)\n size_of_table = len(self.tableOfFrames)\n for i in range(0, size_of_table):\n self.ACK.append(False)\n self.receiver.numberOfValues = self.image.size\n self.receiver.numberOfFrames = len(self.tableOfFrames)\n self.receiver.reset_Data()\n i = 0\n win_start = i\n win_end = i + self.windowSize\n length_table_of_frames = len(self.tableOfFrames)\n while i < length_table_of_frames:\n while i < win_end and i < length_table_of_frames:\n data = self.tableOfFrames[i]\n sequence_number = i\n print(f'\\nSENDER: wysłano obiekt nr \"{i}\"')\n self.ACK[i] = self.receiver.recieve_frame(frame=data,\n sequence_number=sequence_number)\n time.sleep(delay)\n if self.ACK[win_start]:\n print(f'SENDER: odebrano ATK \"{win_start}\"\\n')\n win_end += 1\n win_start += 1\n else:\n if win_end > length_table_of_frames:\n win_end = length_table_of_frames\n for k in range(win_start + 1, win_end):\n if self.ACK[k]:\n print(\n f'SENDER: odebrano ATK \"{k}, Pominięto ATK \"{win_start}\"\\n'\n )\n i = win_start - 1\n break\n i += 1\n time.sleep(delay)\n pass\n pass\n time.sleep(delay)\n if i == win_end:\n i = win_start\n pass\n print('SENDER: koniec wysyłania\\n')\n pass\n\n def send_frame_stop_and_wait(self):\n self.tableOfFrames = Image.gruop_into_frames(self.image, self.size,\n self.ChosenSumAlgorithm)\n print(self.tableOfFrames)\n sizeoftable = len(self.tableOfFrames)\n for i in range(0, sizeoftable):\n self.ACK.append(False)\n Receiver.numberOfValues = number\n Receiver.numberOfFrames = sizeoftable\n Receiver.reset_Data(Receiver)\n i = 0\n endOfWindow = self.windowSize - 1\n print('Rozmiar tablicy ramek:')\n print(sizeoftable)\n while i < sizeoftable:\n self.ACK[i] = self.receiver.receive_frame_stop_and_wait(self.\n tableOfFrames[i], i)\n if self.ACK[i]:\n i += 1\n else:\n self.ACK[i] = False\n continue\n\n\nclass Frame:\n value = None\n seq_number = 0\n pass\n",
"step-5": "from Receiver import Receiver\nimport time\nimport Image\n\n\nclass Sender:\n ACK = []\n size = None\n windowSize = None\n tableOfFrames = []\n ChosenSumAlgorithm = None\n def __init__(self, receiver):\n self.receiver = receiver\n pass\n\n def send_frame(self, frame):\n self.receiver.receiver_frame(frame)\n pass\n\n def send_frame_selective(self):\n #stworzenie tablicy z ramkami\n self.tableOfFrames = Image.gruop_into_frames(self.image, self.size, self.ChosenSumAlgorithm)\n\n # zapisuje ilosc ramek dopedli wysylania\n sizeoftable = len(self.tableOfFrames)\n\n # tworzy tablice o rozmiarze ilosci ramek z potwierdzeniami lub odrzuceniami pakietów\n for i in range(0, sizeoftable):\n self.ACK.append(False)\n\n # przenoszenie do receivera potrzebnych wartosci\n Receiver.numberOfFrames = sizeoftable\n Receiver.reset_Data(Receiver)\n endOfWindow = self.windowSize - 1\n i = 0\n # petla wysylajaca ramki zgodnie z regulami algotrytmu selektywnego\n while i < sizeoftable:\n isCorrectFrame = True\n # petla operujaca oknem i wysylajaca te ramki ktore sender od nas chce\n for j in range(i, endOfWindow + 1):\n if j == sizeoftable:\n break\n if self.ACK[j] == False:\n # time.sleep(0.2)\n print(f'SENDER: wysłano obiekt nr \"{j}\"')\n self.ACK[j] = self.receiver.recieve_frame(self.tableOfFrames[j], j)\n else:\n pass\n # petla sprawdzajaca czy cala ramka zostala przeslana bez zarzutów\n for j in range(i, endOfWindow + 1):\n if j == sizeoftable:\n break\n if self.ACK[j] == False:\n isCorrectFrame = False\n # warunki odpowiadajace za przesuwanie sie okna gdy ramka jest dobra lub gdy ktorys z pakietow jest uszkodzony\n if isCorrectFrame:\n if (endOfWindow + self.windowSize) >= sizeoftable:\n endOfWindow = sizeoftable\n else:\n endOfWindow += self.windowSize\n i += self.windowSize\n else:\n count = 0\n for j in range(i, endOfWindow + 1):\n if self.ACK[j] == True:\n count += 1\n else:\n break\n endOfWindow += count\n i += count\n\n def send_frame_go_back_n(self, delay):\n # self.image = interfere(self.image)\n # przygotowanie ramek fo wysłania\n # 1. stworzenie tablicy ramek z sumą kontrolną\n self.tableOfFrames = Image.gruop_into_frames(self.image, self.size, self.ChosenSumAlgorithm)\n\n # pokazuje ilość ramek\n size_of_table = len(self.tableOfFrames)\n\n # tworzy tablice o rozmiarze ilości ramek z potwierdzeniami lub odrzuceniami pakietów\n for i in range(0, size_of_table):\n self.ACK.append(False)\n\n # przenoszenie do receivera potrzebnych wartości\n self.receiver.numberOfValues = self.image.size\n self.receiver.numberOfFrames = len(self.tableOfFrames)\n self.receiver.reset_Data()\n\n # rozpoczęcie przesyłania\n i = 0\n win_start = i\n win_end = i + self.windowSize\n length_table_of_frames = len(self.tableOfFrames)\n\n while i < length_table_of_frames:\n while i < win_end and i < length_table_of_frames:\n # pobranie ramki do wysłania\n data = self.tableOfFrames[i]\n sequence_number = i\n\n # wysyłanie ramki\n print(f'\\nSENDER: wysłano obiekt nr \"{i}\"')\n self.ACK[i] = self.receiver.recieve_frame(frame=data, sequence_number=sequence_number)\n\n time.sleep(delay)\n if self.ACK[win_start]:\n print(f'SENDER: odebrano ATK \"{win_start}\"\\n')\n win_end += 1\n win_start += 1\n # i = win_start\n else:\n if win_end > length_table_of_frames:\n win_end = length_table_of_frames\n for k in range(win_start + 1, win_end):\n if self.ACK[k]:\n print(f'SENDER: odebrano ATK \"{k}, Pominięto ATK \"{win_start}\"\\n')\n i = win_start - 1\n break\n\n i += 1\n time.sleep(delay)\n pass\n pass\n time.sleep(delay)\n if i == win_end:\n i = win_start\n pass\n\n print('SENDER: koniec wysyłania\\n')\n pass\n\n# Metoda wysyłająca dla protokołu stop-and-wait\n def send_frame_stop_and_wait(self):\n # test\n # print(self.image)\n self.tableOfFrames = Image.gruop_into_frames(self.image, self.size, self.ChosenSumAlgorithm)\n\n #wyświetlenie tablicy zawierającej wszystkie ramki\n print(self.tableOfFrames)\n\n #zapis ilości ramek\n sizeoftable = len(self.tableOfFrames)\n\n #tworzy tablice o rozmiarze ilosci ramek z potwierdzeniami lub odrzuceniami pakietów\n for i in range(0, sizeoftable):\n self.ACK.append(False)\n\n #przenoszenie do receivera potrzebnych wartosci\n Receiver.numberOfValues = number\n Receiver.numberOfFrames = sizeoftable\n Receiver.reset_Data(Receiver)\n i = 0\n endOfWindow = self.windowSize -1\n\n print(\"Rozmiar tablicy ramek:\")\n print(sizeoftable)\n\n #wysyłanie poszczególnych ramek\n while i < sizeoftable:\n self.ACK[i] = self.receiver.receive_frame_stop_and_wait(self.tableOfFrames[i], i)\n if self.ACK[i]:\n i += 1\n else:\n self.ACK[i] = False\n continue\n\nclass Frame:\n value = None\n seq_number = 0\n pass\n",
"step-ids": [
5,
7,
8,
10,
11
]
}
|
[
5,
7,
8,
10,
11
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.