❌

Normal view

There are new articles available, click to refresh the page.
Today β€” 21 November 2024Main stream

Reading#Eat the Frog: Ch-2

21 November 2024 at 12:00

In continuation from Chapter 1, Chapter 2 starts with how to approach the priority list. Because for a normal person[without any priority like me :-)] every task will be a priority. Unlike that, the author is suggesting an alternative.

It goes like this. Take a piece of paper or use a text editor and name that as β€œPriorities” and start writing all the tasks that comes to your mind which you wanted to do. Not necessarily in a day, week or month. Just random. For eg: Complete reading a book, finish the assignment, save a minimum amount, practice meditation etc., By the end of this activity, you will have an exhaustive list of task that you wish you could complete.

Next, take one more sheet of paper or open one more text editor and name this as monthly. In here, from the list that you created in β€œPriorities”, pick up those tasks which could be or has to be completed in the next month. From our example, we can choose β€œFinish an assignment” and add it to the β€œmonthly” list.

Now the monthly list will be comparatively less than the entire priorities and you have a clear idea of what needs to be done in next 30 days. From here, create one more list for β€œWeekly”. And do the same exercise of choosing the things that has to or could be completed in next 7 days. And start including them in the weekly list.

Hard part is now complete. From here, connect the things that was described in Chapter#1. Pick up the frog that is bigger to eat and add it to your daily list.

From a larger picture, the moment you knock off one task from daily it creates a ripple effect. That is, it knocks off a task from weekly, then monthly and from the entire priorities. You will accomplished by the end of first week. And if we do this on week 2 we will feel even more happier and accomplished.

This is all about Chapter-2. Once again, this is my understanding and nothing to do with authors narration.

See you again in Chapter-3! Thank you for reading!

Before yesterdayMain stream

Reading#Eat the Frog – Ch:1

19 November 2024 at 11:51

I always have the challenge of reading. Whether it is technical documentation, general documentation or anything. If I remember correctly, the last time I read something continuously was when I was in my school and college days. And that too nothing extraordinary but weekly magazines like Anandha Vikatan/Kumudham and very rarely newspapers. That got improved when I started my work and regularly read the news headlines from β€œThe Hindu”. That’s all the reading I have got in my entire life. I have this habit of purchasing the books and will think.. One day.. that One day will come and I will become a Pro Reader and I will read all the books. But that did not happened till date.

So I was pouring all these frustration in the β€œ#Kaniyam” IRC chat along with some more concerns like I have trouble planning things. I use to start with one and if I come across something else I will leave whatever I was doing and start doing the new item and it goes on and on. Then Srini from the Kaniyam IRC group suggested various ideas to give a try and one such idea is reading this book called β€œEat the Frog”.

I wouldn’t say the book has changed me completely overnight but the practice of reading a few pages continuously gives a sense of satisfaction. I am not saying I have read 20-30 pages continuously instead I planned to complete a chapter whenever i start.

The book as such has got things we often hear or see elsewhere but more importantly it is structured. When I say it is structured, it starts with the topic explanation on why the author has named the book as β€œEat the Frog”.

In our daily life if we think eating a frog is one of our primary task. How will one plan. Because eating a frog is not that easy. And that too if you have more than one frog how will one plan to do that. Here the author compares the frog to that of the tasks we have in a day. Not all tasks are difficult as eating a frog. So if we have frogs of different size and the task is to complete eating them all in a day. How will one approach. He will target finishing the bigger one then the next then the next and it goes on. By the time one completes the biggest he will get the confidence to go for the next smaller sized frog.

This analogy works the same way for our daily tasks. Rather than picking the easy ones and save the bulk or harder tasks for a later time, plan to finish the harder or most difficult task first which will help us move with the next difficult task with a lot more confidence.

This was primarily discussed on Chapter 1. After reading this I wanted to see if this approach works. I started implementing it immediately but listing the items it wanted to complete for that day. And in that I sorted those items based on the difficulty(in terms of time). I did not create an exhaustive list rather 4 tasks for that day and out of which 2 are time taking or difficult task.

