I am having problems with writing to my HTML file.
I want to be able to make my code place what I have written in HTML, but my code will only do it when I do not have any While/If statements in this definition. If I do have Whiles/Ifs, my HTML file will simply just become blank. I have no idea why this happens, and I can't seem to find a workaround.
Is there any way to use Whiles/Ifs without making my code delete everything in my file, and instead make it write what I want to in there?
def invoice_creator_window():
global total_cost, total_cost_list, list_of_items, invoice_created
invoice_created = Toplevel()
invoice_created.focus_set()
invoice_created.resizable(width = True, height = False)
invoice_created.title("Invoice Created")
invoice_created.geometry("300x300")
invoice_created.geometry("+400+400")
invoice_created.configure(bg = "limegreen")
currentDisplay = 10
print(total_cost, total_cost_list, list_of_items)
done = Label(invoice_created, text = "Items have been purchased. Invoice has been created. Please check this program's file location.")
invoice_created = Button(invoice_created, text = "Done", bg = "white", command = close_window)
#
done.grid(row = 1, column = 1, padx = 7.5, pady = space_between)
invoice_created.grid(row = 2, column = 1, padx = 7.5, pady = space_between)
# This section is for the invoice creation with HTML.
html_formatting_start = """<!DOCTYPE html>
<html>
<head>
<title>Games R Us - Invoice</title>
</head>
<body>
<style>
body {background-color: #F7D358;}
h1 {color: #775A03;}
p {color: ; border: 1px solid #775A03; padding: 15px; width: 650px}
</style>
<center>
<h1>Games R Us - Invoice Document</h1>
"""
counter = 0
while len(list_of_items) > 0:
global html_formatting_mid
print(counter)
html_formatting_mid = ("""
<h3>
<p>
<img src="https://steamcdn-a.akamaihd.net/steam/apps/211420/header.jpg?t=1483694369"</img>
<br>""" + str(list_of_items[counter]) + """<br>
<i>$""" + str(total_cost_list[counter]) + """ AUD</i>
</p>
</h3>
""")
if counter >= len(list_of_items) - 1:
return
else:
counter += 1
html_formatting_end = """
<h2>In Total: $""" + str(total_cost) +""" AUD</h2>
<br>
<b>Information Grabbed from These Links: </b>
Steam's New Releases [LIVE] -
Steam's Top Sellers [LIVE] -
Umart's Headphones [PRE-DOWNLOADED] -
Umart's Microphones [PRE-DOWNLOADED]
</center>
</body>
</html>"""
invoice_creation = open(invoice_file, "w")
invoice_creation.write(html_formatting_start)
invoice_creation.write(html_formatting_mid)
invoice_creation.write(html_formatting_end)
invoice_creation.close()
#############################################################################
button_buy = Button(welcome_window, text = "Buy", fg = "white", bg = "goldenrod", font = gui_font_10,
command = invoice_creator_window)
Note: "total_cost_list" and "list_of_items" are all lists. "total_cost" is a value. Do not worry too much about the context of these, but I wanted to clarify in case they might be affecting anything.
Here is a fixed version of your code in as simple a container as possible.
from tkinter import *
import webbrowser
root = Tk ()
space_between, invoice_file = 5, "Invoice.html"
total_cost, total_cost_list, list_of_items = 10, [1, 9], ["Something", "Something 2"]
def close_window (): root.destroy ()
def invoice_creator_window():
global total_cost, total_cost_list, list_of_items, invoice_created
invoice_created = Toplevel()
invoice_created.focus_set()
invoice_created.resizable(width = True, height = False)
invoice_created.title("Invoice Created")
invoice_created.geometry("300x300")
invoice_created.geometry("+400+400")
invoice_created.configure(bg = "limegreen")
currentDisplay = 10
print(total_cost, total_cost_list, list_of_items)
done = Label(invoice_created, text = "Items have been purchased. Invoice has been created.")
invoice_created = Button(invoice_created, text = "Done", bg = "white", command = close_window)
#
done.grid(row = 1, column = 1, padx = 7.5, pady = space_between)
invoice_created.grid(row = 2, column = 1, padx = 7.5, pady = space_between)
# This section is for the invoice creation with HTML.
html_formatting_start = """<!DOCTYPE html>
<html>
<head>
<title>Games R Us - Invoice</title>
</head>
<body>
<style>
body {background-color: #F7D358;}
h1 {color: #775A03;}
p {color: ; border: 1px solid #775A03; padding: 15px; width: 650px}
</style>
<center>
<h1>Games R Us - Invoice Document</h1>
"""
counter = 0
html_formatting_mid = ""
while len(list_of_items) > 0:
print(counter)
html_formatting_mid += """
<h3>
<p>
<img src="https://steamcdn-a.akamaihd.net/steam/apps/211420/header.jpg?t=1483694369"</img>
<br>""" + str(list_of_items[counter]) + """<br>
<i>$""" + str(total_cost_list[counter]) + """ AUD</i>
</p>
</h3>
"""
if counter >= len(list_of_items) - 1:
break
else:
counter += 1
html_formatting_end = """
<h2>In Total: $""" + str(total_cost) +""" AUD</h2>
<br>
<b>Information Grabbed from These Links: </b>
Steam's New Releases [LIVE] -
Steam's Top Sellers [LIVE] -
Umart's Headphones [PRE-DOWNLOADED] -
Umart's Microphones [PRE-DOWNLOADED]
</center>
</body>
</html>"""
invoice_creation = open(invoice_file, "w")
invoice_creation.write (html_formatting_start + html_formatting_mid + html_formatting_end)
invoice_creation.close ()
webbrowser.open (invoice_file)
#############################################################################
button_buy = Button(root, text = "Buy", fg = "white", bg = "goldenrod",
command = invoice_creator_window).pack ()
root.mainloop ()
I found a solution.
def invoice_creator_window():
global total_cost, total_cost_list, list_of_items, invoice_created
invoice_created = Toplevel()
invoice_created.focus_set()
invoice_created.resizable(width = True, height = False)
invoice_created.title("Invoice Created")
invoice_created.geometry("300x300")
invoice_created.geometry("+400+400")
invoice_created.configure(bg = "limegreen")
currentDisplay = 10
print(total_cost, total_cost_list, list_of_items)
done = Label(invoice_created, text = "Items have been purchased. Invoice has been created. Please check this program's file location.")
invoice_created = Button(invoice_created, text = "Done", bg = "white", command = close_window)
#
done.grid(row = 1, column = 1, padx = 7.5, pady = space_between)
invoice_created.grid(row = 2, column = 1, padx = 7.5, pady = space_between)
# This section is for the invoice creation with HTML.
html_formatting_start = """<!DOCTYPE html>
<html>
<head>
<title>Games R Us - Invoice</title>
</head>
<body>
<style>
body {background-color: #F7D358;}
h1 {color: #775A03;}
p {color: ; border: 1px solid #775A03; padding: 15px; width: 650px}
</style>
<center>
<h1>Games R Us - Invoice Document</h1>
"""
counter = 0
html_formatting_mid = ""
for items in list_of_items:
print(counter)
html_formatting_mid += ("""
<h3>
<p>
<img src="https://steamcdn-a.akamaihd.net/steam/apps/211420/header.jpg?t=1483694369"</img>
<br>""" + str(list_of_items[counter]) + """<br>
<i>$""" + str(total_cost_list[counter]) + """ AUD</i>
</p>
</h3>
""")
counter += 1
html_formatting_end = """
<h2>In Total: $""" + str(total_cost) +""" AUD</h2>
<br>
<b>Information Grabbed from These Links: </b>
Steam's New Releases [LIVE] -
Steam's Top Sellers [LIVE] -
Umart's Headphones [PRE-DOWNLOADED] -
Umart's Microphones [PRE-DOWNLOADED]
</center>
</body>
</html>"""
invoice_creation = open(invoice_file, "w")
invoice_creation.write(html_formatting_start)
invoice_creation.write(html_formatting_mid)
invoice_creation.write(html_formatting_end)
invoice_creation.close()
#############################################################################
button_buy = Button(welcome_window, text = "Buy", fg = "white", bg = "goldenrod", font = gui_font_10,
command = invoice_creator_window)
I went back to my older use of a for loop and tried using that. Except this time, I added html_formatting_mid += (""" to it, and then before the for loop, just added html_formatting_mid = "", like Minion Jim showed.
It works fully now.
A short answer would be, you could just write in append mode. open (filename, 'a') instead of open (filename, 'w'). This will add on to whatever is already in the file, so you may want to truncate it first.
Related
I am creating a simulated covid-care center in which i am using python's flask, html etc.
In this i will have a table showing some values at the home screen and then a chatbot and faq page. I have made the chat bot and faqs but i am having troubles updating my html data dynamically. (The data is created at the backend using random and thread modules).
Here is my main.py:
import flask
import time
import mysql.connector
app = flask.Flask(__name__)
app.static_folder = 'static'
#I am storing the values in a database
f = mysql.connector.connect(host = "localhost", user = "root", passwd = "")
mycur = f.cursor()
mycur.execute("use one_stop_healthcare;")
mycur.execute("select * from ccinfo;")
lines = mycur.fetchall()
#app.route("/")
def print_val():
global lines
return flask.render_template("index.html", lines = lines)
app.run()
Here is my index.html which is stored in a templates directory:
<html>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 15px;
text-align: center;
}
.button {
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
.button1 {background-color: #4CAF50;} /* Green */
.button2 {background-color: #008CBA;} /* Blue */
</style>
<head>
<title> One Stop Healthcare </title>
</head>
<body>
<h2> The data for all the COVID care centers </h1>
<table style="width:100%">
<tr>
<th> ID </th>
<th> NAME </th>
<th> LOCATION </th>
<th> BEDS </th>
<th> DISCARGED </th>
<th> ACTIVE </th>
<th> DEAD </th>
<th> DOCTORS </th>
<th> MONEY </th>
<th> PPE_KITS </th>
<th> BLANKETS </th>
<th> MASKS </th>
<th> SANITIZER </th>
</tr>
{% for line in lines %}
<tr>
{% for i in line %}
<td>{{ i }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<button type="button"> Chatbot </button>
<button type="button"> FAQs </button>
</body>
</html>
Here is my database + inserting the values into the database (You just need to run this once to insert the values and create the database). It doesn't have a issue
import mysql.connector
f = mysql.connector.connect(host = "localhost", user = "root", passwd = "")
mycur = f.cursor()
mycur.execute("create database One_Stop_Healthcare;")
f.commit()
mycur.execute("use One_Stop_Healthcare;")
print("database created")
que = "create table ccinfo(ID INTEGER NOT NULL primary key, NAME varchar(20), LOCATION varchar(20), BEDS integer, DISCHARGED integer, ACTIVE integer, DEAD integer, DOCTORS integer, MONEY integer, PPE_KITS integer, BLANKETS integer, MASKS integer, SANITIZER integer);"
mycur.execute(que)
print("table created")
mycur.execute("insert into ccinfo(ID, NAME, LOCATION, BEDS, DISCHARGED, ACTIVE, DEAD, DOCTORS, MONEY , PPE_KITS, BLANKETS, MASKS, SANITIZER)values(1, 'Ward-1', 'KRM', 500, 100, 300, 50, 25, 100000, 20, 100, 100, 70);")
mycur.execute("insert into ccinfo(ID, NAME, LOCATION, BEDS, DISCHARGED, ACTIVE, DEAD, DOCTORS, MONEY , PPE_KITS, BLANKETS, MASKS, SANITIZER)values(2, 'Ward-2', 'KRM', 1000, 290, 700, 150, 78, 250000, 40, 600, 300, 130);")
mycur.execute("insert into ccinfo(ID, NAME, LOCATION, BEDS, DISCHARGED, ACTIVE, DEAD, DOCTORS, MONEY , PPE_KITS, BLANKETS, MASKS, SANITIZER)values(3, 'Ward-3', 'KRM', 50, 10, 30, 5, 5, 80000, 7, 50, 30, 40);")
mycur.execute("insert into ccinfo(ID, NAME, LOCATION, BEDS, DISCHARGED, ACTIVE, DEAD, DOCTORS, MONEY , PPE_KITS, BLANKETS, MASKS, SANITIZER)values(4, 'Ward-4', 'HSR', 1500, 400, 1300, 250, 100, 400000, 70, 500, 300, 150);")
mycur.execute("insert into ccinfo(ID, NAME, LOCATION, BEDS, DISCHARGED, ACTIVE, DEAD, DOCTORS, MONEY , PPE_KITS, BLANKETS, MASKS, SANITIZER)values(5, 'Ward-5', 'Bellandur', 500, 50, 100, 25, 40, 90000, 30, 100, 90, 90);")
f.commit()
And finally here is where i am simulating the data
import threading
import time
import random
import mysql.connector
TC=5 #Total thread count
count = 0
thr = [0 for i in range(TC)]
db_data = [[] for i in range(TC+1)]
def print_time():
global count
global db_data
count = count + 1
mylocal = count
'''
1: id
2: location
3: beds
4: discharged
5: active
6: dead
7: doctors
8: money
9: ppe kits
10: blankets
11: masks
12: sanitizer
'''
i = 0
while i < 5:
i = i+1
x = random.randint(1,350)
#print(x)
if x == 1:
db_data[mylocal][3] = db_data[mylocal][3] + 50
st = "UPDATE ccinfo SET BEDS = {} where ID = {}".format(db_data[mylocal][3], mylocal)
elif x == 2 and db_data[mylocal][3] > 50:
db_data[mylocal][3] = db_data[mylocal][3] - 50
st = "UPDATE ccinfo SET BEDS = {} where ID = {}".format(db_data[mylocal][3], mylocal)
elif x == 3:
db_data[mylocal][7] = db_data[mylocal][7] + 1
st = "UPDATE ccinfo SET DOCTORS = {} where ID = {}".format(db_data[mylocal][7], mylocal)
elif x == 4 and db_data[mylocal][7] > 7:
db_data[mylocal][7] = db_data[mylocal][7] - 1
st = "UPDATE ccinfo SET DOCTORS = {} where ID = {}".format(db_data[mylocal][7], mylocal)
elif x > 4 and x < 101:
db_data[mylocal][4] = db_data[mylocal][4] + 1
st = "UPDATE ccinfo SET DISCHARGED = {} where ID = {}".format(db_data[mylocal][4], mylocal)
elif x > 100 and x < 201:
db_data[mylocal][5] = db_data[mylocal][5] + 1
st = "UPDATE ccinfo SET ACTIVE = {} where ID = {}".format(db_data[mylocal][5], mylocal)
elif x > 200 and x < 211:
db_data[mylocal][6] = db_data[mylocal][6] + 1
st = "UPDATE ccinfo SET DEAD = {} where ID = {}".format(db_data[mylocal][6], mylocal)
elif x > 210 and x < 221:
db_data[mylocal][8] = db_data[mylocal][8] + 10000
st = "UPDATE ccinfo SET MONEY = {} where ID = {}".format(db_data[mylocal][8], mylocal)
elif x > 220 and x < 231 and db_data[mylocal][8] > 20000:
db_data[mylocal][8] = db_data[mylocal][8] - 10000
st = "UPDATE ccinfo SET MONEY = {} where ID = {}".format(db_data[mylocal][8], mylocal)
elif x > 230 and x < 241:
db_data[mylocal][9] = db_data[mylocal][9] + 5
st = "UPDATE ccinfo SET PPE_KITS = {} where ID = {}".format(db_data[mylocal][9], mylocal)
elif x > 240 and x < 251 and db_data[mylocal][9] > 0:
db_data[mylocal][9] = db_data[mylocal][9] - 5
st = "UPDATE ccinfo SET PPE_KITS = {} where ID = {}".format(db_data[mylocal][9], mylocal)
elif x > 250 and x < 261:
db_data[mylocal][10] = db_data[mylocal][10] + 5
st = "UPDATE ccinfo SET BLANKETS = {} where ID = {}".format(db_data[mylocal][10], mylocal)
elif x > 260 and x < 271 and db_data[mylocal][10] > 0:
db_data[mylocal][10] = db_data[mylocal][10] - 5
st = "UPDATE ccinfo SET BLANKETS = {} where ID = {}".format(db_data[mylocal][10], mylocal)
elif x > 270 and x < 281:
db_data[mylocal][11] = db_data[mylocal][11] + 5
st = "UPDATE ccinfo SET MASKS = {} where ID = {}".format(db_data[mylocal][11], mylocal)
elif x > 280 and x < 291 and db_data[mylocal][11] > 0:
db_data[mylocal][11] = db_data[mylocal][11] - 5
st = "UPDATE ccinfo SET MASKS = {} where ID = {}".format(db_data[mylocal][11], mylocal)
elif x > 290 and x < 301:
db_data[mylocal][12] = db_data[mylocal][12] + 5
st = "UPDATE ccinfo SET SANITIZER = {} where ID = {}".format(db_data[mylocal][12], mylocal)
elif x > 300 and x < 311 and db_data[mylocal][12] > 0:
db_data[mylocal][12] = db_data[mylocal][12] - 5
st = "UPDATE ccinfo SET SANITIZER = {} where ID = {}".format(db_data[mylocal][12], mylocal)
print(st)
mycur.execute(st)
f.commit()
time.sleep(10)
if __name__ == "__main__":
f = mysql.connector.connect(host = "localhost", user = "root", passwd = "")
mycur = f.cursor()
mycur.execute("use one_stop_healthcare;")
mycur.execute("select * from ccinfo;")
dat = mycur.fetchall()
for val in dat:
i = val[0]
db_data[i] = list(val)
print(db_data)
for i in range(TC):
thr[i] = threading.Thread(target=print_time)
thr[i].start()
time.sleep(1)
for i in range(TC):
thr[i].join()
```
Simply add this <meta http-equiv="refresh" content="5"> to your HTML in the head
I am working on a python project where I have data stored in QTableWidget. I have to export this data into excel sheet and PDF. I have been able to export data to excel sheet using below code. But unable to understand how can I convert it to PDF.
filename, _ = QFileDialog.getSaveFileName(self, 'Save File', '', ".xls(*.xls)")
wbk = xlwt.Workbook()
sheet = wbk.add_sheet("sheet", cell_overwrite_ok=True)
style = xlwt.XFStyle()
font = xlwt.Font()
font.bold = True
style.font = font
model = self.home_ui.reports_table.model()
for c in range(model.columnCount()):
text = model.headerData(c, QtCore.Qt.Horizontal)
first_col = sheet.col(c+1)
l = len(text)
first_col.width = (256 * l) + 1000
sheet.write(0, c + 1, text, style=style)
for r in range(model.rowCount()):
text = model.headerData(r, QtCore.Qt.Vertical)
sheet.write(r + 1, 0, text, style=style)
for c in range(model.columnCount()):
for r in range(model.rowCount()):
text = model.data(model.index(r, c))
sheet.write(r + 1, c + 1, text)
wbk.save(filename)
Above code is working fine and saving data to excel.
I have looked into other questions with same topic but all of them are in c++. I am looking for python equivalent.
Can anyone give me some good suggestion on how to convert data to PDF. Please help. Thanks
When you review an answer you should not only see the code but the solution itself, that is, the logic that is in the background. In this particular case the solution is to create an HTML that shows the table content, and use QTextDocument with QPrinter to print the HTML to PDF.
Considering the above, it is not necessary to do the translation since it is enough to implement it from scratch since the logic is clear.
from PyQt5 import QtCore, QtGui, QtWidgets, QtPrintSupport
app = QtWidgets.QApplication([])
w = QtWidgets.QTableWidget(10, 10)
for i in range(10):
for j in range(10):
it = QtWidgets.QTableWidgetItem("{}-{}".format(i, j))
w.setItem(i, j, it)
filename = "table.pdf"
model = w.model()
printer = QtPrintSupport.QPrinter(QtPrintSupport.QPrinter.PrinterResolution)
printer.setOutputFormat(QtPrintSupport.QPrinter.PdfFormat)
printer.setPaperSize(QtPrintSupport.QPrinter.A4)
printer.setOrientation(QtPrintSupport.QPrinter.Landscape)
printer.setOutputFileName(filename)
doc = QtGui.QTextDocument()
html = """<html>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
</head>"""
html += "<table><thead>"
html += "<tr>"
for c in range(model.columnCount()):
html += "<th>{}</th>".format(model.headerData(c, QtCore.Qt.Horizontal))
html += "</tr></thead>"
html += "<tbody>"
for r in range(model.rowCount()):
html += "<tr>"
for c in range(model.columnCount()):
html += "<td>{}</td>".format(model.index(r, c).data() or "")
html += "</tr>"
html += "</tbody></table>"
doc.setHtml(html)
doc.setPageSize(QtCore.QSizeF(printer.pageRect().size()))
doc.print_(printer)
i used unittest + HTMLTestRunner to test the software,early it runs very well,but yestarday i found it occured an error
File "/usr/lib/python2.7/site-packages/cephmgmtclient/sds_cli_auto_test/HTMLTestRunner.py", line 558, in complete_output
return self.outputBuffer.getvalue()
AttributeError: '_TestResult' object has no attribute 'outputBuffer'
i searched the reason on internet,some people ask me to add the code in HTMLTestRunner.py and the code is below:
class _TestResult(TestResult):
# note: _TestResult is a pure representation of results.
# It lacks the output and reporting ability compares to unittest._TextTestResult.
def __init__(self, verbosity=1):
TestResult.__init__(self)
self.stdout0 = None
self.stderr0 = None
self.success_count = 0
self.failure_count = 0
self.error_count = 0
self.verbosity = verbosity
# result is a list of result in 4 tuple
# (
# result code (0: success; 1: fail; 2: error),
# TestCase object,
# Test output (byte string),
# stack trace,
# )
self.result = []
self.outputBuffer = io.BytesIO()
#self.test_start_time = round(time.time(), 2)
afer do this,it not occur the same error,but my test cases cannot run,when i python the case.py,the print is below
Begin to run test_template 1 and apply the job map
E setUpClass (__main__.Test_case01)
Time Elapsed: 0:00:00.013564
it is so strange!because it normal in last version and i never changed my test case!
i can not figure out
the all codes of HTMLTestRunner.py is below
# TODO: color stderr
# TODO: simplify javascript using ,ore than 1 class in the class attribute?
import datetime
import StringIO
import sys
import time
import unittest
from xml.sax import saxutils
# ------------------------------------------------------------------------
# The redirectors below are used to capture output during testing. Output
# sent to sys.stdout and sys.stderr are automatically captured. However
# in some cases sys.stdout is already cached before HTMLTestRunner is
# invoked (e.g. calling logging.basicConfig). In order to capture those
# output, use the redirectors for the cached stream.
#
# e.g.
# >>> logging.basicConfig(stream=HTMLTestRunner.stdout_redirector)
# >>>
class OutputRedirector(object):
""" Wrapper to redirect stdout or stderr """
def __init__(self, fp):
self.fp = fp
def write(self, s):
self.fp.write(s)
def writelines(self, lines):
self.fp.writelines(lines)
def flush(self):
self.fp.flush()
stdout_redirector = OutputRedirector(sys.stdout)
stderr_redirector = OutputRedirector(sys.stderr)
# ----------------------------------------------------------------------
# Template
class Template_mixin(object):
"""
Define a HTML template for report customerization and generation.
Overall structure of an HTML report
HTML
+------------------------+
|<html> |
| <head> |
| |
| STYLESHEET |
| +----------------+ |
| | | |
| +----------------+ |
| |
| </head> |
| |
| <body> |
| |
| HEADING |
| +----------------+ |
| | | |
| +----------------+ |
| |
| REPORT |
| +----------------+ |
| | | |
| +----------------+ |
| |
| ENDING |
| +----------------+ |
| | | |
| +----------------+ |
| |
| </body> |
|</html> |
+------------------------+
"""
STATUS = {
0: 'pass',
1: 'fail',
2: 'error',
}
DEFAULT_TITLE = 'Unit Test Report'
DEFAULT_DESCRIPTION = ''
# ------------------------------------------------------------------------
# HTML Template
HTML_TMPL = r"""<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>%(title)s</title>
<meta name="generator" content="%(generator)s"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
%(stylesheet)s
</head>
<body>
<script language="javascript" type="text/javascript"><!--
output_list = Array();
/* level - 0:Summary; 1:Failed; 2:All */
function showCase(level) {
trs = document.getElementsByTagName("tr");
for (var i = 0; i < trs.length; i++) {
tr = trs[i];
id = tr.id;
if (id.substr(0,2) == 'ft') {
if (level < 1) {
tr.className = 'hiddenRow';
}
else {
tr.className = '';
}
}
if (id.substr(0,2) == 'pt') {
if (level > 1) {
tr.className = '';
}
else {
tr.className = 'hiddenRow';
}
}
}
}
function showClassDetail(cid, count) {
var id_list = Array(count);
var toHide = 1;
for (var i = 0; i < count; i++) {
tid0 = 't' + cid.substr(1) + '.' + (i+1);
tid = 'f' + tid0;
tr = document.getElementById(tid);
if (!tr) {
tid = 'p' + tid0;
tr = document.getElementById(tid);
}
id_list[i] = tid;
if (tr.className) {
toHide = 0;
}
}
for (var i = 0; i < count; i++) {
tid = id_list[i];
if (toHide) {
document.getElementById('div_'+tid).style.display = 'none'
document.getElementById(tid).className = 'hiddenRow';
}
else {
document.getElementById(tid).className = '';
}
}
}
function showTestDetail(div_id){
var details_div = document.getElementById(div_id)
var displayState = details_div.style.display
// alert(displayState)
if (displayState != 'block' ) {
displayState = 'block'
details_div.style.display = 'block'
}
else {
details_div.style.display = 'none'
}
}
function html_escape(s) {
s = s.replace(/&/g,'&');
s = s.replace(/</g,'<');
s = s.replace(/>/g,'>');
return s;
}
/* obsoleted by detail in <div>
function showOutput(id, name) {
var w = window.open("", //url
name,
"resizable,scrollbars,status,width=800,height=450");
d = w.document;
d.write("<pre>");
d.write(html_escape(output_list[id]));
d.write("\n");
d.write("<a href='javascript:window.close()'>close</a>\n");
d.write("</pre>\n");
d.close();
}
*/
--></script>
%(heading)s
%(report)s
%(ending)s
</body>
</html>
"""
# variables: (title, generator, stylesheet, heading, report, ending)
# ------------------------------------------------------------------------
# Stylesheet
#
# alternatively use a <link> for external style sheet, e.g.
# <link rel="stylesheet" href="$url" type="text/css">
STYLESHEET_TMPL = """
<style type="text/css" media="screen">
body { font-family: verdana, arial, helvetica, sans-serif; font-size: 80%; }
table { font-size: 100%; }
pre { }
/* -- heading ---------------------------------------------------------------------- */
h1 {
font-size: 16pt;
color: gray;
}
.heading {
margin-top: 0ex;
margin-bottom: 1ex;
}
.heading .attribute {
margin-top: 1ex;
margin-bottom: 0;
}
.heading .description {
margin-top: 2ex;
margin-bottom: 4ex;
}
/* -- css div popup ------------------------------------------------------------------------ */
a.popup_link {
}
a.popup_link:hover {
color: red;
}
.popup_window {
display: none;
position: relative;
left: 0px;
top: 0px;
/*border: solid #627173 1px; */
padding: 10px;
background-color: #E6E6D6;
font-family: "Lucida Console", "Courier New", Courier, monospace;
text-align: left;
font-size: 8pt;
width: 500px;
}
}
/* -- report ------------------------------------------------------------------------ */
#show_detail_line {
margin-top: 3ex;
margin-bottom: 1ex;
}
#result_table {
width: 80%;
border-collapse: collapse;
border: 1px solid #777;
}
#header_row {
font-weight: bold;
color: white;
background-color: #777;
}
#result_table td {
border: 1px solid #777;
padding: 2px;
}
#total_row { font-weight: bold; }
.passClass { background-color: #6c6; }
.failClass { background-color: #c60; }
.errorClass { background-color: #c00; }
.passCase { color: #6c6; }
.failCase { color: #c60; font-weight: bold; }
.errorCase { color: #c00; font-weight: bold; }
.hiddenRow { display: none; }
.testcase { margin-left: 2em; }
/* -- ending ---------------------------------------------------------------------- */
#ending {
}
</style>
"""
# ------------------------------------------------------------------------
# Heading
#
HEADING_TMPL = """<div class='heading'>
<h1>%(title)s</h1>
%(parameters)s
<p class='description'>%(description)s</p>
</div>
""" # variables: (title, parameters, description)
HEADING_ATTRIBUTE_TMPL = """<p class='attribute'><strong>%(name)s:</strong> %(value)s</p>
""" # variables: (name, value)
# ------------------------------------------------------------------------
# Report
#
REPORT_TMPL = """
<p id='show_detail_line'>Show
<a href='javascript:showCase(0)'>Summary</a>
<a href='javascript:showCase(1)'>Failed</a>
<a href='javascript:showCase(2)'>All</a>
</p>
<table id='result_table'>
<colgroup>
<col align='left' />
<col align='right' />
<col align='right' />
<col align='right' />
<col align='right' />
<col align='right' />
</colgroup>
<tr id='header_row'>
<td>Test Group/Test case</td>
<td>Count</td>
<td>Pass</td>
<td>Fail</td>
<td>Error</td>
<td>View</td>
</tr>
%(test_list)s
<tr id='total_row'>
<td>Total</td>
<td>%(count)s</td>
<td>%(Pass)s</td>
<td>%(fail)s</td>
<td>%(error)s</td>
<td> </td>
</tr>
</table>
""" # variables: (test_list, count, Pass, fail, error)
REPORT_CLASS_TMPL = r"""
<tr class='%(style)s'>
<td>%(desc)s</td>
<td>%(count)s</td>
<td>%(Pass)s</td>
<td>%(fail)s</td>
<td>%(error)s</td>
<td>Detail</td>
</tr>
""" # variables: (style, desc, count, Pass, fail, error, cid)
REPORT_TEST_WITH_OUTPUT_TMPL = r"""
<tr id='%(tid)s' class='%(Class)s'>
<td class='%(style)s'><div class='testcase'>%(desc)s</div></td>
<td colspan='5' align='center'>
<!--css div popup start-->
<a class="popup_link" onfocus='this.blur();' href="javascript:showTestDetail('div_%(tid)s')" >
%(status)s</a>
<div id='div_%(tid)s' class="popup_window">
<div style='text-align: right; color:red;cursor:pointer'>
<a onfocus='this.blur();' onclick="document.getElementById('div_%(tid)s').style.display = 'none' " >
[x]</a>
</div>
<pre>
%(script)s
</pre>
</div>
<!--css div popup end-->
</td>
</tr>
""" # variables: (tid, Class, style, desc, status)
REPORT_TEST_NO_OUTPUT_TMPL = r"""
<tr id='%(tid)s' class='%(Class)s'>
<td class='%(style)s'><div class='testcase'>%(desc)s</div></td>
<td colspan='5' align='center'>%(status)s</td>
</tr>
""" # variables: (tid, Class, style, desc, status)
REPORT_TEST_OUTPUT_TMPL = r"""
%(id)s: %(output)s
""" # variables: (id, output)
# ------------------------------------------------------------------------
# ENDING
#
ENDING_TMPL = """<div id='ending'> </div>"""
# -------------------- The end of the Template class -------------------
TestResult = unittest.TestResult
class _TestResult(TestResult):
# note: _TestResult is a pure representation of results.
# It lacks the output and reporting ability compares to unittest._TextTestResult.
def __init__(self, verbosity=1):
TestResult.__init__(self)
self.stdout0 = None
self.stderr0 = None
self.success_count = 0
self.failure_count = 0
self.error_count = 0
self.verbosity = verbosity
# result is a list of result in 4 tuple
# (
# result code (0: success; 1: fail; 2: error),
# TestCase object,
# Test output (byte string),
# stack trace,
# )
self.result = []
def startTest(self, test):
TestResult.startTest(self, test)
# just one buffer for both stdout and stderr
self.outputBuffer = StringIO.StringIO()
stdout_redirector.fp = self.outputBuffer
stderr_redirector.fp = self.outputBuffer
self.stdout0 = sys.stdout
self.stderr0 = sys.stderr
sys.stdout = stdout_redirector
sys.stderr = stderr_redirector
def complete_output(self):
"""
Disconnect output redirection and return buffer.
Safe to call multiple times.
"""
if self.stdout0:
sys.stdout = self.stdout0
sys.stderr = self.stderr0
self.stdout0 = None
self.stderr0 = None
return self.outputBuffer.getvalue()
def stopTest(self, test):
# Usually one of addSuccess, addError or addFailure would have been called.
# But there are some path in unittest that would bypass this.
# We must disconnect stdout in stopTest(), which is guaranteed to be called.
self.complete_output()
def addSuccess(self, test):
self.success_count += 1
TestResult.addSuccess(self, test)
output = self.complete_output()
self.result.append((0, test, output, ''))
if self.verbosity > 1:
sys.stderr.write('ok ')
sys.stderr.write(str(test))
sys.stderr.write('\n')
else:
sys.stderr.write('.')
def addError(self, test, err):
self.error_count += 1
TestResult.addError(self, test, err)
_, _exc_str = self.errors[-1]
output = self.complete_output()
self.result.append((2, test, output, _exc_str))
if self.verbosity > 1:
sys.stderr.write('E ')
sys.stderr.write(str(test))
sys.stderr.write('\n')
else:
sys.stderr.write('E')
def addFailure(self, test, err):
self.failure_count += 1
TestResult.addFailure(self, test, err)
_, _exc_str = self.failures[-1]
output = self.complete_output()
self.result.append((1, test, output, _exc_str))
if self.verbosity > 1:
sys.stderr.write('F ')
sys.stderr.write(str(test))
sys.stderr.write('\n')
else:
sys.stderr.write('F')
class HTMLTestRunner(Template_mixin):
"""
"""
def __init__(self, stream=sys.stdout, verbosity=1, title=None, description=None):
self.stream = stream
self.verbosity = verbosity
if title is None:
self.title = self.DEFAULT_TITLE
else:
self.title = title
if description is None:
self.description = self.DEFAULT_DESCRIPTION
else:
self.description = description
self.startTime = datetime.datetime.now()
def run(self, test):
"Run the given test case or test suite."
result = _TestResult(self.verbosity)
test(result)
self.stopTime = datetime.datetime.now()
self.generateReport(test, result)
print >>sys.stderr, '\nTime Elapsed: %s' % (self.stopTime-self.startTime)
return result
def sortResult(self, result_list):
# unittest does not seems to run in any particular order.
# Here at least we want to group them together by class.
rmap = {}
classes = []
for n,t,o,e in result_list:
cls = t.__class__
if not rmap.has_key(cls):
rmap[cls] = []
classes.append(cls)
rmap[cls].append((n,t,o,e))
r = [(cls, rmap[cls]) for cls in classes]
return r
def getReportAttributes(self, result):
"""
Return report attributes as a list of (name, value).
Override this to add custom attributes.
"""
startTime = str(self.startTime)[:19]
duration = str(self.stopTime - self.startTime)
status = []
if result.success_count: status.append('Pass %s' % result.success_count)
if result.failure_count: status.append('Failure %s' % result.failure_count)
if result.error_count: status.append('Error %s' % result.error_count )
if status:
status = ' '.join(status)
else:
status = 'none'
return [
('Start Time', startTime),
('Duration', duration),
('Status', status),
]
def generateReport(self, test, result):
report_attrs = self.getReportAttributes(result)
generator = 'HTMLTestRunner %s' % __version__
stylesheet = self._generate_stylesheet()
heading = self._generate_heading(report_attrs)
report = self._generate_report(result)
ending = self._generate_ending()
output = self.HTML_TMPL % dict(
title = saxutils.escape(self.title),
generator = generator,
stylesheet = stylesheet,
heading = heading,
report = report,
ending = ending,
)
self.stream.write(output.encode('utf8'))
def _generate_stylesheet(self):
return self.STYLESHEET_TMPL
def _generate_heading(self, report_attrs):
a_lines = []
for name, value in report_attrs:
line = self.HEADING_ATTRIBUTE_TMPL % dict(
name = saxutils.escape(name),
value = saxutils.escape(value),
)
a_lines.append(line)
heading = self.HEADING_TMPL % dict(
title = saxutils.escape(self.title),
parameters = ''.join(a_lines),
description = saxutils.escape(self.description),
)
return heading
def _generate_report(self, result):
rows = []
sortedResult = self.sortResult(result.result)
for cid, (cls, cls_results) in enumerate(sortedResult):
# subtotal for a class
np = nf = ne = 0
for n,t,o,e in cls_results:
if n == 0: np += 1
elif n == 1: nf += 1
else: ne += 1
# format class description
if cls.__module__ == "__main__":
name = cls.__name__
else:
name = "%s.%s" % (cls.__module__, cls.__name__)
doc = cls.__doc__ and cls.__doc__.split("\n")[0] or ""
desc = doc and '%s: %s' % (name, doc) or name
row = self.REPORT_CLASS_TMPL % dict(
style = ne > 0 and 'errorClass' or nf > 0 and 'failClass' or 'passClass',
desc = desc,
count = np+nf+ne,
Pass = np,
fail = nf,
error = ne,
cid = 'c%s' % (cid+1),
)
rows.append(row)
for tid, (n,t,o,e) in enumerate(cls_results):
self._generate_report_test(rows, cid, tid, n, t, o, e)
report = self.REPORT_TMPL % dict(
test_list = ''.join(rows),
count = str(result.success_count+result.failure_count+result.error_count),
Pass = str(result.success_count),
fail = str(result.failure_count),
error = str(result.error_count),
)
return report
def _generate_report_test(self, rows, cid, tid, n, t, o, e):
# e.g. 'pt1.1', 'ft1.1', etc
has_output = bool(o or e)
tid = (n == 0 and 'p' or 'f') + 't%s.%s' % (cid+1,tid+1)
name = t.id().split('.')[-1]
doc = t.shortDescription() or ""
desc = doc and ('%s: %s' % (name, doc)) or name
tmpl = has_output and self.REPORT_TEST_WITH_OUTPUT_TMPL or self.REPORT_TEST_NO_OUTPUT_TMPL
# o and e should be byte string because they are collected from stdout and stderr?
if isinstance(o,str):
# TODO: some problem with 'string_escape': it escape \n and mess up formating
# uo = unicode(o.encode('string_escape'))
uo = o.decode('latin-1')
else:
uo = o
if isinstance(e,str):
# TODO: some problem with 'string_escape': it escape \n and mess up formating
# ue = unicode(e.encode('string_escape'))
ue = e.decode('latin-1')
else:
ue = e
script = self.REPORT_TEST_OUTPUT_TMPL % dict(
id = tid,
output = saxutils.escape(uo+ue),
)
row = tmpl % dict(
tid = tid,
Class = (n == 0 and 'hiddenRow' or 'none'),
style = n == 2 and 'errorCase' or (n == 1 and 'failCase' or 'none'),
desc = desc,
script = script,
status = self.STATUS[n],
)
rows.append(row)
if not has_output:
return
def _generate_ending(self):
return self.ENDING_TMPL
##############################################################################
# Facilities for running tests from the command line
##############################################################################
# Note: Reuse unittest.TestProgram to launch test. In the future we may
# build our own launcher to support more specific command line
# parameters like test title, CSS, etc.
class TestProgram(unittest.TestProgram):
"""
A variation of the unittest.TestProgram. Please refer to the base
class for command line parameters.
"""
def runTests(self):
# Pick HTMLTestRunner as the default test runner.
# base class's testRunner parameter is not useful because it means
# we have to instantiate HTMLTestRunner before we know self.verbosity.
if self.testRunner is None:
self.testRunner = HTMLTestRunner(verbosity=self.verbosity)
unittest.TestProgram.runTests(self)
main = TestProgram
##############################################################################
# Executing this module from the command line
##############################################################################
if __name__ == "__main__":
main(module=None)
at last i add a line in _TestResult() function,and the code is below
class _TestResult(TestResult):
# note: _TestResult is a pure representation of results.
# It lacks the output and reporting ability compares to unittest._TextTestResult.
def __init__(self, verbosity=1):
TestResult.__init__(self)
self.stdout0 = None
self.stderr0 = None
self.success_count = 0
self.failure_count = 0
self.error_count = 0
self.verbosity = verbosity
# result is a list of result in 4 tuple
# (
# result code (0: success; 1: fail; 2: error),
# TestCase object,
# Test output (byte string),
# stack trace,
# )
self.result = []
self.outputBuffer = StringIO.StringIO() #this the added code!!!
and my program occur error because another place the code is wrong ,i fixed it !
so it works add the code!
trying to create several web pages that contains tables from the read csv file and I tried to define a function to create html web pages rather than writing the same codes many times.
read my csv file:
infile = open("new.csv", "r")
data = []
for line in infile:
cols = line.split(",")
Oposition = cols[0]
Winner = cols[1]
Margin = cols[2]
Ground = cols[3]
Year = cols[4]
pair = (Oposition, Winner, Margin, Ground, Year)
data.append(pair)
infile.close()
so far my codes are:
page = """<!DOCTYPE html>
<html>
<head>
<title>abc</title>
<style>
h1 {
text-align: center;
}
body {
background-image: url("2014.png");
background-repeat: no-repeat;
background-position: right top;
background-attachment: fixed;
}
</style>
</head>
<body>
<h1>{{heading}}</h1>
{{paragraph}}
<p>Back to main page</p>
<table border="1"><tr><th>Oposition</th><th>Winner</th><th>Margin</th><th>Ground</th><th>Year</th></tr>
"""
out1=page.format(heading = "2012 Stats", paragraph = "<p>aaaaaaa</p>")
out2 = page.format(heading = "2013 Stats", paragraph = "<p>bbbbb</P>")
out3 = page.format(heading = "2014 Stats", paragraph = "<p>cccc</P>")
out4 = page.format(heading = "2015 Stats", paragraph = "<p>ddddCSK</p>")
def write_html_file(filename, body):
out = open(filename, "w")
out.write(body)
write_html_file("2012.html",out1)
write_html_file("2013.html",out2)
write_html_file("2014.html",out3)
write_html_file("2015.html",out4)
for r in data:
if ''.join(r[4].split()) == "2012":
Oposition = r[0]
Winner = r[1]
Margin = r[2]
Ground=r[3]
Year = r[4]
out1.write("<tr> <td>" + Oposition+ '</td><td> '+ Winner+'</td><td> '+Margin+'</td><td> '+Ground+' </td><td>'+ Year+ " </td></tr>")
elif ''.join(r[4].split()) == "2013":
Oposition = r[0]
Winner = r[1]
Margin = r[2]
Ground=r[3]
Year = r[4]
out2.write("<tr> <td>" + Oposition+ '</td><td> '+ Winner+'</td><td> '+Margin+'</td><td> '+Ground+' </td><td>'+ Year+ " </td></tr>")
elif ''.join(r[4].split()) == "2014":
Oposition = r[0]
Winner = r[1]
Margin = r[2]
Ground=r[3]
Year = r[4]
out3.write("<tr> <td>" + Oposition+ '</td><td> '+ Winner+'</td><td> '+Margin+'</td><td> '+Ground+' </td><td>'+ Year+ " </td></tr>")
elif ''.join(r[4].split()) == "2015":
Oposition = r[0]
Winner = r[1]
Margin = r[2]
Ground=r[3]
Year = r[4]
out4.write("<tr> <td>" + Oposition+ '</td><td> '+ Winner+'</td><td> '+Margin+'</td><td> '+Ground+' </td><td>'+ Year+ " </td></tr>")
def output(a):
a.write("</table> </body>\n")
a.write("</html>\n")
a.close()
output(out1)
output(out2)
output(out3)
output(out4)
im trying to make tables according to years 2012, 2013, 2014, 2015 and make html pages that contains each of them. just cant figure out.
Any help or other option? Much appreciated
I get an error message saying:
---> 25 page1 = page.format(heading = "2012 Stats", paragraph = "<p>aaaa</p>")
KeyError: '\n text-align'
Short Answer
Python's built-in string format syntax is a variable enclosed by single paramthesis. That's why '\n text-align' is regarded as a key whereas it was intended to be a css style.
Solution
You can go ahead to escape your css snippets but I would not recommend it, because the html text will not be readable and will be difficult to maintain.
Hence, please use a template engine to help. There are many template engines: Jinja2, Mako.. etc. Since I am more familiar with the first one, let me show you how to get page1 working::
from jinja2 import Environment
env = Environment()
page_template = env.from_string(page)
page1 = page_template(heading="2012 Stats", paragraph="<p>aaaaaaa</p>")
And you will need to install jinja2:
$ pip install jinja2
Alternative solution
You can use my library pyexcel and pyexcel-text to get a html table rendered for you. The sample code is:
import pyexcel as p
sheet = p.get_sheet(file_name='new.csv')
sheet.colnames = ['Oposition', 'Winner', 'Margin', 'Ground', 'Year']
sheet.name = "2012 Stats"
print(sheet.html)
To run above code, you need to install these two additional packages:
$ pip install pyexcel pyexcel-text
When I look at my MainWindow in Qt Designer, I see this
However, when I compile ui file into python code, take the match object (a QGroupBox with "Champion" as the title, inside match history), and port it over so that I can build many of these things and add them all to the scroll area (Match History) and run it I get this
The group box ends shortly after the bottom of the window, so it doesn't go on forever, and I have confirmed in my code that the width and height of the group box is set correctly. I've also confirmed that the match object does indeed have 10 slots and has the items in it after being built, the problem is just that it doesn't look right at runtime. What's going wrong?
Here is the buildMatch method:
def buildMatch(self, summonerId, matchIndex, matchId, matchWidth, matchHeight):
# This method takes the matchIndex and matchId as an input, builds a match object, and returns it. As a part of
# building each match object, this method calls calculateMatchStatistics() and calculateAverages. It might be
# prudent later to only call self.calculateAverages() once, rather than every time, but I'm not sure.
# Globals: none
# Check whether we have match data for the matchID in question. If we do,
# continue. If not, call getMatchDetails for the match and store that data in matchHistoryDetails.
# Keys of the matchHistoryDetails dictionary will be unicode strings. Convert the matchId to unicode
# before using as a key or lookup element.
matchId = unicode(matchId)
knownMatchIds = self.matchHistoryDetails.keys()
if matchId not in knownMatchIds:
self.matchHistoryDetails[matchId] = self.getMatchDetails(summonerId, matchId)
# Load champion name from getChampionName() and lane from matchHistoryList
championId = self.matchHistoryList["matches"][matchIndex]["champion"]
championName = self.getChampionName(championId)
match = QGroupBox(championName)
match.setFixedHeight(matchWidth)
match.setFixedWidth(matchHeight)
matchWidget = QWidget(match)
matchWidget.setGeometry(QRect(10, 20, matchWidth, matchHeight))
matchLayout = QGridLayout(matchWidget)
statisticsBoxToMatchWidthRatio = .165
statisticsBoxToMatchHeightRatio = .3895
statisticsBoxWidth = int(matchWidth * statisticsBoxToMatchWidthRatio)
statisticsBoxHeight = int(matchHeight * statisticsBoxToMatchHeightRatio)
scoreBox = QGroupBox(matchWidget)
scoreBox.setAlignment(Qt.AlignCenter)
scoreBox.setTitle("score")
scoreBox.setStyleSheet('QGroupBox {font: 8pt "Calibri"}')
scoreBox.setToolTip("Score, in the format of kills-deaths-assists")
scoreValue = QLabel(scoreBox)
scoreValue.setGeometry(QRect(10, 29, statisticsBoxWidth, statisticsBoxHeight))
scoreValue.setAlignment(Qt.AlignCenter)
scoreValue.setStyleSheet('font: 9pt "Calibri";')
kdaBox = QGroupBox(matchWidget)
kdaBox.setAlignment(Qt.AlignCenter)
kdaBox.setTitle("KDA")
kdaBox.setStyleSheet('QGroupBox {font: 8pt "Calibri"}')
kdaBox.setToolTip("Calculated by (kills+deaths)/assists")
kdaValue = QLabel(kdaBox)
kdaValue.setGeometry(QRect(10, 29, statisticsBoxWidth, statisticsBoxHeight))
kdaValue.setAlignment(Qt.AlignCenter)
killParticipationPercentBox = QGroupBox(matchWidget)
killParticipationPercentBox.setAlignment(Qt.AlignCenter)
killParticipationPercentBox.setTitle("Kill part. %")
killParticipationPercentBox.setStyleSheet('QGroupBox {font: 8pt "Calibri"}')
killParticipationPercentBox.setToolTip("The percentage of your teams kills you contributed to")
killParticipationPercentValue = QLabel(killParticipationPercentBox)
killParticipationPercentValue.setGeometry(QRect(10, 29, statisticsBoxWidth, statisticsBoxHeight))
killParticipationPercentValue.setAlignment(Qt.AlignCenter)
goldPerMinBox = QGroupBox(matchWidget)
goldPerMinBox.setAlignment(Qt.AlignCenter)
goldPerMinBox.setTitle("gold/min")
goldPerMinBox.setStyleSheet('QGroupBox {font: 8pt "Calibri"}')
goldPerMinBox.setToolTip("Gold earned per minute")
goldPerMinValue = QLabel(goldPerMinBox)
goldPerMinValue.setGeometry(QRect(11, 29, statisticsBoxWidth, statisticsBoxHeight))
goldPerMinValue.setAlignment(Qt.AlignCenter)
wardScoreBox = QGroupBox(matchWidget)
wardScoreBox.setAlignment(Qt.AlignCenter)
wardScoreBox.setTitle("ward score")
wardScoreBox.setStyleSheet('QGroupBox {font: 8pt "Calibri"}')
wardScoreBox.setToolTip("Calculated by wards placed + wards killed")
wardScoreValue = QLabel(wardScoreBox)
wardScoreValue.setGeometry(QRect(10, 30, statisticsBoxWidth, statisticsBoxHeight))
wardScoreValue.setAlignment(Qt.AlignCenter)
csPerMinBox = QGroupBox(matchWidget)
csPerMinBox.setAlignment(Qt.AlignCenter)
csPerMinBox.setTitle("cs/min")
csPerMinBox.setStyleSheet('QGroupBox {font: 8pt "Calibri"}')
csPerMinBox.setToolTip("Creeps killed per minute")
csPerMinValue = QLabel(csPerMinBox)
csPerMinValue.setGeometry(QRect(10, 29, statisticsBoxWidth, statisticsBoxHeight))
csPerMinValue.setAlignment(Qt.AlignCenter)
spacerItem2 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
laneLabel = QLabel(matchWidget)
laneLabel.setAlignment(Qt.AlignCenter)
laneLabel.setStyleSheet('font: 10pt "Calibri";')
laneLabel.setToolTip("Lane")
spacerItem3 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
resultLabel = QLabel(matchWidget)
resultLabel.setAlignment(Qt.AlignCenter)
resultLabel.setStyleSheet('font: 12pt "Calibri"')
resultLabel.setToolTip("Match result")
matchLayout.addItem(spacerItem2, 0, 1, 1, 1)
matchLayout.addWidget(scoreBox, 0, 2, 1, 1)
matchLayout.addWidget(killParticipationPercentBox, 0, 3, 1, 1)
matchLayout.addWidget(wardScoreBox, 0, 4, 1, 1)
matchLayout.addItem(spacerItem3, 0, 5, 1, 1)
matchLayout.addWidget(resultLabel, 0, 6, 1, 1)
matchLayout.addWidget(laneLabel, 1, 0, 1, 1)
matchLayout.addWidget(kdaBox, 1, 2, 1, 1)
matchLayout.addWidget(goldPerMinBox, 1, 3, 1, 1)
matchLayout.addWidget(csPerMinBox, 1, 4, 1, 1)
matchLayout.setColumnStretch(0, 10)
matchLayout.setColumnStretch(1, 3)
matchLayout.setColumnStretch(2, 11)
matchLayout.setColumnStretch(3, 10)
matchLayout.setColumnStretch(4, 10)
matchLayout.setColumnStretch(5, 3)
matchLayout.setColumnStretch(6, 10)
matchLayout.setRowStretch(0, 10)
matchLayout.setRowStretch(1, 10)
##################################################
# Set values for each item
matchWon = self.matchHistoryStatistics["matches"][matchId]["won"]
if matchWon:
result = "Win"
else:
result = "Loss"
score = self.matchHistoryStatistics["matches"][matchId]["score"]
kda = self.matchHistoryStatistics["matches"][matchId]["kda"]
kdaAverage = self.matchHistoryStatistics["kdaAverage"]
killParticipationPercent = self.matchHistoryStatistics["matches"][matchId]["killParticipationPercent"]
killParticipationPercentAverage = self.matchHistoryStatistics["killParticipationPercentAverage"]
wardScore = self.matchHistoryStatistics["matches"][matchId]["wardScore"]
wardScoreAverage = self.matchHistoryStatistics["wardScoreAverage"]
goldPerMin = self.matchHistoryStatistics["matches"][matchId]["goldPerMin"]
goldPerMinAverage = self.matchHistoryStatistics["goldPerMinAverage"]
csPerMin = self.matchHistoryStatistics["matches"][matchId]["csPerMin"]
csPerMinAverage = self.matchHistoryStatistics["csPerMinAverage"]
lane = self.matchHistoryList["matches"][matchIndex]["lane"].lower().capitalize()
if lane == "Bottom":
lane = "Bot"
resultLabel.setText(result)
scoreValue.setText(str(score))
kdaValue.setText(str(kda))
killParticipationPercentValue.setText(str(killParticipationPercent))
wardScoreValue.setText(str(wardScore))
goldPerMinValue.setText(str(goldPerMin))
csPerMinValue.setText(str(csPerMin))
laneLabel.setText(lane)
if result == "Win":
resultLabel.setStyleSheet('color: green; font: 12pt "Calibri";')
else:
resultLabel.setStyleSheet('color: red; font: 12pt "Calibri";')
if kda > kdaAverage:
kdaValue.setStyleSheet('color: green; font: 9pt "Calibri";')
else:
kdaValue.setStyleSheet('color: red; font: 9pt "Calibri";')
if killParticipationPercent > killParticipationPercentAverage:
killParticipationPercentValue.setStyleSheet('color: green; font: 9pt "Calibri";')
else:
killParticipationPercentValue.setStyleSheet('color: red; font: 9pt "Calibri";')
if wardScore > wardScoreAverage:
wardScoreValue.setStyleSheet('color: green; font: 9pt "Calibri";')
else:
wardScoreValue.setStyleSheet('color: red; font: 9pt "Calibri";')
if goldPerMin > goldPerMinAverage:
goldPerMinValue.setStyleSheet('color: green; font: 9pt "Calibri";')
else:
goldPerMinValue.setStyleSheet('color: red; font: 9pt "Calibri";')
if csPerMin > csPerMinAverage:
csPerMinValue.setStyleSheet('color: green; font: 9pt "Calibri";')
else:
csPerMinValue.setStyleSheet('color: red; font: 9pt "Calibri";')
return match