Posts

Showing posts from July, 2020

Get MAC Address In HexaDecimal Format In Python

''' #Universally Unique Identifiers UUID Module import uuid myMACID = uuid.getnode() print(myMACID) print(hex(myMACID)) print(hex(myMACID).replace('0x','')) print(hex(myMACID).replace('0x', '').upper()) mac_hex = hex(myMACID).replace('0x', '').upper() Formatted_MACID = '-'.join(mac_hex[i: i + 2] for i in range(0, 11, 2)) print(Formatted_MACID) ''' import uuid import random def Get_MACID(): macid = random.randint(111111111111111,999999999999999) #macid = 123658568936176 #Real MACID mac_hex = hex(macid).replace('0x', '').upper() Formatted_MACID = '-'.join(mac_hex[i: i + 2] for i in range(0, 11, 2)) return Formatted_MACID Formatted_MACID = Get_MACID() print(Formatted_MACID) ''' Physical Address ================== 3C-A8-2A-AD-80-47 70-77-81-13-2A-F0    707781132af0 70-77-81-13-2A-EF 123658568936176 0x707781132af0 707781132af0 70-77-8

Understanding Date and Time in Python

import datetime #Default format of Python Date and Time is YYYY-MM-DD HH:MM:SS:Milliseconds #Myformat is Date-Month-Year Hours:Minutes:Seconds myTimeFormat = '%d-%B-%Y %H:%M:%S' MySystemTime = datetime.datetime.now() print("Default Python Format :",MySystemTime) #Formatting the default python datetime format to our time format MyFormatSystemTime = MySystemTime.strftime(myTimeFormat) print("Date Time in My format is :",MyFormatSystemTime) ''' import datetime #Default format of Python Date and Time is YYYY-MM-DD HH:MM:SS:Milliseconds CurrentTime = datetime.datetime.now() print(CurrentTime) import time import calendar ticks = time.time() print(ticks) MyTime = time.localtime() print(MyTime) Cal = calendar.month(1982,10) print(Cal) #timeFormat = '%d-%m-%Y %H:%M:%S' #timeFormat = '%d/%m/%Y %H.%M' #timeFormat = '%d-%m-%y %H:%M:%S' #timeFormat = '%d-%b-%Y %H:%M:%S' timeFormat = '%d-

Variables In Python

a = 1 print(a) print(type(a)) a = 3.14 print(a) print(type(a)) a = "Python Programming" print(a) print(type(a))

Dictionaries In Python

''' {} - Dictionary in Python is a Key Value(s) Pair [] - List () - Tuple ''' MyDictData = {'Name':['Durgesh','Indrasen', 'Chandan Pandey', 'Premchand'],'CGPA':[9.83,9.79,9.62,7.25]} print(MyDictData)

String Interning In Python

''' #Example for String interning in python string1 = 'Nagaraju' print('String 1 is:',string1 ,'and its ID is',id(string1)) string2 = 'nagaraju' print('String 2 is:',string2 ,'and its ID is',id(string2)) string3 = 'Nagaraju' print('String 3 is:',string3 ,'and its ID is',id(string3)) string4 = 'nagaraju' print('String 4 is:',string4 ,'and its ID is',id(string4)) ''' #Multiple Line Comments are written as ''', ''' import time #Example to show the comparison of String comparision with the String's Indetity comparison def compare_with_equality_operator(n): string1 = 'Python_Programming'*5000 string2 = 'Python_Programming'*5000 for i in range(n): if string1 == string2: pass def compare_identity_with_IS_operator(n): string1 = 'Python_Programming'*5000 string2 = 'Python_Programming'*

Server File Video Transfer Using Python

