Saturday, May 30, 2020

list operation in python

if __name__ == '__main__':
    N = int(input())
    list=[]
    list.insert(0,5)
    list.insert(1,10)
    list.insert(0,6)
    print(list)
    list.remove(6)
    list.append(9)
    list.append(1)
    list.sort()
    print(list)
    list.pop()
    list.reverse()
    print(list)

pattern display in python

thickness = int(input()) #This must be an odd number
c = 'H'

#Top Cone
for i in range(thickness):
    print((c*i).rjust(thickness-1)+c+(c*i).ljust(thickness-1))
    
#Top Pillars
for i in range(thickness+1):    
    print((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6))

#Middle Belt
for i in range((thickness+1)//2):
    print((c*thickness*5).center(thickness*6))    

#Bottom Pillars
for i in range(thickness+1):
    print((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6))    

#Bottom Cone
for i in range(thickness):
    print(((c*(thickness-i-1)).rjust(thickness)+c+(c*(thickness-i-1)).ljust(thickness)).rjust(thickness*6))



  •     H    
  •    HHH   
  •   HHHHH  
  •  HHHHHHH 
  • HHHHHHHHH
  •   HHHHH               HHHHH             
  •   HHHHH               HHHHH             
  •   HHHHH               HHHHH             
  •   HHHHH               HHHHH             
  •   HHHHH               HHHHH             
  •   HHHHH               HHHHH             
  •   HHHHHHHHHHHHHHHHHHHHHHHHH   
  •   HHHHHHHHHHHHHHHHHHHHHHHHH   
  •   HHHHHHHHHHHHHHHHHHHHHHHHH   
  •   HHHHH               HHHHH             
  •   HHHHH               HHHHH             
  •   HHHHH               HHHHH             
  •   HHHHH               HHHHH             
  •   HHHHH               HHHHH             
  •   HHHHH               HHHHH             
  •                     HHHHHHHHH 
  •                      HHHHHHH  
  •                       HHHHH   
  •                        HHH    
  •                         H     

Monday, May 25, 2020

MM32 product search table is working


from tkinter import Toplevel, Button, Tk, Menu  
from tkinter import *
#import sqlite3
import pymysql
import tkinter.ttk as ttk
from view_product_info import*

  
master = Tk() 
conn=pymysql.connect(host="localhost",user="root",password="",db="sslabs")
mycursor=conn.cursor()


def entry_form(): 
    Label(master , text="Name",   font=('arial 12 bold'), justify=LEFT, fg='black').grid(row=0)
    Label(master , text="ArmVer", font=('arial 12 bold'), justify=LEFT, fg='black').grid(row=0,column=3)
    Label(master , text="Speed",  font=('arial 12 bold'), justify=LEFT, fg='black').grid(row=2)
    Label(master , text="Flash",  font=('arial 12 bold'), justify=LEFT, fg='black').grid(row=2,column=3)
    Label(master , text="RAM",    font=('arial 12 bold'), justify=LEFT, fg='black').grid(row=4)
    Label(master , text="GPIO",   font=('arial 12 bold'), justify=LEFT, fg='black').grid(row=4,column=3)
    Label(master , text="AdvTimer", font=('arial 12 bold'), justify=LEFT, fg='black').grid(row=6)
    Label(master , text="GPTM",   font=('arial 12 bold'), justify=LEFT, fg='black').grid(row=6,column=3)
    Label(master , text="WDG",    font=('arial 12 bold'), justify=LEFT, fg='black').grid(row=8)
    Label(master , text="RTC",    font=('arial 12 bold'), justify=LEFT, fg='black').grid(row=9)
    Label(master , text="UART",   font=('arial 12 bold'), justify=LEFT, fg='black').grid(row=10)
    Label(master , text="I2C",    font=('arial 12 bold'), justify=LEFT, fg='black').grid(row=11)
    Label(master , text="SPI",    font=('arial 12 bold'), justify=LEFT, fg='black').grid(row=12)
    Label(master , text="USB",    font=('arial 12 bold'), justify=LEFT, fg='black').grid(row=13)
    Label(master , text="ADC",    font=('arial 12 bold'), justify=LEFT, fg='black').grid(row=14)
    Label(master , text="EEPROM", font=('arial 12 bold'), justify=LEFT, fg='black').grid(row=15)
    Label(master , text="DAC",    font=('arial 12 bold'), justify=LEFT, fg='black').grid(row=16)
    Label(master , text="CAN",    font=('arial 12 bold'), justify=LEFT, fg='black').grid(row=17)
    Label(master , text="SDIO",   font=('arial 12 bold'), justify=LEFT, fg='black').grid(row=18)
    Label(master , text="COMP",   font=('arial 12 bold'), justify=LEFT, fg='black').grid(row=19)
    Label(master , text="AES",    font=('arial 12 bold'), justify=LEFT, fg='black').grid(row=20)
    Label(master , text="TRNG",   font=('arial 12 bold'), justify=LEFT, fg='black').grid(row=21)
    Label(master , text="PACK",   font=('arial 12 bold'), justify=LEFT, fg='black').grid(row=22)
    
    e1=Entry(master)
    Name=e1.grid(row=0,column=1)
    
    e2=Entry(master)
    ArmVer = e2.grid(row=0,column=4)
    
    e3=Entry(master)
    Speed = e3.grid(row=2,column=1)
    
    e4=Entry(master)
    Flash = e4.grid(row=2,column=4)
    
    e5=Entry(master)
    RAM = e5.grid(row=4,column=1)
    e6=Entry(master)
    Gpio = e6.grid(row=4,column=4)
    
    e7=Entry(master)
    AdvTimer = e7.grid(row=6,column=1)
    e8=Entry(master)
    GPTM = e8.grid(row=6,column=4)
    e9=Entry(master)
    WDG = e9.grid(row=8,column=1)
    e10=Entry(master)
    RTC = e10.grid(row=9,column=1)
    
    e11=Entry(master)
    UART = e11.grid(row=10,column=1)
    
    e12=Entry(master)
    I2C = e12.grid(row=11,column=1)
    
    e13=Entry(master)
    SPI = e13.grid(row=12,column=1)
    
    e14=Entry(master)
    USB = e14.grid(row=13,column=1)
    
    e15=Entry(master)
    ADC = e15.grid(row=14,column=1)
    
    e16=Entry(master)
    EEPROM = e16.grid(row=15,column=1)
    
    e17=Entry(master)
    DAC = e17.grid(row=16,column=1)
    
    e18=Entry(master)
    CAN = e18.grid(row=17,column=1)
    
    e19=Entry(master)
    SDIO = e19.grid(row=18,column=1)
    
    e20=Entry(master)
    COMP = e20.grid(row=19,column=1)
    
    e21=Entry(master)
    AES = e21.grid(row=20,column=1)
    
    e22=Entry(master)
    TRNG = e22.grid(row=21,column=1)
    
    e23=Entry(master)
    PACK = e23.grid(row=22,column=1)

def create_table():
    mycursor.execute("CREATE TABLE `mm321` (id INT AUTO_INCREMENT PRIMARY KEY, Name VARCHAR(255),ArmVer VARCHAR(255), Speed VARCHAR(255), Flash VARCHAR(255) , RAM VARCHAR(255) , Gpio VARCHAR(255) , AdvTimer VARCHAR(255), GPTM VARCHAR(255), WDG VARCHAR(255),RTC VARCHAR(255),UART VARCHAR(255),I2C VARCHAR(255),SPI VARCHAR(255),USB VARCHAR(255),ADC VARCHAR(255),EEPROM VARCHAR(255),DAC VARCHAR(255),CAN VARCHAR(255),SDIO VARCHAR(255),COMP VARCHAR(255),AES VARCHAR(255),TRNG VARCHAR(255),PACK VARCHAR(255))")

def display_text():        
    sql = "INSERT INTO `mm321` (Name, ArmVer,Speed,Flash,RAM,Gpio,AdvTimer,GPTM,WDG,RTC,UART,I2C,SPI,USB,ADC,EEPROM,DAC,CAN,SDIO,COMP,AES,TRNG,PACK) VALUES (%s, %s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
    #print("First Name: %s\nstandard:%s\nsubject:%s" % (e1.get(),e2.get(),e3.get()))
    Name=e1.get()
    ArmVer=e2.get()
    Speed=e3.get()
    Flash=e4.get()
    RAM=e5.get()
    Gpio=e6.get()
    AdvTimer=e7.get()
    GPTM=e8.get()
    WDG=e9.get()
    RTC=e10.get()
    UART=e11.get()
    I2C=e12.get()
    SPI=e13.get()
    USB=e14.get()
    ADC=e15.get()
    EEPROM=e16.get()
    DAC=e17.get()
    CAN=e18.get()
    SDIO=e19.get()
    COMP=e20.get()
    AES=e21.get()
    TRNG=e22.get()
    PACK=e23.get()
    val = (Name, ArmVer, Speed,Flash,RAM,Gpio,AdvTimer,GPTM,WDG,RTC,UART,I2C,SPI,USB,ADC,EEPROM,DAC,CAN,SDIO,COMP,AES,TRNG,PACK)
    mycursor.execute(sql, val)
    conn.commit()
    print(mycursor.rowcount, "record inserted.")     
        

        
def Database():
        conn = pymysql.connect(host="localhost",user="root",password="",db="sslabs")
        cursor = conn.cursor()
        #cursor.execute("CREATE TABLE IF NOT EXISTS `mm321` (id INTEGER NOT NULL PRIMARY KEY  AUTOINCREMENT, firstname TEXT, lastname TEXT, address TEXT, age TEXT)")
        cursor.execute("SELECT * FROM `mm321`")
        '''if cursor.fetchone() is None:
            cursor.execute("INSERT INTO `mm321` (firstname, lastname, address, age) VALUES('Clea', 'Hela', 'San Francisco', '20')")
            cursor.execute("INSERT INTO `mm321` (firstname, lastname, address, age) VALUES('Thor', 'Jackson', 'San Aurora', '25')")
            cursor.execute("INSERT INTO `users1` (firstname, lastname, address, age) VALUES('Naruto', 'Uzumaki', 'Konoha', '18')")
            cursor.execute("INSERT INTO `users1` (firstname, lastname, address, age) VALUES('San', 'Juan', 'Peninsula', '55')")
            cursor.execute("INSERT INTO `users1` (firstname, lastname, address, age) VALUES('Juan', 'Dela Cruz', 'San Juan', '22')")
            cursor.execute("INSERT INTO `users1` (firstname, lastname, address, age) VALUES('Pedro', 'Bago', 'Bayan', '30')")
            ''' 
        conn.commit()
          
        cursor.execute("SELECT * FROM `mm321` ORDER BY `Name` ASC")
        fetch = cursor.fetchall()
        for data in fetch:
            tree.insert('', 'end', values=(data))
        cursor.close()
        conn.close()
    
def Search():
    if SEARCH.get() != "":
        tree.delete(*tree.get_children())
        conn = pymysql.connect(host="localhost",user="root",password="",db="sslabs")
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM `mm321` WHERE `Name` LIKE ? OR `ArmVer` LIKE ?", ('%'+str(SEARCH.get())+'%', '%'+str(SEARCH.get())+'%'))
        fetch = cursor.fetchall()
        for data in fetch:
            tree.insert('', 'end', values=(data))
        cursor.close()
        conn.close()
            
def Reset():
        conn = pymysql.connect(host="localhost",user="root",password="",db="sslabs")
        cursor = conn.cursor()
        tree.delete(*tree.get_children())
        cursor.execute("SELECT * FROM `mm321` ORDER BY `ArmVer` ASC")
        fetch = cursor.fetchall()
        for data in fetch:
            tree.insert('', 'end', values=(data))
        cursor.close()
        conn.close()
        
#=====================================VARIABLES============================================
SEARCH = StringVar()
    
#=====================================FRAME================================================
Top = Frame(master, width=500, bd=1, relief=SOLID)
Top.pack(side=TOP)
TopFrame = Frame(master, width=500)
TopFrame.pack(side=TOP)
TopForm= Frame(TopFrame, width=300)
TopForm.pack(side=LEFT, pady=10)
TopMargin = Frame(TopFrame, width=260)
TopMargin.pack(side=LEFT)
MidFrame = Frame(master, width=500)
MidFrame.pack(side=TOP)
    
#=====================================LABEL WIDGET=========================================
lbl_title = Label(Top, width=500, font=('arial', 18), text="Product Search Table")
lbl_title.pack(side=TOP, fill=X)
    
#=====================================ENTRY WIDGET=========================================
search = Entry(TopForm, textvariable=SEARCH)
search.pack(side=LEFT)
    
#=====================================BUTTON WIDGET========================================
btn_search = Button(TopForm, text="Search", bg="#006dcc", command=Search)
btn_search.pack(side=LEFT)
btn_reset = Button(TopForm, text="Reset", command=Reset)
btn_reset.pack(side=LEFT)
#=====================================Table WIDGET=========================================
scrollbarx = Scrollbar(MidFrame, orient=HORIZONTAL)
scrollbary = Scrollbar(MidFrame, orient=VERTICAL)
#Name, ArmVer, Speed,Flash,RAM
tree = ttk.Treeview(MidFrame, columns=("ID", "Name", "ArmVer", "Speed", "Flash","RAM","Gpio","AdvTimer","GPTM","WDG","RTC","UART","I2C","SPI","USB","ADC","EEPROM","DAC","CAN","SDIO","COMP","AES","TRNG","PACK"), selectmode="extended", height=400, yscrollcommand=scrollbary.set, xscrollcommand=scrollbarx.set)
scrollbary.config(command=tree.yview)
scrollbary.pack(side=RIGHT, fill=Y)
scrollbarx.config(command=tree.xview)
scrollbarx.pack(side=BOTTOM, fill=X)
tree.heading('ID', text="ID",anchor=W)
tree.heading('Name', text="Name",anchor=W)#1
tree.heading('ArmVer', text="ArmVer",anchor=W)#2
tree.heading('Speed', text="Speed",anchor=W)#3
tree.heading('Flash', text="Flash",anchor=W)#4
tree.heading('RAM', text="RAM",anchor=W)#5
tree.heading('Gpio', text="Gpio",anchor=W)#6
tree.heading('AdvTimer', text="AdvTimer",anchor=W)#7
tree.heading('GPTM', text="GPTM",anchor=W)#8
tree.heading('WDG', text="WDG",anchor=W)#9
tree.heading('RTC', text="RTC",anchor=W)#10
tree.heading('UART', text="UART",anchor=W)#11
tree.heading('I2C', text="I2C",anchor=W)#12#"SPI","USB","ADC","EEPROM","DAC","CAN","SDIO","COMP","AES","TRNG","PACK"
tree.heading('USB', text="USB",anchor=W)#13
tree.heading('ADC', text="ADC",anchor=W)#14
tree.heading('EEPROM', text="EEPROM",anchor=W)#15
tree.heading('DAC', text="DAC",anchor=W)#16
tree.heading('CAN', text="CAN",anchor=W)#17
tree.heading('SDIO', text="SDIO",anchor=W)#18
tree.heading('COMP', text="COMP",anchor=W)#19
tree.heading('AES', text="AES",anchor=W)#20
tree.heading('TRNG', text="TRNG",anchor=W)#21
tree.heading('PACK', text="PACK",anchor=W)#22
tree.column('#0', stretch=NO, minwidth=0, width=0)#1
tree.column('#1', stretch=NO, minwidth=0, width=0)#2
tree.column('#2', stretch=NO, minwidth=0, width=60)#3
tree.column('#3', stretch=NO, minwidth=0, width=60)#4
tree.column('#4', stretch=NO, minwidth=0, width=60)#5
tree.column('#5', stretch=NO, minwidth=0, width=40)#6
tree.column('#6', stretch=NO, minwidth=0, width=40)#7
tree.column('#7', stretch=NO, minwidth=0, width=40)#8
tree.column('#8', stretch=NO, minwidth=0, width=40)#9
tree.column('#9', stretch=NO, minwidth=0, width=40)#10
tree.column('#10', stretch=NO, minwidth=0, width=40)#11
tree.column('#11', stretch=NO, minwidth=0, width=40)#12
tree.column('#12', stretch=NO, minwidth=0, width=40)#13
tree.column('#13', stretch=NO, minwidth=0, width=40)#14
tree.column('#14', stretch=NO, minwidth=0, width=40)#15
tree.column('#15', stretch=NO, minwidth=0, width=40)#16
tree.column('#16', stretch=NO, minwidth=0, width=40)#17
tree.column('#17', stretch=NO, minwidth=0, width=40)#18
tree.column('#18', stretch=NO, minwidth=0, width=40)#19
tree.column('#19', stretch=NO, minwidth=0, width=40)#20
tree.column('#20', stretch=NO, minwidth=0, width=40)#21
tree.column('#21', stretch=NO, minwidth=0, width=40)#22
tree.column('#22', stretch=NO, minwidth=0, width=40)#22
tree.pack()

###########################################################################

menubar = Menu(master)  
file = Menu(menubar, tearoff=0)  
file.add_command(label="New",command=db_related.display_text)  
file.add_command(label="Open")  
file.add_command(label="Save")  
file.add_command(label="Save as...")  
file.add_command(label="Close")  
  
file.add_separator()  
  
file.add_command(label="Exit", command=master.quit)  
  
menubar.add_cascade(label="File", menu=file)  


edit = Menu(menubar, tearoff=0)  
edit.add_command(label="Undo")  
  
edit.add_separator()  
  
edit.add_command(label="Cut")  
edit.add_command(label="Copy")  
edit.add_command(label="Paste")  
edit.add_command(label="Delete")  
edit.add_command(label="Select All")  
  
menubar.add_cascade(label="Edit", menu=edit)  
help = Menu(menubar, tearoff=0)  
help.add_command(label="About")  
menubar.add_cascade(label="Help", menu=help)  

view = Menu(menubar, tearoff=0) 
view.add_command(label="View")
menubar.add_cascade(label="View", menu=view) 
master.config(menu=menubar)  

btn=Button(master, text="MM32", fg='blue')
btn.place(x=20, y=40)
btn=Button(master, text="Quectel", fg='blue')
btn.place(x=20, y=80)
btn=Button(master, text="Mornsun", fg='blue')
btn.place(x=20, y=120)

#=====================================INITIALIZATION=======================================
if __name__ == '__main__':
    Database()
    master.mainloop()  





Tkinter pack example


from tkinter import *

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

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

tkinter combobox postcommand example


A Python function that receives a three digit no and return the ones place value?

def ones_place_value(a):
    b =a%10;
    return b;


val= int(input("enter three digit number\n"))
c=ones_place_value(val)
print(c)

How to create train ticketing inventory management system in Python?

using tkinter library we can create train ticketing inventory system

for loop in python

list=("anil","shiva","maha")

for i in list:
    print(i)

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);

python class topic video