Showing posts with label Project. Show all posts
Showing posts with label Project. Show all posts

snowman

import turtle

turtle.speed(2)

turtle.setup(800, 700)

turtle.bgcolor("black")

turtle.penup()

turtle.goto(0, -320)

turtle.pendown()

turtle.color("#c1f8b5")

turtle.begin_fill()

turtle.circle(320)

turtle.end_fill()

turtle.penup()

turtle.goto(0, -280)

turtle.pendown()

turtle.color("white")

turtle.begin_fill()

turtle.circle(110)

turtle.end_fill()

turtle.penup()

turtle.goto(0, -110)

turtle.pendown()

turtle.begin_fill()

turtle.circle(90)

turtle.end_fill()

turtle.penup()

turtle.goto(0, 20)

turtle.pendown()

turtle.begin_fill()

turtle.circle(70)

turtle.end_fill()

def black_circle():

turtle.color("black")

turtle.begin_fill()

turtle.circle(10)

turtle.end_fill()

x = -20

for i in range(2):

turtle.penup()

turtle.goto(x, 110)

turtle.pendown()

black_circle()

x = x + 40

y = 0

for i in range(5):

turtle.penup()

turtle.goto(0, y)

turtle.pendown()

black_circle()

y = y - 55

turtle.penup()

turtle.goto(0,70)

turtle.pendown()

turtle.color("red")

turtle.begin_fill()

turtle.circle(17)

turtle.end_fill()

turtle.penup()

turtle.goto(0,75)

turtle.pendown()

turtle.color("white")

turtle.begin_fill()

turtle.circle(17)

turtle.end_fill()

turtle.penup()

turtle.goto(75, 0)

turtle.pendown()

turtle.color("brown")

turtle.begin_fill()

turtle.left(40)

for i in range(2):

turtle.forward(75)

turtle.left(90)

turtle.forward(7)

turtle.left(90)

turtle.end_fill()

turtle.penup()

turtle.goto(115, 38)

turtle.pendown()

turtle.begin_fill()

turtle.left(40)

for i in range(2):

turtle.forward(25)

turtle.left(90)

turtle.forward(5)

turtle.left(90)

turtle.end_fill()

turtle.begin_fill()

turtle.right(100)

for i in range(2):

turtle.forward(25)

turtle.left(90)

turtle.forward(5)

turtle.left(90)

turtle.end_fill()

turtle.penup()

turtle.goto(-130, 50)

turtle.pendown()

turtle.begin_fill()

turtle.right(10)

for i in range(2):

turtle.forward(75)

turtle.right(90)

turtle.forward(7)

turtle.right(90)

turtle.end_fill()

turtle.penup()

turtle.goto(-112, 58)

turtle.pendown()

turtle.begin_fill()

turtle.right(40)

for i in range(2):

turtle.forward(25)

turtle.right(90)

turtle.forward(5)

turtle.right(90)

turtle.end_fill()

turtle.begin_fill()

turtle.right(100)

turtle.penup()

turtle.goto(-108, 31)

turtle.pendown()

for i in range(2):

turtle.forward(25)

turtle.right(90)

turtle.forward(5)

turtle.right(90)

turtle.end_fill()

turtle.penup()

turtle.goto(50, 150)

turtle.pendown()

turtle.color("black")

turtle.begin_fill()

turtle.right(10)

turtle.forward(100)

turtle.right(90)

turtle.forward(10)

turtle.right(90)

turtle.forward(20)

turtle.left(90)

turtle.forward(45)

turtle.right(90)

turtle.forward(60)

turtle.right(90)

turtle.forward(45)

turtle.left(90)

turtle.forward(20)

turtle.right(90)

turtle.end_fill()

turtle.hideturtle()


Extract Links

import requests

from bs4 import BeautifulSoup

url = 'https://www.pythonforengineers.in/'

reqs = requests.get(url)

soup = BeautifulSoup(reqs.text, 'html.parser')

urls = []

for link in soup.find_all('a'):

print(link.get('href'))


Scraping TV Rating

import requests

from bs4 import BeautifulSoup

def getdata(url):

r = requests.get(url)

return r.text

htmldata = getdata("https://barcindia.co.in/data-insights")

soup = BeautifulSoup(htmldata, 'html.parser')

data = ''

for i in soup.find_all('tbody'):

data = data + (i.get_text())

data

data = ''.join((filter(lambda i: i not in ['\t'], data)))

print(data)


Caller Info

import requests

import pandas as pd

from bs4 import BeautifulSoup

def getdata(url):

r=requests.get(url)

return r.text

# Enter your own API key 

api = 'YOUR API KEY'

number = '9876543210'

country = 'IN'

# pass Your API, number and country code

htmldata=getdata('http://apilayer.net/api/validate?access_key='+api+'&number='+number+'&country_code='+country+'&format=1')

soup = BeautifulSoup(htmldata, 'html.parser')

print(soup)


Digital clock

import time

import datetime as dt

import turtle

t = turtle.Turtle()

t1 = turtle.Turtle()

s = turtle.Screen()

s.bgcolor("green")

sec = dt.datetime.now().second

min = dt.datetime.now().minute

hr = dt.datetime.now().hour

t1.pensize(3)

t1.color('black')

t1.penup()

t1.goto(-20, 0)

t1.pendown()

for i in range(2):

t1.forward(200)

t1.left(90)

t1.forward(70)

t1.left(90)

t1.hideturtle()

while True:

t.hideturtle()

t.clear()

t.write(str(hr).zfill(2)

+ ":"+str(min).zfill(2)+":"

+ str(sec).zfill(2),

font=("Arial Narrow", 35, "bold"))