End of the day I was able to complete the top 2 leaving the remaining 2. I still felt happy because i completed the top 2 which is harder. And moved the pending 2 to next day and kept the priority as top for those 2.

So far it is working and I will continue to write about the other chapters as I complete reading them.

β€œLet us all start get into the habit of reading and celebrate..happy reading”

Task#6-New version of integrating the Store Billing app to produce a well formatted pdf file using python

8 November 2024 at 15:00

I was so much into using the fpdf module that I almost gave up on this particular task. The challenge I faced is that, I can pass the entire content to the createpdf function but the formatting went completely off track. The other option i was thinking is that send lines one after the other to a text file and finally convert that text file to a pdf. But even that task looked out of my ability. I paused this for a few days and poured in all my frustration not just with this task but with all the other challenges in my IRC channel #kaniyam where I received awesome suggestions from Shrinivasan.T, again not just with the solution to this problem but in general about overcoming the challenges in reading.

Took a deep breath and started fresh and came across a resource where they implemented pdf creation using a different module called reportlab where there was a solution to insert the text to display into a python list and get the entries from the list using a loop and add it to the pdf construct. I was able to finally complete the first step using that module.

Here is the code block

import configparser
import psycopg2
import psycopg2.extras
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.lib import colors
config = configparser.ConfigParser()
config.read('config.ini')
hostname = config['ConnPostgres']['hostname']
database = config['ConnPostgres']['database']
port_id = config['ConnPostgres']['port_id']
pwd = config['ConnPostgres']['pwd']
username = config['ConnPostgres']['username']
bill=0
final_bill_txt = ''
textlines = []
def fetch_BillAmount(in_item,in_qty):
conn=None
cur=None
try:
conn = psycopg2.connect(
host = hostname,
dbname = database,
user = username,
password = pwd,
port=port_id
)
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
select_script = '''Select ItemCode, ItemName, ItemPrice from StoreItems where ItemCode= %s'''
cur.execute(select_script,(in_item,))
dict_items = dict()
dict_items = cur.fetchall()
for dictItem in dict_items:
bill_amount = in_qty * dictItem['itemprice']
return dictItem['itemname'],bill_amount
except Exception as error:
print(error)
finally:
if conn is not None:
conn.close()
if cur is not None:
cur.close()
def billing():
global bill,textlines
in_item = input('Enter the item code:')
in_qty = int(input('Enter the quantity:'))
item_name,calc_bill = fetch_BillAmount(in_item,in_qty)
bill = bill + calc_bill
print(f'The Bill amount for {in_qty} of {item_name} : ${calc_bill}')
textlines.append(f'The Bill amount for {in_qty} of {item_name} : ${calc_bill}')
def write2Pdf(lsTextline):
pdf = canvas.Canvas('Demo.pdf')
pdf.setFillColorRGB(0,0,255)
pdf.setFont("Courier-Bold",24)
pdf.drawCentredString(290,720,"Shoppers Mart")
pdf.line(30,710,550,710)
text = pdf.beginText(40,680)
text.setFont("Courier",18)
for line in lsTextline:
text.textLine(line)
pdf.drawText(text)
pdf.save()
print('Welcome to Shoppers Mart')
first_login = 'Y' #default initial condition
i=1 #default loop initial value
while i != 0:
if first_login != 'Y':
in_Opt = input('Do you wish to continue shopping?(Y/N)')
if first_login == 'Y' or in_Opt == 'Y':
billing()
first_login = 'N'
else:
print(f'Your total bill amount is ${bill}')
textlines.append(f'Your total bill amount is ${bill}')
print('Thank you for shopping!')
textlines.append('Thank you for shopping!')
write2Pdf(textlines)
break

Task#5- My next attempt to create a pdf file using python

8 November 2024 at 14:48
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.lib import colors
textlines = ['Sample text 1','Sample text 2','Sample text 3','Sample text 4']
pdf = canvas.Canvas('Demo.pdf')
text = pdf.beginText(40,680)
text.setFont("Courier",18)
for line in textlines:
text.textLine(line)
pdf.drawText(text)
pdf.save()
view raw pdfGenDemo.py hosted with ❀ by GitHub

Task#4- Secure the DB config using configParser

