Sunday, November 12, 2023

Automate Bingo game using Python

                

                         189 x 126                 86 x 87


https://www.blogger.com/blog/post/edit/preview/705067943936137407/8237077484565746551 is the link to creating Bingo cards. Here, we simulate the game play.


from tkinter import *

from random import shuffle


win = Tk()

win.config(bg="white")

win.title("B C R S  Children's Day B I N G O")


scrWidth = win.winfo_screenwidth()

scrHeight = win.winfo_screenheight()

winWidth, winHeight = 1200, 680

x = scrWidth//2 - winWidth//2

y = scrHeight//2 - winHeight//2 - 40

win.geometry("%dx%d+%d+%d" % (winWidth, winHeight, x, y))


ctr = 0

L = [i for i in range(1, 91)]

shuffle(L)


def Next():

  global ctr

  num = L[ctr]  # Next number to call

  txt1['state'] = NORMAL

  txt2['state'] = NORMAL


  if num < 10:

    lbl2.config(text=('  ' + str(num)))

  else:

    lbl2.config(text=(' ' + str(num)))


  if num < 10:

    txt1.insert(END, ' ' + str(num) + '   ')

  else:

    txt1.insert(END, str(num) + '  ')


  L1 = sorted(L[:ctr+1])

  txt2.delete("0.0", END)

  for i in range(len(L1)):

    if L1[i] < 10:

      txt2.insert(END, ' ' + str(L1[i]) + '   ')

    else:

      txt2.insert(END, str(L1[i]) + '  ')


  if ctr < 89:

    ctr += 1

  txt1['state'] = DISABLED

  txt2['state'] = DISABLED

  if ctr == 90:

    btn1['state'] = DISABLED


pic1 = PhotoImage(file="Bingo.png")

lbl1 = Label(win, image=pic1, border=0)

lbl1.place(x=500, y=545)


lbl2 = Label(win, font=("Verdana", 32, "bold"), bg="yellow", width=3,

             relief="raised", borderwidth=3, anchor="w", border=2)

lbl2.place(x=150, y=580)


txt1 = Text(win, font=("Verdana", 26, "bold"), width=47, bg="blue",

            fg="white", height=6, undo=False)

txt1.place(x=10, y=10)


txt2 = Text(win, font=("Verdana", 26, "bold"), width=47, bg="green",

            fg="white", height=6, undo=False)

txt2.place(x=10, y=280)


pic2 = PhotoImage(file="Bingo Next.png")

btn1 = Button(win, image=pic2, command=Next) 

btn1.place(x=950, y=550)


win.mainloop()


Wednesday, November 8, 2023

Testing Internet speed


from tkinter import *
import speedtest

root=Tk()
root.geometry("320x250")
root.resizable(False,False)
root.title("Internet Speed Test")
root.config(bg='#E6E6FA')

Label(root,text="Internet Speed Test",font=("Arial,bold",22),bg='#8B8386',fg='White',width=30).pack(pady=10)
l1=Label(root,text="Download Speed :",font=("Arial,bold",15),bg='#E6E6FA')
l1.place(x=10,y=80)
ldspd=Label(root,text="",font=("Arial,bold",15),bg='#E6E6FA',fg='#089927')
ldspd.place(x=180,y=80)
l2=Label(root,text="Upload Speed :",font=("Arial,bold",15),bg='#E6E6FA')
l2.place(x=10,y=130)
luspd=Label(root,text="",font=("Arial,bold",15),bg='#E6E6FA',fg='#089927')
luspd.place(x=180,y=130)

def check():
  spd=speedtest.Speedtest()
  spd.get_servers()
  dspd=str(round(spd.download() / (10**6),3)) + " Mbps"
  uspd=str(round(spd.upload() / (10**6),3)) + " Mbps"
  ldspd.config(text=dspd)
  luspd.config(text=uspd)

btn=Button(root,text="Check",font=('Arial,bold',15),bd=5,bg='#8B8386',fg='White',activebackground='#8B8386',activeforeground='White',command=check)
btn.place(x=125,y=190)

root.mainloop()

Sunday, October 15, 2023

Automate SQL Table Creation/Insertion using Python

def createTable():

  global fields, table

  table = input("Enter table name: ")

  s = "CREATE TABLE " + table + "(\n"

  while True:

    attr = input("Enter attribute: ") # Enter empty string to quit

    if attr == '':

      break

    dtype = input("Enter type: ").upper()

    fields[attr] = dtype

    s += '  ' + attr + ' ' + dtype + ',\n'

  s += ');'

  s = s[:-4] + s[-2:]

  print(s)

  out = open("TempTable.txt", 'w')

  out.write(s) # Write CREATE TABLE commands to TempTable.txt

  out.close()