time.sleep(1)

sec += 1

if sec == 60:

sec = 0

min += 1

if min == 60:

min = 0

hr += 1

if hr == 13:

hr = 1


openai

import openai

openai.api_key = "your secret api key"

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)


To get secret api key  go to   openai.com/api/ and signup

then login and go to  platform.openai.com/ 

click on personal and then click on vie api keys and now click on 'create new secret key'.

Scientific calculator

import tkinter as tk

from math import *

convert_constant = 1

inverse_convert_constant = 1

btn_params = {'padx': 16, 'pady': 1, 'bd': 4, 'fg': 'white', 'bg': 'black', 'font': ('arial', 18),

              'width': 2, 'height': 2, 'relief': 'flat', 'activebackground': "black"}

def fsin(arg):

    return sin(arg * convert_constant)

def fcos(arg):

    return cos(arg * convert_constant)

def ftan(arg):

    return tan(arg * convert_constant)

def arcsin(arg):

    return inverse_convert_constant * (asin(arg))

def arccos(arg):

    return inverse_convert_constant * (acos(arg))

def arctan(arg):

    return inverse_convert_constant * (atan(arg))

class Calculator:

    def __init__(self, master):

        self.expression = ""

        self.recall = ""

        self.sum_up = ""

        self.text_input = tk.StringVar()

        self.master = master

        top_frame = tk.Frame(master, width=650, height=10,

                             bd=10, relief='flat', bg='gray')

        top_frame.pack(side=tk.TOP)

        bottom_frame = tk.Frame(

            master, width=650, height=470, bd=2, relief='flat', bg='black')

        bottom_frame.pack(side=tk.BOTTOM)

        txt_display = tk.Entry(top_frame, font=('arial', 36), relief='flat', bg='black', fg='white', textvariable=self.text_input, width=60, bd=12, justify='right')

        txt_display.pack()

        self.btn_left_brack = tk.Button(

            bottom_frame, **btn_params, text="(", border=1, command=lambda: self.btn_click('('))

        self.btn_left_brack.grid(row=0, column=0)

        self.btn_right_brack = tk.Button(

            bottom_frame, **btn_params, text=")", command=lambda: self.btn_click(')'))

        self.btn_right_brack.grid(row=0, column=1)

        self.btn_exp = tk.Button(

            bottom_frame, **btn_params, text="exp", command=lambda: self.btn_click('exp('))

        self.btn_exp.grid(row=0, column=2)

        self.btn_pi = tk.Button(

            bottom_frame, **btn_params, text="π", command=lambda: self.btn_click('pi'))

        self.btn_pi.grid(row=0, column=3)

        self.btn_sqrt = tk.Button(

            bottom_frame, **btn_params, text="sqrt", command=lambda: self.btn_click('sqrt('))

        self.btn_sqrt.grid(row=0, column=4)

        self.btn_clear = tk.Button(

            bottom_frame, **btn_params, text="C", command=self.btn_clear_all)

        self.btn_clear.grid(row=0, column=5)

        self.btn_del = tk.Button(

            bottom_frame, **btn_params, text="AC", command=self.btn_clear1)

        self.btn_del.grid(row=0, column=6)

        self.btn_change_sign = tk.Button(

            bottom_frame, **btn_params, text="+/-", command=self.change_signs)

        self.btn_change_sign.grid(row=0, column=7)

        self.btn_div = tk.Button(

            bottom_frame, **btn_params, text="/", command=lambda: self.btn_click('/'))

        self.btn_div.grid(row=0, column=8)

        self.btn_Deg = tk.Button(bottom_frame, **btn_params, activeforeground='gray', text="Deg", command=self.convert_deg)

        self.btn_Deg.grid(row=1, column=0)

        self.btn_Rad = tk.Button(bottom_frame, **btn_params, foreground='white', activeforeground='Gray', text="Rad", command=self.convert_rad)

        self.btn_Rad.grid(row=1, column=1)

        self.cube = tk.Button(bottom_frame, **btn_params, text=u"x\u00B3", command=lambda: self.btn_click('**3'))

        self.cube.grid(row=1, column=2)

        self.btn_abs = tk.Button(

            bottom_frame, **btn_params, text="abs", command=lambda: self.btn_click('abs' + '('))

        self.btn_abs.grid(row=1, column=3)

        self.btn_MC = tk.Button(

            bottom_frame, **btn_params, text="MC", command=self.memory_clear)

        self.btn_MC.grid(row=1, column=4)

        self.btn_7 = tk.Button(bottom_frame, **btn_params, text="7", command=lambda: self.btn_click(7))

        self.btn_7.configure(activebackground="black", bg='black')

        self.btn_7.grid(row=1, column=5)

        self.btn_8 = tk.Button(bottom_frame, **btn_params, text="8", command=lambda: self.btn_click(8))

        self.btn_8.configure(activebackground="black", bg='black')

        self.btn_8.grid(row=1, column=6)

        self.btn_9 = tk.Button(bottom_frame, **btn_params, text="9", command=lambda: self.btn_click(9))

        self.btn_9.configure(activebackground="black", bg='black')

        self.btn_9.grid(row=1, column=7)

        self.btn_mult = tk.Button(bottom_frame, **btn_params, text="x", command=lambda: self.btn_click('*'))

        self.btn_mult.grid(row=1, column=8)

        self.btn_sin = tk.Button(

            bottom_frame, **btn_params, text="sin", command=lambda: self.btn_click('fsin('))

        self.btn_sin.grid(row=2, column=0)

        self.btn_cos = tk.Button(

            bottom_frame, **btn_params, text="cos", command=lambda: self.btn_click('fcos('))

        self.btn_cos.grid(row=2, column=1)

        self.btn_tan = tk.Button(bottom_frame, **btn_params, text="tan", command=lambda: self.btn_click('ftan('))

        self.btn_tan.grid(row=2, column=2)

        self.btn_log = tk.Button(bottom_frame, **btn_params, text="log", command=lambda: self.btn_click('log('))

        self.btn_log.grid(row=2, column=3)

        self.btn_MR = tk.Button(bottom_frame, **btn_params, text="MR", command=self.memory_recall)

        self.btn_MR.grid(row=2, column=4)

        self.btn_4 = tk.Button(bottom_frame, **btn_params, text="4", command=lambda: self.btn_click(4))

        self.btn_4.configure(activebackground="black", bg='black')

        self.btn_4.grid(row=2, column=5)

        self.btn_5 = tk.Button(bottom_frame, **btn_params, text="5", command=lambda: self.btn_click(5))

        self.btn_5.configure(activebackground="black", bg='black')

        self.btn_5.grid(row=2, column=6)

        self.btn_6 = tk.Button(bottom_frame, **btn_params, text="6", command=lambda: self.btn_click(6))

        self.btn_6.configure(activebackground="black", bg='black')

        self.btn_6.grid(row=2, column=7)

        self.btnSub = tk.Button(bottom_frame, **btn_params, text="-", command=lambda: self.btn_click('-'))

        self.btnSub.grid(row=2, column=8)

        self.btn_sin_inverse = tk.Button(bottom_frame, **btn_params, text=u"sin-\u00B9", command=lambda: self.btn_click('arcsin('))

        self.btn_sin_inverse.grid(row=3, column=0)

        self.btn_cos_inverse = tk.Button(bottom_frame, **btn_params, text=u"cos-\u00B9", command=lambda: self.btn_click('arccos('))

        self.btn_cos_inverse.grid(row=3, column=1)

        self.btn_tan_inverse = tk.Button(bottom_frame, **btn_params, text=u"tan-\u00B9", command=lambda: self.btn_click('arctan('))

        self.btn_tan_inverse.grid(row=3, column=2)

        self.btn_ln = tk.Button(bottom_frame, **btn_params, text="ln", command=lambda: self.btn_click('log1p('))

        self.btn_ln.grid(row=3, column=3)

        self.btn_M_plus = tk.Button(bottom_frame, **btn_params, text="M+", command=self.memory_add)

        self.btn_M_plus.grid(row=3, column=4)

        self.btn_1 = tk.Button(bottom_frame, **btn_params, text="1", command=lambda: self.btn_click(1))

        self.btn_1.configure(activebackground="black", bg='black')

        self.btn_1.grid(row=3, column=5)

        self.btn_2 = tk.Button(bottom_frame, **btn_params, text="2", command=lambda: self.btn_click(2))

        self.btn_2.configure(activebackground="black", bg='black')

        self.btn_2.grid(row=3, column=6)

        self.btn_3 = tk.Button(bottom_frame, **btn_params, text="3", command=lambda: self.btn_click(3))

        self.btn_3.configure(activebackground="black", bg='black')

        self.btn_3.grid(row=3, column=7)

        self.btn_add = tk.Button(

            bottom_frame, **btn_params, text="+", command=lambda: self.btn_click('+'))

        self.btn_add.grid(row=3, column=8)

        self.btn_fact = tk.Button(bottom_frame, **btn_params, text="n!", command=lambda: self.btn_click('factorial('))

        self.btn_fact.grid(row=4, column=0)

        self.btn_sqr = tk.Button(bottom_frame, **btn_params, text=u"x\u00B2", command=lambda: self.btn_click('**2'))

        self.btn_sqr.grid(row=4, column=1)

        self.btn_power = tk.Button(bottom_frame, **btn_params, text="x^y", command=lambda: self.btn_click('**'))

        self.btn_power.grid(row=4, column=2)

        self.btn_ans = tk.Button(bottom_frame, **btn_params, text="ans", command=self.answer)

        self.btn_ans.grid(row=4, column=3)

        self.btn_comma = tk.Button(bottom_frame, **btn_params, text=",", command=lambda: self.btn_click(','))

        self.btn_comma.grid(row=4, column=4)

        self.btn_0 = tk.Button(bottom_frame, **btn_params, text="0", command=lambda: self.btn_click(0))

        self.btn_0.configure(activebackground="black", bg='black', width=7, bd=5)

        self.btn_0.grid(row=4, column=5, columnspan=2)

        self.btn_eq = tk.Button(bottom_frame, **btn_params, text="=", command=self.btn_equal)

        self.btn_eq.configure(bg='Gray', activebackground='#009999')

        self.btn_eq.grid(row=4, column=7)

        self.btn_dec = tk.Button(bottom_frame, **btn_params, text=".", command=lambda: self.btn_click('.'))

        self.btn_dec.grid(row=4, column=8)

    def btn_click(self, expression_val):

        if len(self.expression) >= 23:

            self.expression = self.expression

            self.text_input.set(self.expression)

        else:

            self.expression = self.expression + str(expression_val)

            self.text_input.set(self.expression)

    def btn_clear1(self):

        self.expression = self.expression[:-1]

        self.text_input.set(self.expression)

    def change_signs(self):

        self.expression = self.expression + '-'

        self.text_input.set(self.expression) 

    def memory_clear(self):

        self.recall = "" 

    def memory_add(self):

        self.recall = self.recall + '+' + self.expression 

    def answer(self):

        self.answer = self.sum_up

        self.expression = self.expression + self.answer

        self.text_input.set(self.expression)

    def memory_recall(self):

        if self.expression == "":

            self.text_input.set('0' + self.expression + self.recall)

        else:

            self.text_input.set(self.expression + self.recall) 

    def convert_deg(self):

        global convert_constant

        global inverse_convert_constant

        convert_constant = pi / 180

        inverse_convert_constant = 180 / pi

        self.btn_Rad["foreground"] = 'white'

        self.btn_Deg["foreground"] = 'RED'

    def convert_rad(self):

        global convert_constant

        global inverse_convert_constant

        convert_constant = 1

        inverse_convert_constant = 1

        self.btn_Rad["foreground"] = 'RED'

        self.btn_Deg["foreground"] = 'white' 

    def btn_clear_all(self):

        self.expression = ""

        self.text_input.set("") 

    def btn_equal(self):

        self.sum_up = str(eval(self.expression))

        self.text_input.set(self.sum_up)

        self.expression = self.sum_up

