Wednesday, May 20, 2020

Write a Python program to create a dictionary of students and display the content of the dictionary in alphabetical order

Python program to accept two strings and check if second string is prefix of first


str1 = input("enter the string")
str2 = input("enter the sub string")

flag =0


if len(str1) > len(str2):
    for i in range(0,len(str2)):
        #print(i)
        if str1[i] == str2[i]:
            pass
            #i=i+1
        flag=flag+1
        
print(str1,str2,end="\n")
print("matched at position{}".format(flag))

output:
enter the stringsubject

enter the sub stringsub
subject sub
matched at position3

openGL using cube in python

import pygame
from pygame.locals import *

from OpenGL.GL import *
from OpenGL.GLU import *

verticies = (
    (1, -1, -1),
    (1, 1, -1),
    (-1, 1, -1),
    (-1, -1, -1),
    (1, -1, 1),
    (1, 1, 1),
    (-1, -1, 1),
    (-1, 1, 1),
    )

edges = (
    (0,1),
    (0,3),
    (0,4),
    (2,1),
    (2,3),
    (2,7),
    (6,3),
    (6,4),
    (6,7),
    (5,1),
    (5,4),
    (5,7),
    )

surfaces = (
    (0,1,2,3),
    (3,2,7,6),
    (6,7,5,4),
    (4,5,1,0),
    (1,5,7,2),
    (4,0,3,6)    
    )




def Draw_Cube():

    glBegin(GL_QUADS)
    for surface in surfaces:
        for vertex in surface:
            glColor3fv((0,1,1))
            glVertex3fv(verticies[vertex])
    
    glEnd()


    
    glBegin(GL_LINES)
    for edge in edges:
        for vertex in edge:
            glColor3fv(( 1, 1,1))
            glVertex3fv(verticies[vertex])
    glEnd()


def main():
    pygame.init()
    display = (800,600)

    pygame.display.set_mode(display, DOUBLEBUF|OPENGL)

    
    #
    gluPerspective(90.0, (display[0]/display[1]), 0.1, 50)

    # moving back. 
    glTranslatef(0.0,0.0,-5.0)

    # where we might be
    glRotatef(20, 2, 0, 0)

    while True:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            if event.type == pygame.MOUSEBUTTONDOWN:
                print(event)
                print(event.button)

                if event.button == 4:
                    glTranslatef(0.0,0.0,1.0)
                elif event.button == 5:
                    glTranslatef(0.0,0.0,-1.0)

                    


        glRotatef(1, 3, 1, 1) 
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
        Draw_Cube()
        pygame.display.flip()
        pygame.time.wait(10)

main()

            
    




























Monday, May 18, 2020

tkinter pack functions


from tkinter import *

root = Tk()
root.geometry("800x600")

Label(root, text="heading1", relief=GROOVE).pack(side=LEFT, fill=BOTH, expand=True)
Label(root, text="heading2", relief=GROOVE).pack(side=BOTTOM, fill=BOTH, expand=True)
for i in range(5):
    Label(root, text=str(i), relief=GROOVE).pack(side=RIGHT,fill=BOTH, expand=True)
root.mainloop()
tkinter pack


Wednesday, May 6, 2020

canon model game coding using python language

"""Cannon, hitting targets with projectiles.

Exercises

1. Keep score by counting target hits.
2. Vary the effect of gravity.
3. Apply gravity to the targets.
4. Change the speed of the ball.

"""

from random import randrange
from turtle import *
from base import vector

ball = vector(-200, -200)
speed = vector(0, 0)
targets = []

def tap(x, y):
    "Respond to screen tap."
    if not inside(ball):
        ball.x = -199
        ball.y = -199
        speed.x = (x + 200) / 25
        speed.y = (y + 200) / 25

def inside(xy):
    "Return True if xy within screen."
    return -200 < xy.x < 200 and -200 < xy.y < 200

def draw():
    "Draw ball and targets."
    clear()

    for target in targets:
        goto(target.x, target.y)
        dot(20, 'blue')

    if inside(ball):
        goto(ball.x, ball.y)
        dot(8, 'red')

    update()

def move():
    "Move ball and targets."
    if randrange(40) == 0:
        y = randrange(-150, 150)
        target = vector(200, y)
        targets.append(target)

    for target in targets:
        target.x -= 0.5

    if inside(ball):
        speed.y -= 1
        ball.move(speed)

    dupe = targets.copy()
    targets.clear()

    for target in dupe:
        if abs(target - ball) > 13:
            targets.append(target)

    draw()

    for target in targets:
        if not inside(target):
            return

    ontimer(move, 50)