def addRecords():

  global table, fields

  out = open("TempRecords.txt", 'w')

  while True:

    choice = input("Continue inserting? ") # Enter empty string to quit

    if choice == '':

      break

    rec = "INSERT INTO " + table + " VALUES("

    for key in fields.keys():

      s = "Enter " + key + " - " + fields[key] + ": "

      val = input(s)

      dtype = fields[key].upper()[:3]

      if dtype != "INT" and dtype != "DEC" and dtype != "BOO":

        val = "'" + val + "'"

      rec += val + ', '

    rec = rec[:-2] + ");\n"

    out.write(rec) # Write INSERT INTO commands to TempRecords.txt

  out.close()


table, fields = "", {}

while True:

  print("1. CREATE TABLE")

  print("2. INSERT INTO")

  print("0. Exit")

  choice = input("Enter choice: ")

  if choice == '1':

    createTable()

  elif choice == '2':

    addRecords()

  elif choice == '0':

    break

  else:

    print("Wrong choice\n")


Monday, August 28, 2023

Using ChatGPT with Python GUI


# API Key created on 28th August, 2023, valid for 3 months

# Email: bt25.bcrs@gmail.com Password: Bantuda25New

# Verification Mobile: 9847578833

# https://copyassignment.com/create-your-own-chatgpt-with-python/


import openai

from tkinter import *


win = Tk()

win.geometry("750x450")

win['background'] = '#11A37B'

win.title("Using ChatGPT with Python GUI")


openai.api_key = "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"

model_engine = "text-davinci-003"


def reply(e):

  completion = openai.Completion.create(n=1, stop=None,

  engine="text-davinci-003", prompt=S1.get(),

  max_tokens=1024, temperature=0.5)

  response = completion.choices[0].text.strip()

  txt.delete("0.0", END)

  txt.insert("1.0", response)


S1, S2 = StringVar(), StringVar()

S1.set("")

font1 = ("Verdana", 14, "bold")

font2 = ("Verdana", 24, "bold")

lblHeader = Label(win, text="Hosted by BCRS", font=font2, bg='#11A37B', fg='#FFFFFF')

lblHeader.place(x=280, y=25)

pic = PhotoImage(file="ChatGPT.png")

lblImg = Label(win, image=pic)

lblImg.place(x=40, y=5)

lbl = Label(win, text='Enter prompt', font=font1, bg='#11A37B', fg='#FFFFFF')

lbl.place(x=10, y=130)

ent = Entry(win, textvariable=S1, font=font1, width=40, bg='#11A37B', fg='#FFFFFF')

ent.place(x=180, y=130)

ent.bind('<Return>', reply)

ent.focus()

txt = Text(win, font=font1, width=50, height=10, wrap=WORD, bg='#11A37B', fg='#FFFFFF')

txt.place(x=25, y=180)


win.mainloop()


Use ChatGPT with Python

# API Key created on 28th August, 2023, valid for 3 months

# Email: bt25.bcrs@gmail.com Password: Bantuda25New

# Verification Mobile: 9847578833

# https://copyassignment.com/create-your-own-chatgpt-with-python/


import openai


openai.api_key = "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"


while True:

  model_engine = "text-davinci-003"

  prompt = input('Enter new prompt: ')


  if 'exit' in prompt or 'quit' in prompt:

    break


  completion = openai.Completion.create(

    engine=model_engine, prompt=prompt,

    max_tokens=1024, n=1, stop=None,

    temperature=0.5,

  )


  response = completion.choices[0].text

  print(response)


Tuesday, August 15, 2023

Python script to backup files

import shutil

inn = open("C:/Users/TECHNOSOFT/Desktop/Files to Backup.txt")
L = inn.readlines()
L1 = []
for src in L:
  src = src.strip()
  dest = "G" + src[1:]
  shutil.copy(src, dest)
inn.close()

Saturday, August 5, 2023

Calculating percentiles of marks (roughly as per CBSE guidelines)

import random, csv


nos = 135

nop = 8

percentile = nos // nop

grades = ["A+", "A", "B+", "B", "C+", "C", "D", "F",]


def WriteCSV():

  out = open("Marks.csv", 'w', newline='')

  W = csv.writer(out)

  W.writerow(["English", "Maths"])

  for i in range(nos):

    E = random.randint(30, 100)

    M = random.randint(30, 100)

    W.writerow([E, M])

  out.close()