root = tk.Tk()

b = Calculator(root)

root.title("Scientific Calculator!")

root.geometry("650x490+50+50")

root.resizable(False, False)

root.mainloop()

music player

import pygame

from pygame import mixer

pygame.init()

mixer.init()

screen = pygame.display.set_mode((600, 400))

mixer.music.load("audio.mp3")

mixer.music.play()

print("Press 'p' to pause 'r' to resume")

print("Press 'q' to quit")

running = True

while running:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:

            running = False

        if event.type == pygame.KEYDOWN:

            if event.key == pygame.K_p:

                mixer.music.pause()

            if event.key == pygame.K_r:

                mixer.music.unpause()

            if event.key == pygame.K_q:

                running = False

quit()

Voice Assistant

import pyttsx3

import speech_recognition as sr

def take_commands():

    r = sr.Recognizer()

    with sr.Microphone() as source:

        print('Listening')

        r.pause_threshold = 0.7

        audio = r.listen(source)

        try:

            print("Recognizing")

            Query = r.recognize_google(audio)

            print("the query is printed='", Query, "'")

        except Exception as e:

            print(e)

            print("Say that again sir")

            return "None"

    return Query

def Speak(audio):

    engine = pyttsx3.init()

    engine.say(audio)

    engine.runAndWait()

