I have the following code where I construct HTML rows,now when key is present in dict1 I want to color the row and when key is present in dict2 another color?
how can I modify this code to color the rows?
for item in jiradb :
MailBody = MailBody + "<tr>"
MailBody = MailBody + "<td>" + str(icount) + "</td>"
print get_field(item, 'key')
key = item['key']
key_after_none_check = get_field(item,'key');
crashid_link = "https://company.com/data/browse/" + key;
key_present_in_anr_tombstone = False;
if ((key in dict1) and (dict1[key] !=0)):
key_present_in_anr_tombstone = True
#MailBody "" + str(get_field(item,'key ')) + ";
MailBody = MailBody + "<td>" + "" + str(key_after_none_check) + "" + "(" + "x" + str(dict1[key]) + ")" + "</td>"
if ((key in dict2) and (dict2[key] !=0)):
key_present_in_anr_tombstone = True
MailBody = MailBody + "<td>" + "" + str(key_after_none_check) + "" + "(" + "x" + str(dict2[key]) + ")" + "</td>"
if key_present_in_anr_tombstone == False:
MailBody = MailBody + "<td>" + "" + str(key_after_none_check) + "" + "</td>"
MailBody = MailBody + "<td style=\"width:100%\">" + get_field(item,'summary') + "</td>"
MailBody = MailBody + "<td style=\"width:100%\">" + get_field(item,'Resolution') + "</td>"
icount = icount + 1
MailBody = MailBody + "</tr>"
To solve your problem, try to fetch the values first, and use css styling to color the rows.
rows = []
for item in jiradb:
data = []
key = item['key']
dict1_value = dict1.get(key)
dict2_value = dict2.get(key)
key_after_none_check = get_field(item,'key')
crashid_link = "https://company.com/data/browse/{}".format(key)
row = '<td><span style="background-color:{};">{}(x{})</span></td>'
color = 'white' # default color
if dict1_value != None:
color = 'red';
data.append(row.format(color, crashid_link, key_after_none_check, dict1_value))
if dict2_value != None:
color = 'blue'
data.append(row.format(color, crashid_link, key_after_none_check, dict2_value))
if not dict1_value and not dict2_value:
data.append('<td>{}</td>'.format(crashid_link, key_after_none_check))
data.append('<td style="width:100%">{}</td>'.format(get_field(item, 'summary')))
data.append('<td style="width:100%">{}</td>'.format(get_field(item, 'Resolution')))
rows.append(data)
mail_rows = []
for count,row in enumerate(rows):
head = '<tr><td>{}</td></tr>'.format(count+1)
body = '\n'.join(row)
footer = '</tr>'
mail_rows.append('{}{}{}'.format(head,body,footer))
mail_body = ''.join(mail_rows)
CURRENT OUTPUT:-
Your code is quite a tangled mess. I'm not sure if I got it all right, but take a look at this version. I don't know where icount comes from, but you can get it from enumerate. I made a string to contain what I think is a template for your table rows. Then I took out all the repetitive logic in the if clauses. Collected the values, and then popped them into the template.
for icount, item in enumerate(jiradb) :
vars = []
MailBody = MailBody +
"""<tr><td>{0}</td>
<td>{2}(x{3})</td>
<td style='width:100%'>{4}</td>
<td style='width:100%'>{5}</td></tr>
"""
vars.append(icount+1)
key = item['key']
vars.append(key)
key_after_none_check = get_field(item,'key');
vars.append(key_after_none_check)
key_present_in_anr_tombstone = False;
if ((key in dict1) and (dict1[key] !=0)):
key_present_in_anr_tombstone = True
vars.append(dict1[key])
if ((key in dict2) and (dict2[key] !=0)):
key_present_in_anr_tombstone = True
vars.append(dict2[key])
if key_present_in_anr_tombstone == False:
vars.append(key_after_non_check)
vars.append(get_field(item, 'summary'))
vars.append(get_field(item, 'Resolution'))
MailBody.format(*vars)
Related
The File I'm editing
45940736:1330:0.266667:1602990684:10023084.555000
48545806:16000000:0.000000:9999999999:0.000000
1191125008:1185:37.408333:1602991293:10282893.310000
116776982:1811:0.637500:1602990076:10022476.137000
My Code
f = open("values", "r+")
lines = f.readlines()
for i in lines:
if str(IDS) in i:
spl = i.split(":")
asset_id = spl[0]
value = spl[1]
volume = spl[2]
updated = spl[3]
item_age = spl[4]
new_line = asset_id + ":" + "this is a test" + ":"+ volume + ":" + updated + ":" + item_age
old_line = i
print(new_line)
How would I replace the line while in the for loop instead of doing
lines[0] = new_line
ff = open('values', 'w')
ff.writelines(lines)
I can't do that because some files will have 2k values and I need to change all of them.
Use enumerate() so you get the index in the list, so you can replace the element.
for index, i in enumerate(lines):
if str(IDS) in i:
spl = i.split(":")
asset_id = spl[0]
value = spl[1]
volume = spl[2]
updated = spl[3]
item_age = spl[4]
new_line = asset_id + ":" + "this is a test" + ":"+ volume + ":" + updated + ":" + item_age
old_line = i
lines[index] = new_line
import pyodbc
cnxn =
enter code here pyodbc.connect(driver='{SQL Server}',
server='cdcbopex',
database='PMLData',
uid='pml_manisha',
pwd='*******')
class DBConnector:
enter code here def init(self, cnxn, cursor):
self.cnxn = cnxn
self.cursor = cursor
Insert Excel sheet values Into Tables
def insertValues(self, row, head):
insertStr = "('"
headStr = '('
for item in self.head:
item = str(item).replace("#", "").replace("(", "").replace(")", "").replace(" ", "").replace("-", "")
headStr = headStr + item + ","
headStr = headStr[:-1] + ")"
for item in row:
item = str(item).replace("\n", "").replace("'", "")
insertStr = insertStr + item + "','"
insertStr = insertStr[:-2] + ");"
queryStr = "INSERT INTO " + head + " " + headStr + " VALUES " + insertStr
self.cursor.execute(queryStr)
self.cursor.commit()
return queryStr
Creating Table in database
def newTable(self, cols, name):
queryStr = "CREATE TABLE " + name + "("
for col in cols:
col = str(col).replace("#", "").replace("(", "").replace(")", "").replace(" ", "").replace("-", "")
queryStr = queryStr + col + " varchar(150),"
queryStr = queryStr[:-1] + ");"
self.cursor.execute(queryStr)
self.cursor.commit()
return queryStr
I'm editing a PDF template with using pdftk
command = ("pdftk " + '"' +
template + '"' +
" fill_form " + '"' +
pathUser + user['mail'] + ".xfdf" + '"' +
" output " + '"' +
pathUser + user['mail'] + ".pdf" + '"' +
" need_appearances")
command = command.replace('/', '\\')
os.system(command)
First I'm writing my data in a .xfdf file
for key, value in user.items():
print(key, value)
fields.append(u"""<field name="%s"><value>%s</value></field>""" % (key, value))
tpl = u"""<?xml version="1.0" encoding="UTF-8"?>
<xfdf xmlns="http://ns.adobe.com/xfdf/" xml:space="preserve">
<fields>
%s
</fields>
</xfdf>""" % "\n".join(fields)
f = open(pathUser + user['mail'] + '.xfdf', 'wb')
f.write(tpl.encode("utf-8"))
f.close()
I fetch the template and as shown above, write the data from the xfdf to pdf but for some reason, only the ime gets written.
Templates get fetched using some basic conditional logic as shown below:
for item in user['predavanja']:
user[acthead + str(actn)] = item
actn += 1
for item in user['radionice']:
user[acthead + str(actn)] = item
actn += 1
for item in user['izlet']:
user[acthead + str(actn)] = item
actn += 1
print(actn)
templates = {}
templates['0'] = "Template/2019/certificate_2019.pdf"
templates['5'] = "Template/2019/certificate_2019_5.pdf"
templates['10'] = "Template/2019/certificate_2019_10.pdf"
templates['15'] = "Template/2019/certificate_2019_15.pdf"
templates['20'] = "Template/2019/certificate_2019_20.pdf"
templates['25'] = "Template/2019/certificate_2019_25.pdf"
templates['30'] = "Template/2019/certificate_2019_30.pdf"
templates['35'] = "Template/2019/certificate_2019_35.pdf"
templates['40'] = "Template/2019/certificate_2019_40.pdf"
templates['45'] = "Template/2019/certificate_2019_45.pdf"
templates['50'] = "Template/2019/certificate_2019_50.pdf"
I'm writing this data
user['id'] = data['recommendations'][0]['role_in_team']['user']['id']
user['ime'] = data['recommendations'][0]['role_in_team']['user']['first_name']
user['prezime'] = data['recommendations'][0]['role_in_team']['user']['last_name']
user['tim'] = data['recommendations'][0]['role_in_team']['team']['short_name']
user['mail'] = data['recommendations'][0]['role_in_team']['user']['estudent_email']
user['puno_ime'] = (data['recommendations'][0]['role_in_team']['user']['first_name'] + ' ' +
data['recommendations'][0]['role_in_team']['user']['last_name'])
user['predavanja'] = predavanja
user['radionice'] = radionice
user['izlet'] = izlet
One note. predavanja, radionice and izlet are lists.
I've tried printing tpl which shows all the data being properly added to the scheme.
Turns out the issue was the naming of the variables since they didn't match the field names in the acroform PDF. So the solution was to rename the variables in the code to match the field names.
I wrote a python's function to increment BT device BD_ADDR by any value but my function can only work up to xx:xx:xx:xx:FE:FF. For example, original BD_ADDR = AA:BB:CC:DD:EE:FF --> incremented by 1 BD_ADDR = AA:BB:CC:DD:EF:00. Also is there a shorter way to do this without all if statements? any suggestions will be appreciated.
Below is the script:
def ba_incr(mac,incr):
old_bytes = mac[12:].split(":")
if (old_bytes[0] != "00"):
if (old_bytes[0] != "01" and old_bytes[0] != "0F"):
old_hex = str(old_bytes[0] + old_bytes[1])
incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
new_bytes = str(incr_hex[:2]) + ":" + str(incr_hex[2:])
elif (old_bytes[0] == "0F" and old_bytes[1] == "FF") :
old_hex = str(old_bytes[0] + old_bytes[1])
incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
new_bytes = str(incr_hex[:2]) + ":" + str(incr_hex[2:])
else:
old_hex = str(old_bytes[0] + old_bytes[1])
incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
#print ("incremented hex",incr_hex)
new_bytes = "0" + str(incr_hex[:1]) + ":" + str(incr_hex[1:])
elif (old_bytes[0] == "00" and old_bytes[1] == "FF"):
old_hex = old_bytes[1]
#print ("old hex:",old_hex)
incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
#print ("incremented hex:",incr_hex)
new_bytes = "01" + ":" + str(incr_hex[1:])
elif (old_bytes[0] == "00" and old_bytes[1][:1] == "0") and old_bytes[1][1:] != "F":
old_hex = old_bytes[1]
#print ("old hex:",old_hex)
incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
#print ("incremented hex:",incr_hex)
new_bytes = old_bytes[0] + ":0" + str(incr_hex)
elif (old_bytes[0] == "00" and old_bytes[1] != "FF"):
old_hex = old_bytes[1]
#print ("old hex:",old_hex)
incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
#print ("incremented hex:",incr_hex)
new_bytes = old_bytes[0] + ":" + str(incr_hex)[:2]
print ("mac after:", mac[:12] + new_bytes.upper())
You can probably try something like this:
Remove the ':' from the mac address
Convert the mac address to integer
Increment the integer value
Convert the integer to hex string
Insert back the ':' at the appropriate positions
Sample code that worked for me (for simplicity I am incrementing by 1). You may need to modify it to handle corner cases.
s = 'AA:BB:CC:DD:EE:FF'
s = s.replace(':', '')
val = int(s, 16)
val = val + 1
incr_s = hex(val)
incr_s = incr_s[2:].upper()
incr_s = ':'.join(incr_s[i:i+2] for i in range(0, len(incr_s), 2))
print(s)
print(incr_s)
Output:
AABBCCDDEEFF
AA:BB:CC:DD:EF:00
wrote a simple program and would like to print the output to a text file. I'm trying the following at the very top of my script:
python SagicorPremiumCalculator2.py > textfile.txt
But this is giving me a syntax error in idle. How is my syntax incorrect?
python SagicorPremiumCalculator2.py > textfile.txt
python SagicorPremiumCalculator2.py > textfile.txt
import openpyxl, os, sys
wb = openpyxl.load_workbook('example.xlsx')
Millar_sheet = wb.get_sheet_by_name('Millar')
client = []
output = []
print(os.getcwd())
for rowOfCellObjects in Millar_sheet['A2':'AA13']:
for cellObj in rowOfCellObjects:
#if cellObj.value != None:
#print(cellObj.coordinate, cellObj.value)
client.append(cellObj.value)
#print(client[2]) #client name
print(client[0]) #policy number
print(client[9]) #license plate
#output.append(client[0]) #1
#output.append(client[9]) #2
if client[12] != "Not Applicable":
float(client[12])
print('S.I. = ' + '$' + str("%0.2f" % client[12]))
#output.append("%0.2f" % client[12]) #3
else:
print('S.I. ' + client[12])
print('Basic = ' + '$' + str("%0.2f" % client[13]))
#output.append("%0.2f" % client[13])#3
if client[14] != None:
print('Loading = ' + str(100*client[14]) + '%')
else:
print('No Loading')
val = client[13]
if client[14] == None:
val = client[15] #if there is no loading percentage, val becomes subtotal
else:
val += (val*client[14]) # a = a + b, adds 150 to 1000
print('Subtotal = ' + '$' + str("%0.2f" % val))#good
if client[16] != None:
ATD = val*client[16] #discount amount
print('ATD = ' + str(100*client[16]) + '%, -$' + str("%0.2f" % ATD))
val -= (val*client[16])
print('$' + str("%0.2f" % val))
if client[17] != None:
val -= (val*client[17])
SP = val*client[17] #Discount amount
print('SP = ' + str(100*client[17]) + '%, -$' + str("%0.2f" % SP))
print('$' + str("%0.2f" % val))
if client[18] != None:
val = (val+client[18])
PAB = client[18]
print('PAB = +$' + str(client[18]))
print('$' + str("%0.2f" % val))
if client[19] != None:
NCD = val*client[19]
val -= (val*client[19])#discount amount
print('NCD = ' + str(100*client[19]) +'%, -$' + str("%0.2f" % NCD))
print('$' + "%0.2f" % val)
if client[20] != None:
val = (val+client[20])
print('W/S = +$' + str(client[20]))
print('$' + "%0.2f" % val)
if client[21] != None:
val = (val+client[21])
print('LOU = $' + str(client[21]))
print('$' + "%0.2f" % val)
if val < 750: #Applies minimum premium if val is under 750
print("Minimum premium applied")
val = 750
print('Pre-tax Premium is ' + '$' + str("%0.2f" % val)) #good
if client[23] == 0: #Client over 65, not being charged tax
print('According to Sagicor speadsheet, client over 65')
else:
PreTax = val*0.06
val = (PreTax+val)
print('Premium Tax = +$' + str("%0.2f" % PreTax)) #good
print('$' + "%0.2f" % val)
if client[25] != None:
print('RS = +$' + str(client[25]))
val = (val+client[25])
print('Total = $' + str("%0.2f" % val))
#if val == client[26]:
#print('Sagicor\'s total agrees with calculated total - top')
#else:
#print('Premium does not agree - top')
else:
print('Roadside assistance NOT included')
print('Total = $' + str("%0.2f" % val))
#if val == client[26]:
#print('Sagicor\'s total agrees with calculated total - bottom')
#else:
#print('Premium does not agree - bottom')
client = []
output = []
print('--- END OF ROW ---')
If you want to write the output of your script in a file I see two options.
The first one is to handle the writing in the python script :
#!/usr/bin/python
#I am here assuming that you use a Unix-like system (i.e. Not Windows )
file = open('textfile.txt','w')
... some code ...
file.write(myData +'\n')
#Don't forget to close the file at the end of the script
file.close()
N.B: the 'w' option creates the file if it not exists, but it aslo delete previous version of the file. If you want to add lines at the end of an existing file, you should use 'a' instead.
The '\n' is just here to create a new line.
The other option is the following : Simple use print statament in your script
#My Script
... some code ...
print MyData
and then, run your script in a shell not in IDLE with the following command :
python SagicorPremiumCalculator2.py > textfile.txt
If you are running Windows, you should definitely use the first option (because I am not sure the bash-style commands works in cmd ).
I hope this helps !