How to use a loop to create radiobuttons in Python - python

I have to create multiple radio buttons. Each has its own name and location on grid. There are also several variables involved.
I stored all the data to create these radio buttons in a tuple
(I know that FONTS does not cause a problem, its stored above this but isn't shown here):
self.unitType = IntVar()
self.matPropSel = IntVar()
self.secProfSel = IntVar()
self.endSupSel = IntVar()
self.loadTypeSel = IntVar()
self.RADIOLABELS = ( # Text, Font, Variable, Value, Row, Column
('English', self.FONTS[3], self.unitType, 1, 3, 1),
('metric', self.FONTS[3], self.unitType, 2, 4, 1),
('select preset', self.FONTS[3], self.matPropSel, 1, 6, 1),
('manual entry', self.FONTS[3], self.matPropSel, 2, 7, 1),
('select preset', self.FONTS[3], self.secProfSel, 1, 10, 1),
('manual entry', self.FONTS[3], self.secProfSel, 2, 11, 1),
('one end', self.FONTS[3], self.endSupSel, 1, 15, 1),
('both ends', self.FONTS[3], self.endSupSel, 2, 16, 1),
('point', self.FONTS[3], self.loadTypeSel, 1, 18, 1),
('uniform distribution', self.FONTS[3], self.loadTypeSel, 2, 19, 1),
('uniform variation', self.FONTS[3], self.loadTypeSel, 3, 20, 1)
)
So, how would I use a for loop to go through this tuple and generate a radio button from each line? Do all of the variables have to be the same? I am having problems with them.
Here is my attempt at a loop:
outerIndexer = 0
for labels in self.RADIOLABELS:
Radiobutton(self, text=self.RADIOLABELS[outerIndexer][0], font=self.RADIOLABELS[outerIndexer][1],
variable=self.RADIOLABELS[outerIndexer][2], value=self.RADIOLABELS[outerIndexer][3])\
.grid(row=self.RADIOLABELS[outerIndexer][4], column=self.RADIOLABELS[outerIndexer][5])
outerIndexer += 1

You can do it like this by looping through the RADIOLABELS. Note: it is also recommended to save the button to a list so it doesn't get lost.
self.RADIOLABELS = ( # Text, Font, Variable, Value, Row, Column
('English', self.FONTS[3], self.unitType, 1, 3, 1),
('metric', self.FONTS[3], self.unitType, 2, 4, 1),
('select preset', self.FONTS[3], self.matPropSel, 1, 6, 1),
('manual entry', self.FONTS[3], self.matPropSel, 2, 7, 1),
('select preset', self.FONTS[3], self.secProfSel, 1, 10, 1),
('manual entry', self.FONTS[3], self.secProfSel, 2, 11, 1),
('one end', self.FONTS[3], self.endSupSel, 1, 15, 1),
('both ends', self.FONTS[3], self.endSupSel, 2, 16, 1),
('point', self.FONTS[3], self.loadTypeSel, 1, 18, 1),
('uniform distribution', self.FONTS[3], self.loadTypeSel, 2, 19, 1),
('uniform variation', self.FONTS[3], self.loadTypeSel, 3, 20, 1)
)
radiobuttons = []
for _Text, _Font, _Variable, _Value, _Row, _Column in self.RADIOLABELS: # it will unpack the values during each iteration
_Radio = tk.Radiobutton(root, text = _Text, font = _Font, variable = _Variable, value = _Value)
# ^ root should be the frame/Tk you're trying to place it on, it will be self if this is a direct subclass of a Frame or Tk
# ^ or Radiobutton(.....) if you did from tkinter import *
_Radio.grid(row = _Row, column = _Column)
radiobuttons.append(_Radio)

Related

Split dataframe based on pandas groupby and generate multiple PDFs

There's a table containing a list of 3 employees and 3-4 courses they are supposed to take respectively. I want to create individual PDFs for every employee in this table. First PDF will have list of 3 courses to be taken by Emp1, 2nd PDF will have list of 3 courses to be taken by Emp2 and so on.
The below code is creating just 1 PDF and contains list of all courses for all employees together.
My idea is to initially split/ group the data based on EmpNo and then create individual PDF and to do this I need to create a For Loop for iterating. However, I am unable to figure this...
DataFrame Code
pip install fpdf #To generate PDF
import pandas as pd
data = {'EmpNo': ['123','123','123','456','456', '456','456','789','789','789'],
'First Name': ['John', 'John', 'John', 'Jane', 'Jane', 'Jane', 'Jane', 'Danny', 'Danny', 'Danny'],
'Last Name': ['Doe', 'Doe' ,'Doe', 'Doe' ,'Doe', 'Doe', 'Doe', 'Roberts', 'Roberts', 'Roberts'],
'Activity Code': ['HR-CONF-1', 'HR-Field-NH-ONB','COEATT-2021','HR-HBK-CA-1','HR-WD-EMP','HR-LIST-1','HS-Guide-3','HR-WD-EMP','HR-LIST-1','HS-Guide-3'],
'RegistrationDate': ['11/22/2021', '11/22/2021', '11/22/2021', '11/22/2021', '11/22/2021', '11/22/2021','11/22/2021', '11/22/2021', '11/22/2021','11/22/2021']}
df = pd.DataFrame(data = data, columns = ['EmpNo','First Name', 'Last Name', 'Activity Code', 'RegistrationDate'])
employees = data['EmpNo']
employees = data.drop_duplicates(subset=['EmpNo'])
print(df)
Input looks like this,
PDF Generation Code
from fpdf import FPDF
class PDF(FPDF):
def header(self):
# Arial bold 15
self.set_font('Helvetica', 'B', 15)
# Move to the right
self.cell(80)
# Title
self.cell(42, 2, 'Plan', 0, 0, 'C')
# Line break
self.ln(20)
# Page footer
def footer(self):
# Position at 1.5 cm from bottom
self.set_y(-15)
# Arial italic 8
self.set_font('Helvetica', 'I', 8)
# Page number
self.cell(0, 10, 'Page ' + str(self.page_no()) + '/{nb}', 0, 0, 'C')
# Footer image First is horizontal, second is vertical, third is size
for EmpNo in employees['EmpNo']:
print (EmpNo)
# Instantiation of inherited class
pdf = PDF()
pdf.alias_nb_pages()
pdf.add_page()
pdf.set_font('Helvetica', '', 11)
pdf.cell(80, 6, 'Employee ID: ' + str(data.loc[0]['EmpNo']), 0, 1, 'L')
pdf.ln(2.5)
pdf.multi_cell(160, 5, 'Dear ' + str(data.loc[0]['First Name']) + ' ' + str(data.loc[0]['Last Name']) + ', Please find below your Plan.', 0, 1, 'L')
pdf.cell(80, 6, '', 0, 1, 'C')
pdf.set_font('Helvetica', 'B', 13)
pdf.cell(80, 6, 'Name', 0, 0, 'L')
pdf.cell(40, 6, 'Date', 0, 0, 'L')
pdf.cell(40, 6, 'Link', 0, 1, 'L')
pdf.cell(80, 6, '', 0, 1, 'C')
pdf.set_font('Helvetica', '', 8)
for i in range (len(data)):
pdf.set_font('Helvetica', '', 8)
pdf.cell(80, 6, data.loc[0+i]['Activity Code'], 0, 0, 'L')
#pdf.cell(40, 6, data.loc[0+i]['Activity Link'], 0, 1, 'L')
pdf.cell(40, 6, data.loc[0+i]['RegistrationDate'], 0, 0, 'L')
pdf.set_font('Helvetica', 'U', 8)
pdf.cell(40, 6, 'Click Here', 0, 1, 'L', link = 'www.google.com')
pdf.set_font('Helvetica', 'B', 10)
pdf.cell(80, 6, '', 0, 1, 'C')
pdf.cell(80, 6, 'IF YOU REQUIRE ANY HELP, PLEASE CONTACT US', 0, 0, 'L')
pdf.output(str(data.loc[0]['First Name']) + ' ' + str(data.loc[0]['Last Name'])+ '.pdf', 'F')
Here's a snap of PDF generated.
I can split the data using below code, but I am stuck at how to call out individual splits and then further create multiple PDF
splits = list(data.groupby('EmpNo'))
Any help would be greatly appreciated. Thanks.
I would write the groupby like this:
for EmpNo, data in df.groupby("EmpNo"):
For each group, the groupby will return the variable it groups on, and the dataframe which matches that variable.
Next, I would extract the first row of that dataframe. This is to make it easier to get the name and similar attributes.
first_row = data.iloc[0]
(What's the difference between iloc and loc?)
Since we have the employee ID already, we can skip looking it up in the dataframe. For other attributes, we can look it up like first_row['First Name'].
pdf.cell(80, 6, 'Employee ID: ' + str(EmpNo), 0, 1, 'L')
# ...
pdf.multi_cell(160, 5, 'Dear ' + str(first_row['First Name']) + ' ' + str(first_row['Last Name']) + ', Please find below your Plan.', 0, 1, 'L')
Next, in this loop which loops over the subset, I would use .iterrows() to do the loop instead of using range() and .loc. This is easier and won't break if the index of your dataframe doesn't start with zero. (After grouping, the second group's index won't start with zero anymore.)
Here is the final source code after the changes:
import pandas as pd
data = {'EmpNo': ['123','123','123','456','456', '456','456','789','789','789'],
'First Name': ['John', 'John', 'John', 'Jane', 'Jane', 'Jane', 'Jane', 'Danny', 'Danny', 'Danny'],
'Last Name': ['Doe', 'Doe' ,'Doe', 'Doe' ,'Doe', 'Doe', 'Doe', 'Roberts', 'Roberts', 'Roberts'],
'Activity Code': ['HR-CONF-1', 'HR-Field-NH-ONB','COEATT-2021','HR-HBK-CA-1','HR-WD-EMP','HR-LIST-1','HS-Guide-3','HR-WD-EMP','HR-LIST-1','HS-Guide-3'],
'RegistrationDate': ['11/22/2021', '11/22/2021', '11/22/2021', '11/22/2021', '11/22/2021', '11/22/2021','11/22/2021', '11/22/2021', '11/22/2021','11/22/2021']}
df = pd.DataFrame(data = data, columns = ['EmpNo','First Name', 'Last Name', 'Activity Code', 'RegistrationDate'])
from fpdf import FPDF
class PDF(FPDF):
def header(self):
# Arial bold 15
self.set_font('Helvetica', 'B', 15)
# Move to the right
self.cell(80)
# Title
self.cell(42, 2, 'Plan', 0, 0, 'C')
# Line break
self.ln(20)
# Page footer
def footer(self):
# Position at 1.5 cm from bottom
self.set_y(-15)
# Arial italic 8
self.set_font('Helvetica', 'I', 8)
# Page number
self.cell(0, 10, 'Page ' + str(self.page_no()) + '/{nb}', 0, 0, 'C')
# Footer image First is horizontal, second is vertical, third is size
for EmpNo, data in df.groupby("EmpNo"):
# Get first row of grouped dataframe
first_row = data.iloc[0]
# Instantiation of inherited class
pdf = PDF()
pdf.alias_nb_pages()
pdf.add_page()
pdf.set_font('Helvetica', '', 11)
pdf.cell(80, 6, 'Employee ID: ' + str(EmpNo), 0, 1, 'L')
pdf.ln(2.5)
pdf.multi_cell(160, 5, 'Dear ' + str(first_row['First Name']) + ' ' + str(first_row['Last Name']) + ', Please find below your Plan.', 0, 1, 'L')
pdf.cell(80, 6, '', 0, 1, 'C')
pdf.set_font('Helvetica', 'B', 13)
pdf.cell(80, 6, 'Name', 0, 0, 'L')
pdf.cell(40, 6, 'Date', 0, 0, 'L')
pdf.cell(40, 6, 'Link', 0, 1, 'L')
pdf.cell(80, 6, '', 0, 1, 'C')
pdf.set_font('Helvetica', '', 8)
for _, row in data.iterrows():
pdf.set_font('Helvetica', '', 8)
pdf.cell(80, 6, row['Activity Code'], 0, 0, 'L')
#pdf.cell(40, 6, row['Activity Link'], 0, 1, 'L')
pdf.cell(40, 6, row['RegistrationDate'], 0, 0, 'L')
pdf.set_font('Helvetica', 'U', 8)
pdf.cell(40, 6, 'Click Here', 0, 1, 'L', link = 'www.google.com')
pdf.set_font('Helvetica', 'B', 10)
pdf.cell(80, 6, '', 0, 1, 'C')
pdf.cell(80, 6, 'IF YOU REQUIRE ANY HELP, PLEASE CONTACT US', 0, 0, 'L')
pdf.output(str(first_row['First Name']) + ' ' + str(first_row['Last Name'])+ '.pdf', 'F')
Tested, and it works.

How to obtain a value from inside a loop

I will be implementing multiprocessing so that the loops are occurring at the same time, but how can I make it so at the end of each iteration, I can obtain the value of westernEurope.cases and easternEurope.cases so that I can add them together
westernEurope = Region("Western Europe", 1000, 0, 0, 8, 4, 4, 0)
while westernEurope.deaths < westernEurope.population:
westernEurope.infection()
if westernEurope.cases > westernEurope.population:
westernEurope.cases = westernEurope.population
print("Infections:", westernEurope.cases)
westernEurope.death()
if westernEurope.deaths > westernEurope.population:
westernEurope.deaths = westernEurope.population
print("Deaths:", westernEurope.deaths)
#where i want to return the value of westernEurope.cases
time.sleep(0.1)
easternEurope = Region("Eastern Europe", 1000, 0, 0, 8, 4, 4, 0)
while easternEurope.deaths < easternEurope.population:
easternEurope.infection()
if easternEurope.cases > easternEurope.population:
easternEurope.cases = easternEurope.population
print("Infections:", easternEurope.cases)
easternEurope.death()
if easternEurope.deaths > easternEurope.population:
easternEurope.deaths = easternEurope.population
print("Deaths:", easternEurope.deaths)
# where i want to return the value of easternEurope.cases
time.sleep(0.1)
print(easternEurope.cases + westernEurope.cases)
IMHO there is no need for multiprocessing. With a generator, your problem can be solved in an even more elgant way.
# where i want to return the value of easternEurope.cases
yield region.cases
Full code:
def desease(region: Region):
while region.deaths < region.population:
region.infection()
if region.cases > region.population:
region.cases = region.population
print("Infections:", region.cases)
region.death()
if region.deaths > region.population:
region.deaths = region.population
print("Deaths:", region.deaths)
# where i want to return the value of easternEurope.cases
yield region.cases
time.sleep(0.1)
easternEurope = Region("Eastern Europe", 1000, 0, 0, 8, 4, 4, 0)
westernEurope = Region("Western Europe", 2000, 0, 0, 8, 4, 4, 0)
eastDesease = desease(easternEurope)
westDesease = desease(westernEurope)
for eastCases, westCases in zip(eastDesease, westDesease):
print(eastCases, westCases)

How to fix "AttributeError: type object has no attribute" in python?

I am adding some code to the preset code to check the time availability, which is if the meeting time can fit into the proposed time schedule. However, I keep getting the following error. Can anyone please give me some advices? Thanks so much for your time.
Preset codes:
from datetime import datetime
class Meeting:
def __init__(self, start_time, end_time):
self.start_time = start_time
self.end_time = end_time
My codes:
def check_availability(meetings, proposed_time):
meeting_start = Meeting.datetime.start_time.hour
meeting_end = Meeting.datetime.end_time.hour
ok_time = datetime.proposed_time.hour
if meeting_start < ok_time < meeting_end:
return True
else:
return False
meetings = [Meeting(datetime(2018, 8, 1, 9, 0, 0), datetime(2018, 8, 1, 11,
0, 0)), Meeting(datetime(2018, 8, 1, 15, 0, 0), datetime(2018, 8, 1, 16, 0,
0)), Meeting(datetime(2018, 8, 2, 9, 0, 0), datetime(2018, 8, 2, 10, 0, 0))]
print(check_availability(meetings, datetime(2018, 8, 1, 12, 0, 0)))
print(check_availability(meetings, datetime(2018, 8, 1, 10, 0, 0)))
Your code raises this exception:
AttributeError: type object 'Meeting' has no attribute 'datetime'
At this line:
meeting_start = Meeting.datetime.start_time.hour
Python is telling you that the Meeting class doesn't have an attribute named datetime. This is true: the Meeting class is a factory for making meeting objects (or instances), and these objects have start_time and end_time attributes, which are set by passing datetime instances to Meeting's __init__ method. These attributes can be accessed like this:
>>> meeting = Meeting(datetime(2018, 8, 1, 9, 0, 0), datetime(2018, 8, 1, 11,
0, 0))
>>> print(meeting.start_time)
2018-08-01 09:00:00
>>> print(meeting.end_time)
2018-08-01 11:00:00
Your check_availability function is being passed a list of meetings, so you need to loop over the list to check whether any of the meetings conflict with the proposed meeting time.
def check_availability(meetings, proposed_time):
# Loop over the list of meetings; "meeting"
# is the meeting that you are currently inspecting.
for meeting in meetings:
# if proposed_time is between meeting.start_time
# and meeting.end_time, return False
# If you get through the list without returning False
# then the proposed time must be ok, so return True.

Using json.Encoder in django

i have done following things
def handle_json(obj):
# i want to make sure control goes here
print(obj)
return obj
def test_json():
data= {datetime.date(2018, 12, 1): 160000.0,
datetime.date(2019, 2, 1): 240000.0,
datetime.date(2020, 9, 1): 1360000.0,
datetime.date(2019, 3, 1): 280000.0}
print(json.dumps(data, default=handle_json))
When i run test_json(), why i am not getting print() from handle_json() on console?

Passing multiple value_list in Django

I have this code in views.py:
def pins_info(request):
if request.method == "GET":
getpin = request.GET.get('pin', None)
m = ButuanMaps.objects.filter(clandpin=getpin).
values_list('landproperty__ctaxdec')
n = ButuanMaps.objects.filter(clandpin=getpin).
values_list('ssectionid__sbrgyid__cbrgyname')
return HttpResponse(json.dumps({'taxdec': list(m),'brgy': list(n)}),
content_type='application/json')
I works fine, but it is not that effective when I want to get other values. I can access the result in my template like this:
success: function(data) {
taxdec = data['taxdec'];
brgy = data['brgy'];
var inputform = $('#forminput').val();
if( inputform == "Select Land PIN") {
alert('Please Select Land PIN')
}
else{
$('#status').append(
"<p>Tax Declaration: " + taxdec + "<br/>Barangay: " + brgy + "</p>"
);
}
}
How can I simplify my code to make it more effective like:
m = ButuanMaps.objects.filter(clandpin=getpin).
values_list('landproperty__ctaxdec','ssectionid__sbrgyid__cbrgyname')
But how do I pass it to my template?
If we take your m and n queries as:
m = range(5)
n = range(6, 11)
Then your single query of m = ButuanMaps.objects.filter(clandpin=getpin). values_list('landproperty__ctaxdec','ssectionid__sbrgyid__cbrgyname') is equivalent to the structure of:
new = zip(m, n)
#[(0, 6), (1, 7), (2, 8), (3, 9), (4, 10)]
So you can "transpose" that:
zip(*new)
# [(0, 1, 2, 3, 4), (6, 7, 8, 9, 10)]
Then build a dict from that and your keys:
results = dict(zip(['taxdec', 'brgy'], zip(*new))))
# {'brgy': (6, 7, 8, 9, 10), 'taxdec': (0, 1, 2, 3, 4)}
Then json.dumps results.
Or use an OrderedDict for your JSON name and column names values and generalise further:
from collections import OrderedDict
keyvals = OrderedDict([
('taxdec','landproperty__ctaxdec'),
('brgy', 'ssectionid__sbrgyid__cbrgyname')
])
m = ButuanMaps.objects.filter(clandpin=getpin).values_list(*keyvals.values())
result = dict(zip(keyvals, zip(*m)))
That way, you can add/remove columns to be selected and their associated JSON values in one place for the same query.

Categories

Resources