if __name__ == '__main__':

    while True:

        command = take_commands()

        if "exit" in command:

            Speak("Sure sir! as your wish, bye")

            break

        if "welcome" in command:

            Speak("hi welcome to python for engineers")

        if "python" in command:

            Speak("a complete solution for python programming")

Typing Speed Test Application

from tkinter import *

import ctypes

import random

import tkinter

ctypes.windll.shcore.SetProcessDpiAwareness(1)

storage = Tk()

storage.title('Typing Speed Test')

storage.geometry('1400x700')

storage.option_add("*Label.Font", "consolas 30")

storage.option_add("*Button.Font", "consolas 30")

def handlingLabels():

    random_selection = [

        'Software engineering is the branch of computer science that deals with the design, development, testing, and maintenance of software applications. Software engineers apply engineering principles and knowledge of programming languages to build software solutions for end users.',

        'A web developer is a programmer who develops World Wide Web applications using a client–server model. The applications typically use HTML, CSS, and JavaScript in the client, and any general-purpose programming language in the server. HTTP is used for communications between client and server.'

    ]

    text = random.choice(random_selection).lower()

    splitPoint = 0

    global nameLabelLeft

    nameLabelLeft = Label(storage, text=text[0:splitPoint], fg='green')

    nameLabelLeft.place(relx=0.5, rely=0.5, anchor=E)

    global nameLabelRight

    nameLabelRight = Label(storage, text=text[splitPoint:])

    nameLabelRight.place(relx=0.5, rely=0.5, anchor=W)

    global currentAlphabetLabel

    currentAlphabetLabel = Label(storage, text=text[splitPoint], fg='grey')

    currentAlphabetLabel.place(relx=0.5, rely=0.6, anchor=N)

    global secondsLeft

    headingLabel = Label(storage, text=f'CopyAssignment - Typing Speed Test', fg='blue')

    headingLabel.place(relx=0.5, rely=0.2, anchor=S)

    secondsLeft = Label(storage, text=f'0 Seconds', fg='red')

    secondsLeft.place(relx=0.5, rely=0.4, anchor=S)

    global writeAble

    writeAble = True

    storage.bind('<Key>', handlekeyPress)

    global secondsPassed

    secondsPassed = 0

    storage.after(60000, stopGame)

    storage.after(1000, timeAddition)

def stopGame():

    global writeAble

    writeAble = False

    amountWords = len(nameLabelLeft.cget('text').split(' '))

    secondsLeft.destroy()

    currentAlphabetLabel.destroy()

    nameLabelRight.destroy()

    nameLabelLeft.destroy()

    global labelOfResult

    labelOfResult = Label(storage, text=f'Words per Minute (WPM): {amountWords}', fg='black')

    labelOfResult.place(relx=0.5, rely=0.4, anchor=CENTER)

    global showcaseResults

    showcaseResults = Button(storage, text=f'Retry', command=restartGame)

    showcaseResults.place(relx=0.5, rely=0.6, anchor=CENTER)

def restartGame():

    labelOfResult.destroy()

    showcaseResults.destroy()

    handlingLabels()

def timeAddition():

    global secondsPassed

    secondsPassed += 1

    secondsLeft.configure(text=f'{secondsPassed} Seconds')

    if writeAble:

        storage.after(1000, timeAddition)