6 November 2024 at 10:50

The below program uses configparser module to secure the DB config or the connection parameters. In the earlier programs the DB connections were all exposed and kept in the same program. In this program, DB connection is saved under a different file named β€œconfig.ini” and the parameters were called with the help of β€œConfigParser”.

import configparser#Note: All lowercase
import psycopg2 #module to connect the postgreSQL DB
import psycopg2.extras #module to fetch the data from DB table in the form of Dictionaries
config = configparser.ConfigParser()#Note:the calling method is a camel case
config.read('config.ini')
in_Item2buy = input('Enter the itemcode required:')
in_ItemQty = int(input('Enter the quantity:'))
hostname = config['ConnPostgres']['hostname']
database = config['ConnPostgres']['database']
port_id = config['ConnPostgres']['port_id']
pwd = config['ConnPostgres']['pwd']
username = config['ConnPostgres']['username']
conn=None
cur=None
try:
conn = psycopg2.connect(
host = hostname,
dbname = database,
user = username,
password = pwd,
port=port_id
)
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
#cur = conn.cursor()
select_script = '''Select ItemCode, ItemName, ItemPrice from StoreItems where ItemCode= %s'''
cur.execute(select_script,(in_Item2buy,))
dict_items = dict()
dict_items = cur.fetchall()
for dictItem in dict_items:
#print(dictItem) #test print statement to verify the dict of items for the given input
bill_amount = in_ItemQty * dictItem['itemprice']
print('The bill amount for ',dictItem['itemname'],':$',bill_amount) # Print the price
#conn.commit() #not required for this program as we are not doing any DML
except Exception as error:
print(error)
finally:
if conn is not None:
conn.close()
if cur is not None:
cur.close()
view raw configparserDemo.py hosted with ❀ by GitHub

Task#3c: BillingApp with output in pdf file(not formatted properly)

30 October 2024 at 11:46

After many unsuccessful attempts, I was able to send the output from my previous code block to a pdf file. Definitely a huge learning in terms of how to properly import the necessary packages how to troubleshoot the error messages and find out the deprecated syntax and replace with the updated ones etc.,

here is the snapshot of the exceptions i received during the process of fixing

And here I am with a screenshot with no exception mentioned

My final code snippet below:

import psycopg2
import psycopg2.extras
from fpdf import FPDF
from fpdf.enums import XPos, YPos
def fetch_BillAmount(in_item,in_qty):
hostname = 'localhost'
database = 'deptstore'
port_id = 5432
pwd = 'admin@1234'
username = 'postgres'
conn=None
cur=None
try:
conn = psycopg2.connect(
host = hostname,
dbname = database,
user = username,
password = pwd,
port=port_id
)
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
#cur = conn.cursor()
select_script = '''Select ItemCode, ItemName, ItemPrice from StoreItems where ItemCode= %s'''
cur.execute(select_script,(in_item,))
dict_items = dict()
dict_items = cur.fetchall()
for dictItem in dict_items:
#print(dictItem) #test print statement to verify the dict of items for the given input
bill_amount = in_qty * dictItem['itemprice']
return dictItem['itemname'],bill_amount
except Exception as error:
print(error)
finally:
if conn is not None:
conn.close()
if cur is not None:
cur.close()
bill=0
final_bill_txt = ''
def billing():
global bill,final_bill_txt
in_item = input('Enter the item code:')
in_qty = int(input('Enter the quantity:'))
item_name,calc_bill = fetch_BillAmount(in_item,in_qty)
bill = bill + calc_bill
print(f'The Bill amount for {in_qty} of {item_name} : ${calc_bill}')
final_bill_txt = final_bill_txt + (f'The Bill amount for {in_qty} of {item_name} : ${calc_bill}\n')
def write2Pdf(in_text):
pdf = FPDF()
pdf.add_page()
pdf.set_font("helvetica", size = 15)
pdf.cell(200, 10, text = "Shoppers Mart",new_x=XPos.LEFT, new_y=YPos.NEXT, align = 'C')
pdf.cell(200, 10, text = final_bill_txt,new_x=XPos.LEFT, new_y=YPos.NEXT,align = 'L')
pdf.output("ShoppersReceipt.pdf")
print('Welcome to Shoppers Mart')
first_login = 'Y' #default initial condition
i=1 #default loop initial value
while i != 0:
if first_login != 'Y':
in_Opt = input('Do you wish to continue shopping?(Y/N)')
if first_login == 'Y' or in_Opt == 'Y':
billing()
first_login = 'N'
else:
print(f'Your total bill amount is ${bill}')
final_bill_txt = final_bill_txt + (f'\n\n\n\nYour total bill amount is ${bill}\n\n\n\n\n\n''Thank you for shopping!')
print(final_bill_txt)
write2Pdf(final_bill_txt)
#print('Thank you for shopping!')
break