import socket import threading import os def RetrFile(name,sock): print('control is before receiving the file name from client') filename = sock.recv(1024).decode() print('control is after receving the file name from client') print('The file name received from the client is :'+filename) if os.path.isfile(filename): print('Inside the IF of server code') msg = "EXISTS:"+str(os.path.getsize(filename)) print(msg) sock.send(msg.encode()) userResponse = sock.recv(1024).decode() print("The client responsed as :"+userResponse[:2]) if userResponse[:2] == 'OK': with open(filename,'rb') as f: bytesToSend = f.read(1024) sock.send(bytesToSend) while (bytesToSend): bytesToSend = f.read(1024) sock.send(bytesToSend) else: sock.send("ERR".encode()) sock.close() def Main(): host = socket.gethostname() port = 5000 s = socket.socket(socket.AF_I

Server File Transfer Using Python

import socket import threading import os def RetrFile(name,sock): print('control is before receiving the file name from client') filename = sock.recv(1024).decode() print('control is after receving the file name from client') print('The file name received from the client is :'+filename) if os.path.isfile(filename): print('Inside the IF of server code') msg = "EXISTS:"+str(os.path.getsize(filename)) print(msg) sock.send(msg.encode()) userResponse = sock.recv(1024).decode() print("The client responsed as :"+userResponse[:2]) if userResponse[:2] == 'OK': with open(filename,'rb') as f: bytesToSend = f.read(1024) sock.send(bytesToSend) while (bytesToSend): bytesToSend = f.read(1024) sock.send(bytesToSend) else: sock.send("ERROR".encode()) else: sock.send("File Does not Exist".encode()) sock.close() def Main(): host =

Reading CSV File Using Python

import os import csv import time myCSVFileName = input('Enter a CSV Filename to read its contents: ') fileExists = os.path.isfile(myCSVFileName) if (fileExists): print(myCSVFileName, 'exists') recordsList = []#Creates a empty list called as recordsList print(recordsList)#Prints Empty List with open(myCSVFileName,'r') as csvFileObject:#open a file in read mode, and execute line 13 -19 myDictReader = csv.DictReader(csvFileObject)#Reading the contents in the form of Dictionary print(myDictReader) for eachLine in myDictReader: print(eachLine) print('\n') recordsList.append(eachLine) time.sleep(1) print(recordsList) else: print(myCSVFileName,' does not exist')

Loading CSV File Into DataBase Table Using Python

import pymysql import csv import os myCSVFileName= input('Enter a Filename: ') fileExists = os.path.isfile(myCSVFileName) myDBConnectObject = pymysql.connect('127.0.0.1','test','test123','scet-autonomous') if fileExists: print(myCSVFileName,' exist to load in to the Database Table') myCursorObject = myDBConnectObject.cursor() createTableQuery = 'create table if not exists SCETDATASETTABLE (REGISTRATION_NUMBER bigint,STUDENT_NAME varchar(50),STUDENT_GENDER VARCHAR(20),STUDENT_DEPARTMENT VARCHAR(20),STUDENT_CGPA float(4,2),STUDENT_EMAILID varchar(50), STUDENT_CONTACT_NUMBER bigint)' myCursorObject.execute(createTableQuery) record = [] with open(myCSVFileName,'r') as csvFileObject: reader = csv.DictReader(csvFileObject) for line in reader: record.append(line) for i in range(0,5000): Col1 = record[i]['REGISTRATION_NUMBER'] Col2 = record[i]['STUDENT_NAME']

Integer Caching in Python

import platform cacheBegin, cacheEnd = 0, 0 print(cacheBegin) print(cacheEnd) for i in range( -500, 0): if i is int(str(i)): cacheBegin = i break for i in range( cacheBegin, 500 ): if i is not int(str(i)): cacheEnd = i - 1 break print( "Python version: {} implementation: {}".format( platform.python_version(), platform.python_implementation() ) ) print( "This implementation caches integers {} to {}".format( cacheBegin, cacheEnd ) )

Finding a File Using Python

#Searching an existence of a file in Current directory import os #myFileName = 'UnderstandLists.py' #isfile() returns a boolean value True if file is available #isfile() returns a boolean value False if file is not available #fileExists = os.path.isfile(myFileName) #print(fileExists) myFileName = input('Enter a File Name to search:  ') fileExists = os.path.isfile(myFileName) if(fileExists): print(myFileName, 'is available') else: print(myFileName, 'is not available')

File Copying In Python

import os #reading the source file from the standard input device i.e., keyboard sourceFileName = input('Enter the Source filename: ') #verifying the existence of the source file fileExists = os.path.isfile(sourceFileName) if not fileExists: print(sourceFileName," does not exist") else: #logic for creating a duplicate file name with source filename ending with string _Duplicate_File print(sourceFileName," is available for copying") tempFileName = sourceFileName.split('.') print(tempFileName) print('The source filename is: ',tempFileName[0]) print('The source file extension is: ',tempFileName[1]) destinationFileName = tempFileName[0]+'_Duplicate_File.'+tempFileName[1] print('The destination file name created is: ',destinationFileName) #reading the source file contents through the source file object named as fileReadObject fileReadObject = open(sourceFileName,'r') sourceFileC

Create Student Dataset CSV File

import csv import os import random import names delimiter = ',' myCSVFileName = input('Enter a CSV Filename: ') fileExists = os.path.isfile(myCSVFileName) #Open the CSV File in append mode for creating the header when file does not exist, with open(myCSVFileName,'a',newline='') as appendInToCSVFile: csvHeader = ['REGISTRATION_NUMBER','STUDENT_NAME','STUDENT_GENDER','STUDENT_DEPARTMENT','STUDENT_CGPA','STUDENT_EMAILID','STUDENT_CONTACT_NUMBER'] MyHeader = csv.DictWriter(appendInToCSVFile,fieldnames=csvHeader) print(MyHeader) if not fileExists: MyHeader.writeheader() ID = 1 while (ID <= 3): studentId = ID appendInToCSVFile.write(str(studentId)) appendInToCSVFile.write(delimiter) firstName = names.get_first_name() lastName = names.get_last_name() studentName = firstName+' '+lastName appendInToCSVFile.write(studentName) appendInToCSVFile.wr

Create Sample Student Data Using Python

mport names import random regNum = 1001 while(regNum <=1003): firstName = names.get_first_name() lastName = names.get_last_name() studentName = firstName+' '+lastName studentGender = random.choice(['Male','Female']) studentDepartment = random.choice(['CSE','ECE','EEE','Mechanical','Civil','EIE']) emailTag = random.choice(['@gmail.com','@yahoo.co.in','@rediffmail.com','@hotmail.com']) studentEmail = firstName+lastName+emailTag studentContact = random.randint(9986000000,9986999999) print(regNum,studentName,studentGender,studentDepartment,studentEmail,studentContact) regNum = regNum+1 ''' import names import random regNum = 1001 while(regNum <=1003): #studentName = names.get_full_name() firstName = names.get_first_name() lastName = names.get_last_name() studentName = firstName+' '+lastName studentGender = random.choice([&

Client Get Video File From Server USing Python

import socket import io import cv2 import numpy def Main(): host = socket.gethostname() port = 5000 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect((host,port)) filename = input("Filename?-> ") if filename != 'q': s.send(filename.encode()) data = s.recv(1024).decode() if data[:6] == 'EXISTS': filesize = (data[7:]) message = input("File Exists, "+str(filesize)+"Bytes, download? (Y/N)? -> ") if message == 'Y': s.send('OK'.encode()) fd = open('new_'+filename,'wb') data = s.recv(1024) totalRecv = len(data) print('The totalRecv has a value: '+str(totalRecv)) print('The type of totalRecv is: '+str(type(totalRecv))) print('The filesize has a value: '+filesize) print('The type of filesize is :'+str(type(filesize))) print('The type of data is:  '+str(type(data))) fd.wr

Chat Client Program Using Python

import socket HOST = socket.gethostname() PORT = 2020 PROTOCOL = socket.AF_INET SOC_TYPE = socket.SOCK_STREAM ENCODING = 'ascii' BUFFER = 4096 server = socket.socket(PROTOCOL, SOC_TYPE) print("Client setup complete.") server.connect((HOST, PORT)) print("Server connect successfull.\n Waiting for Server to join the conversation.\n") msg = server.recv(BUFFER) print("Welcome message from server: \n",msg.decode(ENCODING)) print("Press 'exit' at any time  to exit the chat.") print("Press 'Enter' at any time to wait for other person's reply!\n (NOTE: If other person is doing this then you will enter an infinte wait!!)") # Speaks before listening. while True:     msg_to_send = input("Me: ")     if msg_to_send == 'exit':         server.send("exit".encode(ENCODING))         server.close()         print("Closed connection.")         break     elif msg_

Java Basics1

class Tejanth {       void sample() {   System.out.println("tejanth"); } } class Maple {    Tejanth s=new Tejanth();    s.sample(); }

Python Basics8(Threading)

import threading.*; class Thread1(threading.thread) :  def run(self) :    for i in range(10) :     print("thread1"+str(i));     time.sleep(2); t1=Thread1(); t1.start();

Python Basics7(init method2)

class GrandParent():  def __init__(self,h):   self.house=h; def GrandParentproperties(self):  print("grandparent house is"+self.house); class Parent(GrandParent):  def __init__(self,h,c):   self.house=h;   self.car=c; def Parentproperties(Self):  print("Parent house is"+self.house);  print("Parent house is"+self.car); sub1=Parent('duplexhouse','honda'); sub1.Parentproperties(); sub1.GrandParentproperties();

Python Basics6(init method)

class pythonTraining :  def__init__(self,a,b) :   print("my name is tejanth");   self.pen=a;   self.book=b;  def.display(self):   print("my book is "+self.book);   print("my pen is"+self.pen); #object creation x=pythontraining('parker','whitenote'); x.dispaly(); y=pythontraining('reynolds','rulenotebook'); y.display();

Python Basics5 (instance and class methods)

class pythontraining :  board="whiteboard"; #class variable def bookwriting(self,name) :#instance methods  print("bookwriting is"+str(name)); def listening(self,name) :#instance methods  print("listening is"+str(name)); def understanding(self,percentage) :#instance methods  print("understanding is"+str(name)); def boardreading(cls) :#class method  print("class method") x=pythontraining(); #object x x.pen="parker"; x.book="rule"; x.bookwriting(x.pen); x.understanding('90%'); y=pythontraining(); y.pen="reynolds" y.book="white notebook"; y.bookwriting(y.pen); y.understanding('80%') print(pythontraining.board) pythontraining.bookreading();

Python Basics4 (functions,lambdafunction)

def sum(a=10,b=20) :  add=a+b;  return add; print("sum is",sum()) f=lambda a,b:a+b print(f(10,20)) f=open("sample.txt",'r') a=f.readline(5) f.close() print(a)

Python Basics3( for loop,lists,tuples)

print(x); print(y); for i in range(11) :  print('i value is',i) for i in range(0,5,3) :  print(i) s=(10,20,30) for i in s :  print(i) if(x==10) :  pass s="abcd" print(s[0]) s=(1,2,"hello","santosh") print(s[0:3]) s=[50,10] s1=[20,5] print(s<s1) s=[1,2,"hello","santosh"]; print(s[0]); x={'country':'india','channel':'telugu'} print(x['country']) #del x['channel'] print(x['channel']) x.clear(); print(x['country']) del x print(x['channel'])

Python Basics2

x=input("enter a value"); y=input("enter a value") print (x+y) x="my name is tejanth"\   "tejanth is my name" print (x);

Python Basics1

x=10 if(x==10) :  print("x value is 10"); else :  print("x value is not 10");

HTML Basics

<!DOCTYPE html> <html> <body> <pre>  tejanth is a good boy  persuing btech  in swarnandhra college of engineering in narsapur <pre> <p>time &nbsp; computers</p> <p>&copy; time computers</p> </body> <head> <style> body {   background-image:       url('https://pixteller.com/templates/custom-visuals/simple-background-backgrounds-passion-id1585819');       background-repeat: no-repeat; } </body> </style> </head> <body>My First Webpage</body><br></br><br></br> <a  href ="http://google.com"  title="gotogoogle"> google</a><br></br><br></br> TEAM MEMBERS:<select name="team members" id="team members"><option>members</option>+ <option>TEJANTH</option><option>BINDU</option><option>khyathi</option><opt

Tables in HTML

<html> <body> <hr.color="red"> <caption>SELFRESPECT</caption> <table border="5" allign="left" bgcolor="pink" cellspacing="5"> <th>firstname</th> <th>lastname</th> <tr>  <td>tejanth</td>  <td>atyam</td> </tr> </table> <table border="6"> <tr> <td colspan="3">winner team of cricket></td> </tr> </table> </body> </html>

iframes in HTML

<html> <body> <iframe src="basics.html" width="200" height="200">  </iframe> </body> </html>

Registration Form using HTML

<html> <body bgcolor="wheat"> <marquee bgcolor="red" width="100%" height="80px"><font size="15">THE ELITE</font></marquee> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body {   margin: 0;   font-family: Arial, Helvetica, sans-serif; allign:right } .topnav {   overflow: hidden;   background-color:#FF0000; } .topnav a {   float: right;   color: #f2f2f2;   text-align: center;   padding: 14px 16px;   text-decoration: none;   font-size: 15px; } .topnav a:hover {   background-color: #ddd;   color: black; } .topnav a.active {   background-color: #4CAF50;   color: white; } </style> </head> <body> <div class="topnav" > <b>TEAM MEMBERS:</b><select name="team members" id="team members"><option>members&l