def handlekeyPress(event=None):

    try:

        if event.char.lower() == nameLabelRight.cget('text')[0].lower():

            nameLabelRight.configure(text=nameLabelRight.cget('text')[1:])

            nameLabelLeft.configure(text=nameLabelLeft.cget('text') + event.char.lower())

            currentAlphabetLabel.configure(text=nameLabelRight.cget('text')[0])

    except tkinter.TclError:

        pass

handlingLabels()

storage.mainloop()


Drawing Application

from tkinter import *

from tkinter.ttk import Scale

from tkinter import colorchooser,filedialog,messagebox

import PIL.ImageGrab as ImageGrab

class Draw():

    def __init__(self,root):

        self.root =root

        self.root.title("Painter")

        self.root.configure(background="white")

        self.pointer= "black"

        self.erase="white"    

        text=Text(root)

        text.tag_configure("tag_name", justify='center', font=('arial',25),background='#292826',foreground='orange')

        text.insert("1.0", "Drawing Application ")

        text.tag_add("tag_name", "1.0", "end")

        text.pack()

        self.pick_color = LabelFrame(self.root,text='Colors',font =('arial',15),bd=5,relief=RIDGE,bg="white")

        self.pick_color.place(x=0,y=40,width=90,height=185)

        colors = ['blue','red','green', 'orange','violet','black','yellow','purple','pink','gold','brown','indigo']

        i=j=0

        for color in colors:

            Button(self.pick_color,bg=color,bd=2,relief=RIDGE,width=3,command=lambda col=color:self.select_color(col)).grid(row=i,column=j)

            i+=1

            if i==6:

                i=0

                j=1

        self.eraser_btn= Button(self.root,text="Eraser",bd=4,bg='white',command=self.eraser,width=9,relief=RIDGE)

        self.eraser_btn.place(x=0,y=197)

        self.clear_screen= Button(self.root,text="Clear Screen",bd=4,bg='white',command= lambda : self.background.delete('all'),width=9,relief=RIDGE)

        self.clear_screen.place(x=0,y=227)

        self.save_btn= Button(self.root,text="ScreenShot",bd=4,bg='white',command=self.save_drawing,width=9,relief=RIDGE)

        self.save_btn.place(x=0,y=257)

        self.bg_btn= Button(self.root,text="Background",bd=4,bg='white',command=self.canvas_color,width=9,relief=RIDGE)

        self.bg_btn.place(x=0,y=287)

        self.pointer_frame= LabelFrame(self.root,text='size',bd=5,bg='white',font=('arial',15,'bold'),relief=RIDGE)

        self.pointer_frame.place(x=0,y=320,height=200,width=70)

        self.pointer_size =Scale(self.pointer_frame,orient=VERTICAL,from_ =48 , to =0, length=168)

        self.pointer_size.set(1)

        self.pointer_size.grid(row=0,column=1,padx=15)

        self.background = Canvas(self.root,bg='white',bd=5,relief=GROOVE,height=470,width=680)

        self.background.place(x=80,y=40)

        self.background.bind("<B1-Motion>",self.paint) 

    def paint(self,event):       

        x1,y1 = (event.x-2), (event.y-2)  

        x2,y2 = (event.x+2), (event.y+2)  

        self.background.create_oval(x1,y1,x2,y2,fill=self.pointer,outline=self.pointer,width=self.pointer_size.get())

    def select_color(self,col):

        self.pointer = col

    def eraser(self):

        self.pointer= self.erase

    def canvas_color(self):

        color=colorchooser.askcolor()

        self.background.configure(background=color[1])

        self.erase= color[1]

    def save_drawing(self):

        try:

            file_ss =filedialog.asksaveasfilename(defaultextension='jpg')

            x=self.root.winfo_rootx() + self.background.winfo_x()

            y=self.root.winfo_rooty() + self.background.winfo_y()

            x1= x + self.background.winfo_width() 

            y1= y + self.background.winfo_height()

            ImageGrab.grab().crop((x , y, x1, y1)).save(file_ss)

            messagebox.showinfo('Screenshot Successfully Saved as' + str(file_ss))

        except:

            print("Error in saving the screenshot")

if __name__ =="__main__":

    root = Tk()

    p= Draw(root)

    root.mainloop()

Fire detection

import cv2

import numpy as np

import matplotlib.pyplot as plt

live_camera = cv2.VideoCapture(0)

while(live_camera.isOpened()):

    ret, frame = live_camera.read()

    cv2.imshow("Fire Detection",frame)

    if cv2.waitKey(10) == 27:

        break

img_RGB = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)

img_cap = plt.imshow(img_RGB)

plt.show()

live_camera.release()

cv2.destroyAllWindows()


Notepad

import tkinter

import os

from tkinter import *

from tkinter.messagebox import *

from tkinter.filedialog import *

class Notepad:

__root = Tk()

__thisWidth = 300

__thisHeight = 300

__thisTextArea = Text(__root)

__thisMenuBar = Menu(__root)

__thisFileMenu = Menu(__thisMenuBar, tearoff=0)

__thisEditMenu = Menu(__thisMenuBar, tearoff=0)

__thisHelpMenu = Menu(__thisMenuBar, tearoff=0)

__thisScrollBar = Scrollbar(__thisTextArea)

__file = None

def __init__(self,**kwargs):

try:

self.__root.wm_iconbitmap("Notepad.ico")

except:

pass

try:

self.__thisWidth = kwargs['width']

except KeyError:

pass

try:

self.__thisHeight = kwargs['height']

except KeyError:

pass

self.__root.title("Untitled - Notepad")

screenWidth = self.__root.winfo_screenwidth()

screenHeight = self.__root.winfo_screenheight()