setup(420, 420, 370, 0)
hideturtle()
up()
tracer(False)
onscreenclick(tap)
move()
done()

ant model python game programming



from random import*
from turtle import*

from base import vector

ant = vector(0,0)
aim = vector(2,0)

def wrap(value):
    return value

def draw():
    ant.move(aim)
    ant.x = wrap(ant.x)
    ant.y = wrap(ant.y)
    aim.move(random()-0.5)
    
    aim.rotate(random()*10-5)
    clear()
    
    goto(ant.x,ant.y)
    dot(4)
    if running:
        ontimer(draw,100)
        

setup(600,400,370,0)
hideturtle()
tracer(False)
up()
running = True
draw()
done()

python game programming from scratch

# -*- coding: utf-8 -*-
"""
Created on Wed May  6 07:12:50 2020

@author: Onyx1
"""

import collection
import math
import sos


def path(filename):
    filepath = os.path.realpath(__file__)
    dirpath = os.path.dirname(filepath)
    fullpath = os.path.join(dirpath,filename)
    return fullpath

def line(a,b,x,y):
    import turtle
    turtle.up()
    turtle.goto(a,b)
    turtle.down()
    turtle.goto(x,y)
    
class Vector(collection.sequence):
    PRECISION = 6
    __slots__ =('_x','_y','_hash')
    
    def __init__(self,x,y):
        self.hash =None
        self._x = round(x,self.PRECISION)
        self._y = round(y,self.PRECISION)
        
    @property
    #getter
    def x(self):
        return self._x
    
    @x.setter
    def x(self,value):
        if self._hash is not None:
            raise ValueError("Cannot set x after hasing")
        self._x = round(value,self.PRECISION)
    
    
    @property
    #getter
    def y(self):
        return self._y
    
    @y.setter
    def y(self,value):
        if self._hash is not None:
            raise ValueError("Cannot set y after hasing")
        self._y = round(value,self.PRECISION)
        
    def __hash__(self):
        if self._hash is None:
            pair = (self.x,self.y)
            self._hash= hash(pair)
            
            return self._hash
        
    def __len__(self):
        return 2
    
    def __getitem__(self,index):
        if index == 0:
            return self.x
        elif index == 1:
            return self.y
        else:
            raise IndexError
            
    def copy(self):
        type_self = type(self)
        return type_self(self.x,self.y)
    
    def __eq__(self,vector):
        if isinstance(other,vector):
            return self.x == other.x and self.y == other.y
        return NotImplemented
    
    def __nq__(slef,other):
        if isinstance(other,vector):
            return self.x != other.x and self.y != other.y
        return NotImplemented
    
    def __iadd__(self,other):
        if self._hash is not None:
            raise ValueError("cannot add vector after hashing")
        elif isinstance(other,vector):
            self.x = other.x
            self.y = other.y
        else:
            self.x += other
            self.y += other
        return self
    
    def __add__(self,other):
        copy = self.copy()
        return copy.__iadd__(other)
    
    __radd__ = __add__
    
    def move(self,other):
        self.__iadd__(other)
        
    def __isub__(self,other):
        if self._hash is not None:
            raise ValueError("cannot substract vector hashing")
        elif isinstance(other,vector):
            self.x -= other.x
            self.y -= other.y
        
        else:
            self.x -= other
            self.y -= other
        return  self
    
    def __sub__(self,other):
        copy = self.copy()
        return copy.__isub__(other)
    
    def __imul__(self,other):
         if self._hash is not None:
            raise ValueError("cannot multiply  vector hashing")
        elif isinstance(other,vector):
            self.x *= other.x
            self.y *= other.y
        
        else:
            self.x *= other
            self.y *= other
        return  self
    
    def __mul__(self,other):
        copy = self.copy()
        return copy.__imul__(other)
    
    __rmul__ = __mul__
    
    def scale(self,other):
        self.__imul__(other)
    
    def __itruediv__(self,other):
        if self._hash is not None:
            raise ValueError("cannot divide vector hashing")
        elif isinstance(other,vector):
            self.x /= other.x
            self.y /= other.y
        
        else:
            self.x /= other
            self.y /= other
        return  self
    
    def __truediv__(self,other):
        copy = self.copy()
        return copy.__itruediv__(other)
    
    def __neg__(self,other):
        copy = self.copy()
        copy.x = -copy.x
        copy.y = -copy.y
        return copy
    
    def __abs__(self):
        return (self.x**2+self.y**2)**0.5
    
    def rotate(self,angle):
        if self._hash is not None:
            raise ValueError("Cannot rotate  vector after hasing")
        radians = angle*math.pi/180.0
        cosine = math.cos(radians)
        sine = math.sin(radians)
        
        x = self.x
        y =self.y
        
        self.x = x*cosine-y*sine
        self.y = x*cosine+y*sine
        
        
    def __repr__(self):
        type_self = type(self)
        name = type_self.__name__
        return '{}({!r}{!r})'.format(name,self.x,self.y)
    
                
        