PDF Output:

General: Failure to learn from mistakes!

30 October 2024 at 11:35

I have been working on a task where I need to collect input(eg: Item code) from user, query the database to fetch the price and then to calculate the bill amount and print the output. I was able to do this successfully. Then comes the next learning where it was asked to feed this output into a pdf file.

I thought it would be a simple task where we will be importing a package and use that to write the output into a pdf file. I was proved terribly wrong.

I found a link where it was asked to use FPDF as a package to import and use it in the code. When I tried to install on my linux machine i kept getting the below error:

As usual I did not get the signal to use my senses rather my IT mindset to start searching like β€œunable to install fpdf” πŸ™‚ I went link over link over link but ended up with the same error. It started from 4:45 am this morning and finally around 6 am I decided to learn from β€œmistakes”. My senses started to work, especially the eyes and the sense of seeing πŸ™‚

I carefully went through the exception, yet my IT brain started to override and asked me to just copy and paste the command from the link. This is classic πŸ™‚

It was mentioned something like this:

If you wish to install a non-Debian packaged Python application,
it may be easiest to use pipx install xyz, which will manage a
virtual environment for you. Make sure you have pipx installed.

Then I tried exactly the same command but this time my brain partially worked it seems so replaced xyz to fpdf:

Thank god. Computers aren’t meant to use abusive language. hehehehe πŸ™‚

Then I went back to the pavillion and started searching other links where they asked to install jinja2( i tried that too). And in the same error message, it was mentioned to consider virtual environment, why to leave that, yes I tried that too.

Somehow I got through installing the virtual environment. But after that, I do not know what to do or interpret the error details. So the failure streak continues

Finally…………………………….

My senses were awaken πŸ™‚ And the brain started to work as if I had an espresso shot πŸ™‚ This time i tried the below

Though it failed again. As I said, β€œI learnt from mistakes(error message)”. And this happened after that.

Moral of the story:

it was told by many people whom I have interacted so far that always β€œread through the error message. 99% it has got enough information to change and rerun the code or installation” But because of my inherited IT brain I have avoided that till today. But from today, I am planning to change…and β€œto learn from mistakes(errors)” always. πŸ™‚

Thanks for reading my funny story! πŸ™‚

Task#3b – Billing application from DB using loop

29 October 2024 at 11:29
import psycopg2
import psycopg2.extras
def fetch_BillAmount(in_item,in_qty):
hostname = 'localhost'
database = 'deptstore'
port_id = 5432
pwd = 'admin@1234'
username = 'postgres'
conn=None
cur=None
try:
conn = psycopg2.connect(
host = hostname,
dbname = database,
user = username,
password = pwd,
port=port_id
)
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
#cur = conn.cursor()
select_script = '''Select ItemCode, ItemName, ItemPrice from StoreItems where ItemCode= %s'''
cur.execute(select_script,(in_item,))
dict_items = dict()
dict_items = cur.fetchall()
for dictItem in dict_items:
#print(dictItem) #test print statement to verify the dict of items for the given input
bill_amount = in_qty * dictItem['itemprice']
return bill_amount
except Exception as error:
print(error)
finally:
if conn is not None:
conn.close()
if cur is not None:
cur.close()
bill=0
def billing():
global bill,itemized_bill
in_item = input('Enter the item code:')
in_qty = int(input('Enter the quantity:'))
calc_bill = fetch_BillAmount(in_item,in_qty)
bill = bill + calc_bill
print('Welcome to Shoppers Mart')
first_login = 'Y' #default initial condition
i=1 #default loop initial value
while i != 0:
if first_login != 'Y':
in_Opt = input('Do you wish to continue shopping?(Y/N)')
if first_login == 'Y' or in_Opt == 'Y':
billing()
first_login = 'N'
else:
print_txt = 'Your total Bill amount : ',bill
print('Your total Bill amount : ',bill)
print('Thank you for shopping!')
break