left = (screenWidth / 2) - (self.__thisWidth / 2)

top = (screenHeight / 2) - (self.__thisHeight /2)

self.__root.geometry('%dx%d+%d+%d' % (self.__thisWidth,

self.__thisHeight,

left, top))

self.__root.grid_rowconfigure(0, weight=1)

self.__root.grid_columnconfigure(0, weight=1)

self.__thisTextArea.grid(sticky = N + E + S + W)

self.__thisFileMenu.add_command(label="New",

command=self.__newFile)

self.__thisFileMenu.add_command(label="Open",

command=self.__openFile)

self.__thisFileMenu.add_command(label="Save",

command=self.__saveFile)

self.__thisFileMenu.add_separator()

self.__thisFileMenu.add_command(label="Exit",

command=self.__quitApplication)

self.__thisMenuBar.add_cascade(label="File",

menu=self.__thisFileMenu)

self.__thisEditMenu.add_command(label="Cut",

command=self.__cut)

self.__thisEditMenu.add_command(label="Copy",

command=self.__copy)

self.__thisEditMenu.add_command(label="Paste",

command=self.__paste)

self.__thisMenuBar.add_cascade(label="Edit",

menu=self.__thisEditMenu)

self.__thisHelpMenu.add_command(label="About Notepad",

command=self.__showAbout)

self.__thisMenuBar.add_cascade(label="Help",

menu=self.__thisHelpMenu)

self.__root.config(menu=self.__thisMenuBar)

self.__thisScrollBar.pack(side=RIGHT,fill=Y)

self.__thisScrollBar.config(command=self.__thisTextArea.yview)

self.__thisTextArea.config(yscrollcommand=self.__thisScrollBar.set)

def __quitApplication(self):

self.__root.destroy()

def __showAbout(self):

showinfo("Notepad","Mrinal Verma")

def __openFile(self):

self.__file = askopenfilename(defaultextension=".txt",

filetypes=[("All Files","*.*"),

("Text Documents","*.txt")])

if self.__file == "":

self.__file = None

else:

self.__root.title(os.path.basename(self.__file) + " - Notepad")

self.__thisTextArea.delete(1.0,END)

file = open(self.__file,"r")

self.__thisTextArea.insert(1.0,file.read())

file.close()

def __newFile(self):

self.__root.title("Untitled - Notepad")

self.__file = None

self.__thisTextArea.delete(1.0,END)

def __saveFile(self):

if self.__file == None:

self.__file = asksaveasfilename(initialfile='Untitled.txt',

defaultextension=".txt",

filetypes=[("All Files","*.*"),

("Text Documents","*.txt")])

if self.__file == "":

self.__file = None

else:

file = open(self.__file,"w")

file.write(self.__thisTextArea.get(1.0,END))

file.close()

self.__root.title(os.path.basename(self.__file) + " - Notepad")

else:

file = open(self.__file,"w")

file.write(self.__thisTextArea.get(1.0,END))

file.close()

def __cut(self):

self.__thisTextArea.event_generate("<<Cut>>")

def __copy(self):

self.__thisTextArea.event_generate("<<Copy>>")

def __paste(self):

self.__thisTextArea.event_generate("<<Paste>>")

def run(self):

self.__root.mainloop()

notepad = Notepad(width=600,height=400)

notepad.run()


21 Game

def nearestMultipleTo4(num):

if num >= 4:

near = num + (4 - (num % 4))

else:

near = 4

return near

def lose1():

print ("\n\nYOU LOSE !")

print("Better luck next time !")

exit(0)

# checks the numbers are consecutive

def check(xyz):

i = 1

while i<len(xyz):

if (xyz[i]-xyz[i-1])!= 1:

return False

i = i + 1

return True

def start1():

xyz = []

last = 0

while True:

print ("Enter 'F' to take the first chance.")

print("Enter 'S' to take the second chance.")

chance = input('> ')

#First Player

if chance == "F":

while True:

if last == 20:

lose1()

else:

print ("\nYour Turn.")

print ("\nHow many numbers do you wish to enter?")

inp = int(input('> '))

if inp > 0 and inp <= 3:

comp = 4 - inp

else:

print ("Wrong input. You are disqualified from the game.")

lose1()

i, j = 1, 1

print ("Now enter the values")

while i <= inp:

a = input('> ')

a = int(a)

xyz.append(a)

i = i + 1

# store the last element of xyz.

last = xyz[-1]

# check numbers are consecutive

if check(xyz) == True:

if last == 21:

lose1()

else:

#"Computer's turn."

while j <= comp:

xyz.append(last + j)

j = j + 1

print ("Order of inputs after computer's turn is: ")

print (xyz)

last = xyz[-1]

else:

print ("\nYou did not input consecutive integers.")

lose1()

# player takes the second chance

elif chance == "S":

comp = 1

last = 0

while last < 20:

#"Computer's turn"

j = 1

while j <= comp:

xyz.append(last + j)

j = j + 1

print ("Order of inputs after computer's turn is:")

print (xyz)

if xyz[-1] == 20:

lose1()

else:

print ("\nYour turn.")

print ("\nHow many numbers do you wish to enter?")

inp = input('> ')

inp = int(inp)

i = 1

print ("Enter your values")

while i <= inp:

xyz.append(int(input('> ')))

i = i + 1

last = xyz[-1]

if check(xyz) == True:

# print (xyz)

near = nearestMultipleTo4(last)

comp = near - last

if comp == 4:

comp = 3

else:

comp = comp

else:

# if inputs are not consecutive

# automatically disqualified

print ("\nYou did not input consecutive integers.")