Tuesday, May 5, 2020

STM32F407VET6 bare metel led blink code

#include "stm32f4xx.h"
#include "stm32f4xx_gpio.h"

void Delay()
{
  
for(int i=0;i<500000;i++);
}
int main()
{
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
GPIOA -> MODER |= GPIO_MODER_MODER6_0;
// GPIOA -> MODER |= GPIO_MODER_MODER8_0;
while(1)
{
GPIOA -> ODR |= 0x00000040 ;//GPIO_ODR_6;
Delay();
GPIOA -> ODR &= ~0x00000040;
Delay();
}

}

Friday, May 1, 2020

stm32f407vet6 led toggle code working

/* USER CODE END WHILE */
//HAL_GPIO_TogglePin(GPIOA,GPIO_PIN_5|GPIO_PIN_6|GPIO_PIN_7);
//HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_RESET);
// HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,0);

HAL_Delay(1000);
//HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_SET);
//HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,1);
HAL_GPIO_TogglePin(GPIOA,GPIO_PIN_4);
HAL_Delay(1000);
HAL_GPIO_TogglePin(GPIOA,GPIO_PIN_6);
HAL_Delay(1000);
HAL_GPIO_TogglePin(GPIOA,GPIO_PIN_7);

Wednesday, April 29, 2020

vector multiplication in machine learning using python

# add vectors
from numpy import array
a = array([1, 2, 3])
print(a)
b = array([1, 2, 3])
print(b)
c = a + b
print(c)
[1 2 3]
[1 2 3]
[2 4 6]
In [2]:
print(type(c))
<class 'numpy.ndarray'>
In [3]:
d=array([4,5,6])
e=array([1,2,3])
f=d-e
print(f)
[3 3 3]
In [4]:
g=a/b
print(g)
[1. 1. 1.]
In [5]:
#vector multiplication
h=d*e
print(h)
[ 4 10 18]
In [6]:
# vector-scalar multiplication
from numpy import array
a = array([1, 2, 3])
print(a)
s = 0.5
print(s)
c = s * a
print(c)
[1 2 3]
0.5
[0.5 1.  1.5]
In [ ]:
 

Monday, April 27, 2020

entry with three form fields using tkinter in python

from tkinter import *
import pymysql


def create_table():
    conn=pymysql.connect(host="localhost",user="root",password="",db="sslabs")
    mycursor=conn.cursor()
    #mycursor.execute("CREATE TABLE student2 (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255),standard VARCHAR(255), sub VARCHAR(255) )")
    sql = "INSERT INTO student2 (name, standard,sub) VALUES (%s, %s,%s)"
 
    #print("First Name: %s\nstandard:%s\nsubject:%s" % (e1.get(),e2.get(),e3.get()))
    name=e1.get()
    standard=e2.get()
    sub=e3.get()
    val = (name, standard, sub)
    mycursor.execute(sql, val)
    conn.commit()
    print(mycursor.rowcount, "record inserted.")

def show_entry_fields():
    #print("First Name: %s\nstandard:%s\nsubject:%s" % (e1.get(),e2.get(),e3.get()))
    query = "SELECT * FROM student2"
    ## getting records from the table
    mycursor.execute(query)
    ## fetching all records from the 'cursor' object
    records = mycursor.fetchall()
    ## Showing the data
    for record in records:
        print(record)

master=Tk()
master.title("Basic Entry Widget")


Label(master , text="First Name").grid(row=0)
Label(master , text="standard").grid(row=1)
Label(master , text="sub").grid(row=2)

e1=Entry(master)
name=e1.grid(row=0,column=1)
e2=Entry(master)
standard = e2.grid(row=1,column=1)
e3=Entry(master)
sub = e3.grid(row=2,column=1)

Button(master,text='Quit', command=master.quit).grid(row=3,column=0,sticky=W,pady=4)
Button(master,text='Show', command=show_entry_fields).grid(row=3,column=1,sticky=W,pady=4)
Button(master,text='Insert', command=create_table).grid(row=3,column=2,sticky=W,pady=4)


mainloop()






 








python class topic video