def ReadCSV():

  inn = open("Marks.csv", 'r', newline='')

  R = csv.reader(inn)

  L = list(R)

  eMarks, mMarks = [], []

  eCutOffs, mCutOffs = [], []

  for i in range(1, len(L)):

    eMarks.append(int(L[i][0]))

    mMarks.append(int(L[i][1]))

  eMarks.sort(reverse=True)

  mMarks.sort(reverse=True)

  for i in range(0, len(eMarks), percentile):

    print(eMarks[i:i+percentile])

    if i < nop * percentile:

      eCutOffs.append(eMarks[i+percentile])

  print(eCutOffs)

  for i in range(1, len(L)):

    for j in range(len(eCutOffs)):

      if int(L[i][0]) >= eCutOffs[j]:

        grade = grades[j]

    L[i].insert(1, grade)

  print(L)


  out = open("Grades.xlsx", 'w', newline='')

  W = csv.writer(out)

  W.writerows(L)

  out.close()


WriteCSV()

ReadCSV()

Saturday, July 22, 2023

BANNER program in Python

# If you've used Unix, you might be familiar with the Banner command.
# Here is my version of the Banner command on Python 3. 
# Sample Output

alpha = [[[" AAAAA "],
          ["A     A"],
          ["A     A"],
          ["AAAAAAA"],
          ["A     A"],
          ["A     A"],
          ["A     A"]
         ], 
         [["BBBBBB "], 
          ["B     B"],
          ["B     B"],
          ["BBBBBB "],
          ["B     B"],
          ["B     B"],
          ["BBBBBB "]
         ],
         [[" CCCCC "],
          ["C     C"],
          ["C      "],
          ["C      "],
          ["C      "],
          ["C     C"],
          [" CCCCC "]
         ],
         [["DDDDDD "], 
          ["D     D"],
          ["D     D"],
          ["D     D"],
          ["D     D"],
          ["D     D"],
          ["DDDDDD "],
         ],
         [["EEEEEEE"], 
          ["E      "],
          ["E      "],
          ["EEEEE  "],
          ["E      "],
          ["E      "],
          ["EEEEEEE"],
         ],
         [["FFFFFFF"],
          ["F      "],
          ["F      "],
          ["FFFFF  "],
          ["F      "],
          ["F      "],
          ["F      "],
         ],
         [[" GGGGGG"], 
          ["G      "],
          ["G      "],
          ["G   GGG"],
          ["G   G G"],
          ["G   G G"],
          [" GGGG G"],
         ],
         [["H     H"], 
          ["H     H"],
          ["H     H"],
          ["HHHHHHH"],
          ["H     H"],
          ["H     H"],
          ["H     H"],
         ],
         [["IIIIIII"], 
          ["   I   "],
          ["   I   "],
          ["   I   "],
          ["   I   "],
          ["   I   "],
          ["IIIIIII"],
         ],
         [["JJJJJJJJ"], 
          ["    J   "],
          ["    J   "],
          ["    J   "],
          ["    J   "],
          ["J   J   "],
          [" JJJ    "],
         ],
         [["K   K"], 
          ["K  K "],
          ["K K  "],
          ["KK   "],
          ["K K  "],
          ["K  K "],
          ["K   K"],
         ],
         [["L      "], 
          ["L      "],
          ["L      "],
          ["L      "],
          ["L      "],
          ["L      "],
          ["LLLLLLL"],
         ],
         [["M     M"], 
          ["MM   MM"],
          ["M M M M"],
          ["M  M  M"],
          ["M     M"],
          ["M     M"],
          ["M     M"],
         ],
         [["N     N"],
          ["NN    N"],
          ["N N   N"],
          ["N  N  N"],
          ["N   N N"],
          ["N    NN"],
          ["N     N"],
         ],
         [[" OOOOO "], 
          ["O     O"],
          ["O     O"],
          ["O     O"],
          ["O     O"],
          ["O     O"],
          [" OOOOO "],
         ],
         [["PPPPPP "], 
          ["P     P"],
          ["P     P"],
          ["PPPPPP "],
          ["P      "],
          ["P      "],
          ["P      "],
         ],
         [[" QQQQQ   "], 
          ["Q     Q  "],
          ["Q     Q  "],
          ["Q   Q Q  "],
          ["Q    QQ  "],
          ["Q     Q  "],
          [" QQQQQ Q "],
         ],
         [["RRRRRR "], 
          ["R     R"],
          ["R     R"],
          ["RRRRRR "],
          ["R   R  "],
          ["R    R "],
          ["R     R"],
         ],
         [[" SSSSS "], 
          ["S     S"],
          ["S      "],
          [" SSSSS "],
          ["      S"],
          ["S     S"],
          [" SSSSS "],
         ],
         [["TTTTTTT"], 
          ["   T   "],
          ["   T   "],
          ["   T   "],
          ["   T   "],
          ["   T   "],
          ["   T   "],
         ],
         [["U     U"], 
          ["U     U"],
          ["U     U"],
          ["U     U"],
          ["U     U"],
          ["U     U"],
          [" UUUUU "],
         ],
         [["V      V"],
          ["V      V"],
          ["V      V"],
          [" V    V "],
          [" V   V  "],
          ["  V V   "],
          ["   V    "],
         ],
         [["W     W"], 
          ["W     W"],
          ["W     W"],
          ["W  W  W"],
          ["W W W W"],
          ["WW   WW"],
          ["W     W"],
         ],
         [["X     X"], 
          [" X   X "],
          ["  X X  "],
          ["   X   "],
          ["  X X  "],
          [" X   X "],
          ["X     X"],
         ],
         [["Y     Y"], 
          [" Y   Y "],
          ["  Y Y  "],
          ["   Y   "],
          ["   Y   "],
          ["   Y   "],
          ["   Y   "],
         ],
         [["ZZZZZZZ"], 
          ["     Z "],
          ["    Z  "],
          ["   Z   "],
          ["  Z    "],
          [" Z     "],
          ["ZZZZZZZ"],
         ]
        ]