Task#3a – To retrieve the bill amount for a specific store item from database

29 October 2024 at 09:14

In this program, the user can get the input about what item is required from the store and how many quantities. Based on the input the dynamic query returns the price of the item selected and the bill amount is calculated and printed.

import psycopg2 #module to connect the postgreSQL DB
import psycopg2.extras #module to fetch the data from DB table in the form of Dictionaries
in_Item2buy = input('Enter the itemcode required:')
in_ItemQty = int(input('Enter the quantity:'))
hostname = 'localhost'
database = 'deptstore'
port_id = 5432
pwd = 'admin@1234'
username = 'postgres'
conn=None
cur=None
try:
conn = psycopg2.connect(
host = hostname,
dbname = database,
user = username,
password = pwd,
port=port_id
)
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
#cur = conn.cursor()
select_script = '''Select ItemCode, ItemName, ItemPrice from StoreItems where ItemCode= %s'''
cur.execute(select_script,(in_Item2buy,))
dict_items = dict()
dict_items = cur.fetchall()
for dictItem in dict_items:
#print(dictItem) #test print statement to verify the dict of items for the given input
bill_amount = in_ItemQty * dictItem['itemprice']
print('The bill amount for ',dictItem['itemname'],':$',bill_amount) # Print the price
#conn.commit() #not required for this program as we are not doing any DML
except Exception as error:
print(error)
finally:
if conn is not None:
conn.close()
if cur is not None:
cur.close()

Task#3- My first python program to connect and retrieve data from DB

25 October 2024 at 13:48
import psycopg2 #module to connect the postgreSQL DB
import psycopg2.extras #module to fetch the data from DB table in the form of Dictionaries
hostname = 'localhost'
database = 'deptstore'
port_id = 5432
pwd = 'admin@1234'
username = 'postgres'
conn=None
cur=None
try:
conn = psycopg2.connect(
host = hostname,
dbname = database,
user = username,
password = pwd,
port=port_id
)
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
#cur = conn.cursor()
select_script = '''Select ItemCode, ItemName, ItemPrice from StoreItems'''
cur.execute(select_script)
dict_items = dict()
dict_items = cur.fetchall()
for items in dict_items:
print(items)
#conn.commit() #not required for this program as we are not doing any DML
except Exception as error:
print(error)
finally:
if conn is not None:
conn.close()
if cur is not None:
cur.close()

Task#2a- A simple billing app to use the information stored in a csv file

24 October 2024 at 15:00
#simple billing app using csv read functionality
#PRE_REQUISITE: Place the file "StoreItems.csv" in the current Python folder or specify the complete file path
import csv
in_ItemCode = input('Enter the item code:')
in_ItemQty = int(input('Enter the quantity required: '))
with open('StoreItems.csv','r') as file1:
reader1 = csv.DictReader(file1)
for row in reader1:
if row['ItemCode']==in_ItemCode:
print('The bill amount for',row['ItemName'],'is:$',int(row['ItemPrice'])*in_ItemQty)
view raw billingAppCsv1.py hosted with ❀ by GitHub

Task#2: Billing application for a store

24 October 2024 at 14:57

create a project – billing application for a grocery store. define the items and prices as a dictionary.get item number and quantity as input.in w while loop, till the itemnumber = 0.for now on the billing application, define the prices as a dictionary. later, read the price data from a CSV file