# print ("You are disqualified from the game.")

lose1()

print ("\n\nCONGRATULATIONS !!!")

print ("YOU WON !")

exit(0)

else:

print ("wrong choice")

game = True

while game == True:

print ("Player 2 is Computer.")

print("Do you want to play the 21 number game? (Yes / No)")

ans = input('> ')

if ans =='Yes':

start1()

else:

print ("Do you want quit the game?(yes / no)")

nex = input('> ')

if nex == "yes":

print ("You are quitting the game...")

exit(0)

elif nex == "no":

print ("Continuing...")

else:

print ("Wrong choice")


Screen Rotation Application

from tkinter import *

import rotatescreen

def Screen_rotate(temp):

screen = rotatescreen.get_primary_display()

if temp == "up":

screen.set_landscape()

elif temp == "right":

screen.set_portrait_flipped()

elif temp == "down":

screen.set_landscape_flipped()

elif temp == "left":

screen.set_portrait()

master = Tk()

master.geometry("100x100")

master.title("Screen Rotation")

master.configure(bg='light grey')

result = StringVar()

Button(master, text="Up", command=lambda: Screen_rotate(

"up"), bg="white").grid(row=0, column=3)

Button(master, text="Right", command=lambda: Screen_rotate(

"right"), bg="white").grid(row=1, column=6)

Button(master, text="Left", command=lambda: Screen_rotate(

"left"), bg="white").grid(row=1, column=2)

Button(master, text="Down", command=lambda: Screen_rotate(

"down"), bg="white").grid(row=3, column=3)

mainloop()


Application to Search Installed Application

from tkinter import *

import winapps

def app():

for item in winapps.search_installed(e.get()):

name.set(item.name)

version.set(item.version)

Install_date.set(item.install_date)

publisher.set(item.publisher)

uninstall_string.set(item.uninstall_string)

master = Tk()

master.configure(bg='light grey')

name = StringVar()

version = StringVar()

Install_date = StringVar()

publisher = StringVar()

uninstall_string = StringVar()

Label(master, text="Enter App name : ",

bg="light grey").grid(row=0, sticky=W)

Label(master, text="Name : ",

bg="light grey").grid(row=2, sticky=W)

Label(master, text="Version :",

bg="light grey").grid(row=3, sticky=W)

Label(master, text="Install date :",

bg="light grey").grid(row=4, sticky=W)

Label(master, text="publisher :",

bg="light grey").grid(row=5, sticky=W)

Label(master, text="Uninstall string :",

bg="light grey").grid(row=6, sticky=W)

Label(master, text="", textvariable=name,

bg="light grey").grid(row=2, column=1, sticky=W)

Label(master, text="", textvariable=version,

bg="light grey").grid(row=3, column=1, sticky=W)

Label(master, text="", textvariable=Install_date,

bg="light grey").grid(row=4, column=1, sticky=W)

Label(master, text="", textvariable=publisher,

bg="light grey").grid(row=5, column=1, sticky=W)

Label(master, text="", textvariable=uninstall_string,

bg="light grey").grid(row=6, column=1, sticky=W)

e = Entry(master, width=30)

e.grid(row=0, column=1)

b = Button(master, text="Show", command=app, bg="Blue")

b.grid(row=0, column=2, columnspan=2, rowspan=2, padx=5, pady=5,)

mainloop()


Generating prime numbers using the sieve of eratosthenes algorithm

def sieve_of_eratosthenes(n):

    primes = [True] * (n + 1)

    primes[0] = primes[1] = False


    for i in range(2, int(n ** 0.5) + 1):

        if primes[i]:

            for j in range(i ** 2, n + 1, i):

                primes[j] = False


    return [i for i in range(2, n + 1) if primes[i]]


# Example usage

n = 100

primes = sieve_of_eratosthenes(n)

print("The prime numbers up to", n, "are:", primes)

Sierpinski triangle fractal using turtle graphics

import turtle

def sierpinski(length, depth):

    if depth == 0:

        for i in range(3):

            turtle.forward(length)

            turtle.left(120)

    else:

        sierpinski(length / 2, depth - 1)

        turtle.forward(length / 2)

        sierpinski(length / 2, depth - 1)

        turtle.backward(length / 2)

        turtle.left(60)

        turtle.forward(length / 2)

        turtle.right(60)

        sierpinski(length / 2, depth - 1)

        turtle.left(60)

        turtle.backward(length / 2)

        turtle.right(60)

turtle.speed(0)

turtle.hideturtle()

turtle.penup()

turtle.goto(-200, -200)

turtle.pendown()

sierpinski(400, 5)

turtle.exitonclick()


Pong game

import turtle

sc = turtle.Screen()

sc.title("Pong game")

sc.bgcolor("white")

sc.setup(width=1000, height=600)

left_pad = turtle.Turtle()

left_pad.speed(0)

left_pad.shape("square")

left_pad.color("black")

left_pad.shapesize(stretch_wid=6, stretch_len=2)

left_pad.penup()

left_pad.goto(-400, 0)

right_pad = turtle.Turtle()

right_pad.speed(0)

right_pad.shape("square")

right_pad.color("black")

right_pad.shapesize(stretch_wid=6, stretch_len=2)

right_pad.penup()

right_pad.goto(400, 0)

hit_ball = turtle.Turtle()

hit_ball.speed(40)

hit_ball.shape("circle")

hit_ball.color("blue")

hit_ball.penup()

hit_ball.goto(0, 0)

hit_ball.dx = 5

hit_ball.dy = -5

left_player = 0

right_player = 0

sketch = turtle.Turtle()

sketch.speed(0)