name = input("Enter a string: ").upper()
for i in range(7):
  for j in range(len(name)):
    diff = ord(name[j]) - 65
    print(*alpha[diff][i], end='    ')
  print()

Monday, July 17, 2023

Removing blank lines from Blogger blogs

with open("Blogger.txt", 'r') as inn:    # Text copied onto Blogger.txt 

  L = inn.readlines()

  L1 = []

  for item in L:

    if item != '\n':

      L1.append(item)


with open("Blogger.txt", 'w') as out:    # Write back to Blogger.txt

  for item in L1:

    out.write(item)



Vigenere Cipher

def CaesarEncrypt(ch, shift):

  ch1 = ord(ch) + shift

  if ch1 > 122:

    ch1 -= 26

  return chr(ch1)


def CaesarDecrypt(ch, shift):

  ch1 = ord(ch) - shift

  if ch1 < 97:

    ch1 += 26

  return chr(ch1)


def VigenereEncrypt():

  global encryptedMessage

  for i in range(len(originalMessage)):

    if originalMessage[i] == ' ':

      encryptedMessage += ' '

      continue

    shift = ord(key[i%len(key)]) - ord('A'.lower())

    char = CaesarEncrypt(originalMessage[i], shift)

    encryptedMessage += char

  print(encryptedMessage)


def VigenereDecrypt():

  global decryptedMessage

  for i in range(len(encryptedMessage)):

    if encryptedMessage[i] == ' ':

      decryptedMessage += ' '

      continue

    shift = ord(key[i%len(key)]) - ord('A'.lower())

    char = CaesarDecrypt(encryptedMessage[i], shift)

    decryptedMessage += char

  print(decryptedMessage)


originalMessage = "attacking tonight"

encryptedMessage, decryptedMessage = "", ""

key = "OCULORHINOLARINGOLOGY".lower()

size = len(key)

VigenereEncrypt()

VigenereDecrypt()

Tuesday, March 21, 2023

Create Bingo cards using CSV module

A Housie card has 3 rows x 9 columns of numbers. The numbers that can appear under each column are 1–9, 10–19, 20–29, 30–39, 40–49, 50–59, 60–69, 70–79 & 80–90. WAPS to create 10 random Housie cards and write the same to a CSV file.

import random, csv


def generateTicket():

         # 4 cols with 1 & 2 nos, 1 col with 3 nos

  LL = [[0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 1, 0], [0, 1, 1], [0, 1, 1],

        [1, 1, 0], [1, 1, 0], [1, 1, 1]]

  random.shuffle(LL)

         # Range of numbers in each column

  nums = [list(range(1,  10)), list(range(10, 20)), list(range(20, 30)), 

          list(range(30, 40)), list(range(40, 50)), list(range(50, 60)),

          list(range(60, 70)), list(range(70, 80)), list(range(80, 91))]

  for i in range(9):

    random.shuffle(nums[i]) # Shuffle the numbers

    ascending = sorted(nums[i][:3]) # Sort only the 3 nos. to be displayed

    for j in range(3):

      nums[i][j] = ascending[j]


          # Where the numbers will be stored 

  bingo = [[0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 1, 0], [0, 1, 1],

           [0, 1, 1], [1, 1, 0], [1, 1, 0], [1, 1, 1]]

  for i in range(9):

    for j in range(3):

      bingo[i][j] = "" if LL[i][j] == 0 else nums[i][j]

  return bingo


def transpose(L1):

  L2 = []

  for i in range(len(L1[0])):

    row = []

    for item in L1:

      row.append(item[i])

    L2.append(row)

  return L2


def createCSV():

  bingo = generateTicket()

  bingo = transpose(bingo)

  with open("Bingo1.csv", 'a', newline='') as out:

    W = csv.writer(out)

    W.writerow("")

    for i in bingo:

      W.writerow(i)

    W.writerow("")


for i in range(10):  # Create 10 tickets

  createCSV()