''' Function to calculate the billing for the purchased item'''
def billing_app():
item_to_buy = int(input('Enter the itemcode[Rice-1011 Dhal-1012 Oil-1013 Spices-1014]: '))
if item_to_buy in dictStoreItems.keys():
qty_to_buy = float(input('Enter the quamtity: '))
print('The total bill amount for ',item_to_buy,': ',qty_to_buy*dictStoreItems[item_to_buy])
else:
print('Invalid Item Code')
dictStoreItems = {1011:15,1022:10,1033:5,1044:3,1055:2}
input('Enter the membership number: ')
first_time_login = 'Y' #used to identify the first time a shopper logging in
i=1 #looping criteria
in_Opt='Y' #defaulting the option to Y for the first time shopping
while i != 0:
if first_time_login != 'Y':
in_Opt = input('Do you wish to continue shopping?(Y/N)')
if in_Opt == 'Y' or first_time_login == 'Y':
billing_app()
first_time_login = 'N'
else:
print('Thank you for shopping!')
break
view raw billing_app.py hosted with ❀ by GitHub
#nested dictionaries
Bill_Total = 0
def billing_app():
item_to_buy = int(input('Enter the itemcode[Rice-1011 Dhal-1012 Oil-1013 Spices-1014]: '))
if item_to_buy in dictStoreItems.keys():
qty_to_buy = float(input('Enter the quamtity: '))
print('The Bill amount for ',dictStoreItems[item_to_buy]['Name'],': $',dictStoreItems[item_to_buy]['UnitPrice']*qty_to_buy)
global Bill_Total
Bill_Total = Bill_Total + dictStoreItems[item_to_buy]['UnitPrice']*qty_to_buy
else:
print('Invalid Item Code')
#below is the nested dictionary containing Product code, name and unit price
dictStoreItems = {1011:{'Name':'Rice','UnitPrice':15},1012:{'Name':'Dhal','UnitPrice':10},1013:{'Name':'Oil','UnitPrice':5},1014:{'Name':'Salt','UnitPrice':3}}
input('Enter the membership number: ')#dummy input
print('****Welcome to Payilagam Shoppers Mart*****')#dummy output
first_time_login = 'Y' #default initial condition
i=1 #default loop initial value
while i != 0:
if first_time_login != 'Y':
in_Opt = input('Do you wish to continue shopping?(Y/N)')
if first_time_login == 'Y' or in_Opt == 'Y':
billing_app()
first_time_login = 'N'
else:
print('Your total Bill amount : ',Bill_Total)
print('Thank you for shopping!')
break

Task#1:Calculator module

21 October 2024 at 14:35

Basic calculator app code:

Alternate method by using function/method:

Code repo:

in_Option = input('Enter the option 1.Sum 2.Difference 3.Multiplcation 4.Division:')
in_Param1 = input('Enter the parameter 1:')
in_Param2 = input('Enter the parameter 2:')
def switch(in_Option):
if in_Option == '1':
print('You entered the option for Addition and the sum of the 2 inputs are: ',int(in_Param1)+int(in_Param2))
return
if in_Option == '2':
if in_Param1>in_Param2:
print('You entered the option for difference and the difference of the 2 inputs are: ',int(in_Param1)-int(in_Param2))
return
else:
print('You entered the option for difference and the difference of the 2 inputs are: ',int(in_Param2)-int(in_Param1))
return
if in_Option == '3':
print('You entered the option for Product and the Product of the 2 inputs are: ',int(in_Param1)*int(in_Param2))
return
if in_Option == '4':
print('You entered the option for Division and the Product of the 2 inputs are: ',int(in_Param1)/int(in_Param2))
return
else:
print('Invalid option selected')
return
switch(in_Option)
view raw calc_app_basic.py hosted with ❀ by GitHub
def calc_app(input, param1, param2):
if input == 1:
print('Sum=',param1+param2)
elif input ==2 and param1 > param2:
print('Difference=',param1-param2)
elif input == 2 and param2 > param1:
print('Difference=',param2 – param1)
elif input == 3:
print('Product=',param1*param2)
elif input ==4:
print('Division=',param1/param2)
in_Option = int(input('Enter the option[1-Add 2-Subtract 3-Multiply 4-Division]: '))
param1 = int(input('Enter the parameter 1:'))
param2 = int(input('Enter the parameter 2:'))
calc_app(in_Option,param1,param2)
view raw calc_app_function.py hosted with ❀ by GitHub

❌
❌