sketch.color("blue")

sketch.penup()

sketch.hideturtle()

sketch.goto(0, 260)

sketch.write("Left_player : 0 Right_player: 0",

            align="center", font=("Courier", 24, "normal"))

def paddleaup():

    y = left_pad.ycor()

    y += 20

    left_pad.sety(y)

def paddleadown():

    y = left_pad.ycor()

    y -= 20

    left_pad.sety(y)

def paddlebup():

    y = right_pad.ycor()

    y += 20

    right_pad.sety(y)

def paddlebdown():

    y = right_pad.ycor()

    y -= 20

    right_pad.sety(y)

sc.listen()

sc.onkeypress(paddleaup, "e")

sc.onkeypress(paddleadown, "x")

sc.onkeypress(paddlebup, "Up")

sc.onkeypress(paddlebdown, "Down")

while True:

    sc.update()

    hit_ball.setx(hit_ball.xcor()+hit_ball.dx)

    hit_ball.sety(hit_ball.ycor()+hit_ball.dy)

    if hit_ball.ycor() > 280:

        hit_ball.sety(280)

        hit_ball.dy *= -1

    if hit_ball.ycor() < -280:

        hit_ball.sety(-280)

        hit_ball.dy *= -1

    if hit_ball.xcor() > 500:

        hit_ball.goto(0, 0)

        hit_ball.dy *= -1

        left_player += 1

        sketch.clear()

        sketch.write("Left_player : {} Right_player: {}".format(

                    left_player, right_player), align="center",

                    font=("Courier", 24, "normal"))

    if hit_ball.xcor() < -500:

        hit_ball.goto(0, 0)

        hit_ball.dy *= -1

        right_player += 1

        sketch.clear()

        sketch.write("Left_player : {} Right_player: {}".format(

                                left_player, right_player), align="center",

                                font=("Courier", 24, "normal"))


    if (hit_ball.xcor() > 360 and hit_ball.xcor() < 370) and (hit_ball.ycor() < right_pad.ycor()+40 and hit_ball.ycor() > right_pad.ycor()-40):

        hit_ball.setx(360)

        hit_ball.dx*=-1

        

    if (hit_ball.xcor()<-360 and hit_ball.xcor() >- 370) and (hit_ball.ycor() < left_pad.ycor()+40 and hit_ball.ycor() > left_pad.ycor()-40):

        hit_ball.setx(-360)

        hit_ball.dx*=-1

Brick Game

import pygame

pygame.init()

size = (600, 600)

display = pygame.display.set_mode(size)

pygame.display.set_caption("Brick Game")

floor = pygame.Rect(100, 550, 200, 10)

brick = pygame.Rect(50, 250, 10, 10)

score = 0

move = [1, 1]

continueGame = True

GREEN  = (28, 252, 106)

WHITE = (255, 255, 255)

BLACK = (0,0,0)

PINK = (252, 3, 152)

ORANGE= (252, 170, 28)

RED = (255, 0, 0)

b1 = [pygame.Rect(1 + i * 100, 60, 98, 38) for i in range(6)]

b2 = [pygame.Rect(1 + i * 100, 100, 98, 38) for i in range(6)]

b3 = [pygame.Rect(1 + i * 100, 140, 98, 38) for i in range(6)]

def draw_brick(bricks):

    for i in bricks:

        pygame.draw.rect(display, ORANGE, i)

while continueGame:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:

            continueGame = False

    display.fill(BLACK)

    pygame.draw.rect(display, PINK, floor)

    font = pygame.font.Font(None, 34)

    text = font.render("CURRENT SCORE: " + str(score), 1, WHITE)

    display.blit(text, (180, 10))


    # floor move

    if event.type == pygame.KEYDOWN:

        if event.key == pygame.K_RIGHT:

            if floor.x < 540:

                floor.x = floor.x + 3


        if event.key == pygame.K_LEFT:

            if floor.x > 0:

                floor.x = floor.x - 3

    draw_brick(b1)

    draw_brick(b2)

    draw_brick(b3)

    brick.x = brick.x + move[0]

    brick.y = brick.y + move[1]

    if brick.x > 590 or brick.x < 0:

        move[0] = -move[0]

    if brick.y <= 3:

        move[1] = -move[1]

    if floor.collidepoint(brick.x, brick.y):

        move[1] = -move[1]

    if brick.y >= 590:

        font = pygame.font.Font(None, 74)

        text = font.render("Game Over!", 1, RED)

        display.blit(text, (150, 300))

        font = pygame.font.Font(None, 50)

        text = font.render("YOUR FINAL SCORE: " + str(score), 1, GREEN)

        display.blit(text, (100, 350))

        pygame.display.flip()

        pygame.time.wait(5000)

        break;

    pygame.draw.rect(display, WHITE, brick)

    for i in b1:

        if i.collidepoint(brick.x, brick.y):

            b1.remove(i)

            move[0] = -move[0]

            move[1] = -move[1]

            score = score + 1

    for i in b2:

        if i.collidepoint(brick.x, brick.y):

            b2.remove(i)

            move[0] = -move[0]

            move[1] = -move[1]

            score = score + 1

    for i in b3:

        if i.collidepoint(brick.x, brick.y):

            b3.remove(i)

            move[0] = -move[0]

            move[1] = -move[1]

            score = score + 1

    if score == 18:

        font = pygame.font.Font(None, 74)

        text = font.render("YOU WON THE GAME", 1, GREEN)

        display.blit(text, (150, 350))

        pygame.display.flip()

        pygame.time.wait(3000)

        break;

    pygame.time.wait(1)

    pygame.display.flip()

pygame.quit