0% found this document useful (0 votes)
175 views64 pages

Apoorva Mehetre

The document outlines a lab journal submitted by Apoorva Mehetre covering Python programming and advanced internet technologies practical programs, with 15 sections describing programs implementing various Python concepts like data types, control flow, functions, object oriented programming, file handling, and data visualization.

Uploaded by

Apoorva Mehetre
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
175 views64 pages

Apoorva Mehetre

The document outlines a lab journal submitted by Apoorva Mehetre covering Python programming and advanced internet technologies practical programs, with 15 sections describing programs implementing various Python concepts like data types, control flow, functions, object oriented programming, file handling, and data visualization.

Uploaded by

Apoorva Mehetre
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

A

Lab

Journal Of

"Python Programming
&
“Advance Internet Technologies"

By

Apoorva Mehetre
Submitted in partial fulfillment of First
Year Master in Computer Application
Savitribai Phule Pune University

Under The Guidance

Of

Prof. Uday Deshmukh


&
Prof. Shubham Wadpalliwar

1
NAVIGATE TO :
1. PYTHON PRACTICALS

2. AIT PRACTICALS

2
INDEX1

PYTHON PROGRAMMING
SR. NO. TITLE PAGE NO.
1 Python installation and configuration with windows and 4
Linux.
2 Programs for understanding the data types, control flow 6
statements, blocks and loops.
3 Programs for understanding functions, use of built-in 10
functions, user defined functions
4 Programs to use existing modules, packages and 11
creating modules, packages
5 Programs for implementations of all object-oriented 12
concepts like class, method, inheritance, polymorphism etc.
(Real life examples must be covered for the implementation
of object oriented concepts)
6 Programs for parsing of data, validations like 15
Password, email, URL, etc.
7 Programs for Pattern finding should be covered. 18
8 Programs covering all the aspects of Exception handling, 19
user defined exception, Multithreading should be covered.

9 Programs demonstrating the IO operations like reading from 20


file, writing into file from different file types like data file,
binary file, etc.
10 Programs to perform searching, adding, updating the 21
content from the file
11 Program for performing CRUD operation with 23
MongoDB and Python
12 Basic programs with NumPy as Array, Searching and 25
Sorting, date & time and String handling
13 Programs for series and data frames should be 30
covered.
14 Programs to demonstrate data pre-processing and data 31
handling with data frame
15 Program for data visualization should be covered. 32

3
1. Python installation and configuration with windows and Linux.
How to install Python in Windows?

Python is the most popular and versatile language in the current scenario. Python doesn't
come with pre-package in Windows, but it doesn't mean that Window user cannot be flexible
with Python. Some operating systems such as Linux come with the Python package manager
that can run to install Python. Below are the steps to install Python in Windows.

Step - 1: Visit Official Site to Download Python Installer

o All Python-related information is available on its official website. First, open the
browser and visit the official site (www.python.org) to install Python installer. Here,
we can see the many Python installer versions, but we will download the latest version
of Python.

o It will take us on the above page. We can download the latest Python installer by
clicking on the Download button. We can also download the older version. Let's see
the following example.

4
Note - You can choose the Python installer according to your processor. If your system
processor has 32-bit, then download Python 32-bit installer, otherwise go with the 64-bit
version. If you are not sure about your processor, then download the 64-bit version.

Step -2 Install Python

o Once the download is completed, then run the installer by double-clicking on the
download file. It will ask for Add Python 3.8 to PATH. Click on the checkbox and
click on Install Now navigator.

Now Python is successfully installed in Windows, and you are ready to work with
Python.

(home)

5
2. Programs for understanding the data types, control flow statements, blocks and
loops.

CODE:

#PYTHON_DATA_TYPES

#1.Python_numbers a
=5
print(a, "is of type", type(a))

a = 2.0
print(a, "is of type", type(a))

a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))

#2.List
a = [5,10,15,20,25,30,35,40]

a[2] = 15
print("a[2] = ", a[2])

a[0:3] = [5, 10, 15]


print("a[0:3] = ", a[0:3])

a[5:] = [30, 35, 40]


print("a[5:] = ", a[5:])

#3.Tuple
t = (5,'program', 1+3j)

#t[1] = 'program'
#print("t[1] = ", t[1])

#t[0:3] = (5, 'program', (1+3j))


#print("t[0:3] = ", t[0:3])

#4.Set
a = {5,2,3,1,4}

# printing set variable


print("a = ", a)

# data type of variable a


print(type(a))

a = {1,2,2,3,3,3}
print(a)

#5.Dictionary
d = {1:'value','key':2}
print(type(d))

print("d[1] = ", d[1])

6
print("d['key'] = ", d['key'])

#string
s = "This is a string"
print(s)
s = '''A multiline
string'''
print(s)
print("\n")

#CONTROL FLOW STATEMENTS

#1.if condition
# If the number is positive, we print an appropriate message

num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")

num = -1 if
num > 0:
print(num, "is a positive number.")
print("This is also always printed.")

#2.if else condition


# Program checks if the number is positive or negative #
And displays an appropriate message
num = 3
if num >= 0: print("positive
or zero")
else:
print("negative number")

#3.if elif else condition


'''In this program,
we check if the number is positive or
negative or zero and
display an appropriate message'''

num = 3.4

if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
#4.nested if condition
'''In this program, we input a number
check if the number is positive or
negative or zero and display
an appropriate message
This time we use nested if statement'''

num = float(input("Enter a number: ")) if


num >= 0:
if num == 0:
print("Zero")

7
else:
print("Positive number")
else:
print("Negative number")

#Loops
#1.while loop

secret_number = 777

print(
"""
+================================+
| Welcome to my game, muggle! |
| Enter an integer number |
| and guess what number I've |
| picked for you. |
| So, what is the secret number? |
+================================+
""")

user_number = int(input("Enter the number: "))

while user_number != secret_number:


print("Ha ha! You're stuck in my loop!")
user_number = int(input("Enter the number again: "))
print(secret_number, "Well done, muggle! You are free now.")

#2.for loop
for second in range(1, 6):
print(second, "Mississippi")
print("Ready or not, here I come!")

#3.break and continue


largest_number = -99999999
counter = 0

number = int(input("Enter a number or type -1 to end program: "))

while number != -1:


if number == -1:
continue
counter += 1

if number > largest_number:


largest_number = number
number = int(input("Enter a number or type -1 to end program: "))

if counter:
print("The largest number is", largest_number)
else:
print("You haven't entered any number.")

8
OUTPUT:

(home)

9
3. Programs for understanding functions, use of built-in functions, user defined
functions.

CODE:
#example of built-in functions

print('Enter your name:') x


= input()
print('Hello, ' + x)

mylist = [True, True, True]


x = all(mylist)
print(x)

a = ("John", "Charles", "Mike")


b = ("Jenny", "Christy", "Monica")

x = zip(a, b)
print(x)

a1 = ('apple', 'banana', 'cherry') b2


= "Hello World"
c3 = 33

x = type(a1)
y = type(b2)
z = type(c3)
print(x, y, z)

# Program to demonstrate the #


use of user defined functions
#example1

def sum(a,b):
total = a + b
return total

x = 10
y = 20

print("The sum of",x,"and",y,"is:",sum(x, y))

#example2
def is_a_triangle(a, b, c): if
a + b <= c:
return False
if b + c <= a:
return False
if c + a <= b:
return False
return True

10
print(is_a_triangle(1, 1, 1))
print(is_a_triangle(1, 1, 3))

OUTPUT:

(home)

4. Programs to use existing modules, packages and creating modules,


packages.

CODE:
# importing sqrt() and factorial from the

# module math

from math import sqrt, factorial

# if we simply do "import math", then

# math.sqrt(16) and math.factorial()

# are required.

print(sqrt(16))

print(factorial(6))

D:\Python\Learn\venv\Scripts\python.exe D:/Python/Learn/main.py
4.0
720

# importing built in module random

import random
# printing random integer between 0 and 5

11
print(random.randint(0, 5))

# print random floating point number between 0 and 1

print(random.random())

# random number between 0 and 100

print(random.random() * 100)
List = [1, 4, True, 800, "python", 27, "hello"]
# using choice function in random module for choosing
# a random element from a set such as a list
print(random.choice(List))

D:\Python\Learn\venv\Scripts\python.exe D:/Python/Learn/main.py

OUTPUT:
1

0.9203095513570789

94.43468017867225

800

(home)

5. Programs for implementations of all object-oriented concepts like class, method,


inheritance, polymorphism etc. (Real life examples must be covered for the
implementation of objectoriented concepts.)

CODE:
#Creating Class and Object in Python
class Parrot:

# class attribute
species = "bird"

# instance attribute
def init (self, name, age):
self.name = name
self.age = age

# instantiate the Parrot class

12
blu = Parrot("Blu", 10)
woo = Parrot("Woo", 15)

# access the class attributes


print("Blu is a {}".format(blu. class .species)) print("Woo
is also a {}".format(woo. class .species))

# access the instance attributes


print("{} is {} years old".format( blu.name, blu.age))
print("{} is {} years old".format( woo.name, woo.age))

#Creating Methods in Python


class Parrot:

# instance attributes
def init (self, name, age): self.name =
name
self.age = age

# instance method def


sing(self, song):
return "{} sings {}".format(self.name, song)

def dance(self):
return "{} is now dancing".format(self.name)

# instantiate the object


blu = Parrot("Blu", 10)

# call our instance methods


print(blu.sing("'Happy'"))
print(blu.dance())

#Use of Inheritance in Python #


parent class
class Bird:

def init (self):


print("Bird is ready")

def whoisThis(self):
print("Bird")

def swim(self):
print("Swim faster")

# child class
class Penguin(Bird):

def init (self):


# call super() function
super(). init ()
print("Penguin is ready")

def whoisThis(self):
print("Penguin")

def run(self):

13
print("Run faster")

peggy = Penguin()
peggy.whoisThis()
peggy.swim()
peggy.run()

# Using Polymorphism in Python


class Parrot:

def fly(self):
print("Parrot can fly")

def swim(self):
print("Parrot can't swim")

class Penguin:

def fly(self):
print("Penguin can't fly")

def swim(self):
print("Penguin can swim")

# common interface
def flying_test(bird):
bird.fly()

# instantiate objects
blu = Parrot()
peggy = Penguin()

# passing the object


flying_test(blu)
flying_test(peggy)

OUTPUT:

14
(home)
6. Programs for parsing of data, validations like Password, email, URL, etc.

CODE:
# Python program to validate an Email

# import re module

# re module provides support


# for regular expressions
import re

# Make a regular expression


# for validating an Email
regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'

# Define a function for


# for validating an Email

def check(email):

# pass the regular expression


# and the string into the fullmatch() method
if(re.fullmatch(regex, email)):
print("Valid Email")

else:
print("Invalid Email")

# Driver Code
if name == ' main ':

# Enter the email

15
email = "[email protected]"

# calling run function


check(email)

email = "[email protected]"
check(email)

email = "ankitrai326.com"
check(email)

# Password validation in Python #


using naive method

# Function to validate the password def


password_check(passwd):
SpecialSym = ['$', '@', '#', '%']
val = True

if len(passwd) < 6:
print('length should be at least 6')
val = False

if len(passwd) > 20:


print('length should be not be greater than 8') val
= False

if not any(char.isdigit() for char in passwd):


print('Password should have at least one numeral') val =
False

if not any(char.isupper() for char in passwd):


print('Password should have at least one uppercase letter') val =
False

if not any(char.islower() for char in passwd):


print('Password should have at least one lowercase letter') val =
False

if not any(char in SpecialSym for char in passwd): print('Password


should have at least one of the symbols $@#') val = False
if val:
return val

# Main method
def main():
passwd = 'Geek12@'

if (password_check(passwd)):
print("Password is valid")
else:
print("Invalid Password !!")

# Driver Code
if name == ' main ':
main()

16
#Parsing and Processing URL using Python

# import library
import re

# url link
s = 'file://localhost:4040/abc_file'

# finding the file capture group


obj1 = re.findall('(\w+)://', s)
print(obj1)

# finding the hostname which may


# contain dash or dots
obj2 = re.findall('://([\w\-\.]+)', s)
print(obj2)

# finding the hostname which may


# contain dash or dots or port
# number
obj3 = re.findall('://([\w\-\.]+)(:(\d+))?', s)
print(obj3)

OUTPUT:

(home)

17
7. Programs for Pattern finding should be covered.

CODE:
import re

phoneValid = False

def phoneValidation():

phoneText = input('Enter Phone: ')

if re.compile(r'\+?\d[\d -]{8,12}\d').findall(phoneText) == []:

print('Please enter a valid phone number with code')

else:

print('Phone validated successfully. Good job!')

global phoneValid

phoneValid=True

return

while not phoneValid:

phoneValidation()

OUTPUT:

D:\Python\Learn\venv\Scripts\python.exe D:/Python/Learn/main.py
Enter Phone: 27412159
Please enter a valid phone number with code
Enter Phone: 02027412159
Phone validated successfully. Good job!

CODE:
import re

def validating_name(name):

regex_name = re.compile(r'^(Mr\.|Mrs\.|Ms\.) ([a-z]+)( [a-z]+)*( [a-


z]+)*$', re.IGNORECASE)

if regex_name.search(name):

print(f'{name} is valid')

18
else:

print(f'{name} is invalid')

validating_name('Mr. Albus Severus Potter')

validating_name('Lily and Mr. Harry Potter')

OUTPUT:
D:\Python\Learn\venv\Scripts\python.exe D:/Python/Learn/main.py
Mr. Albus Severus Potter is valid
Lily and Mr. Harry Potter is invalid

(home)

8. Programs covering all the aspects of Exception handling, user defined


exception, Multithreading should be covered.

CODE:
import re

class InvalidName(RuntimeError):

def init (self, arg):

self.args = arg

def validating_name(name):

regex_name = re.compile(r'^(Mr\.|Mrs\.|Ms\.) ([a-z]+)( [a-z]+)*( [a-


z]+)*$', re.IGNORECASE)

try:

if regex_name.search(name):

print(f'{name} is valid')

else:

raise InvalidName(name)

except InvalidName as e:

print(f'Error: {name} is invalid')

validating_name('Mr. Albus Severus Potter')

19
validating_name('Lily and Mr. Harry Potter')

D:\Python\Learn\venv\Scripts\python.exe D:/Python/Learn/main.py
Mr. Albus Severus Potter is valid
Error: Lily and Mr. Harry Potter is invalid

try:

a = int(input("Enter a:"))

b = int(input("Enter b:"))

c = a/b

print(f'{a} / {b} = {c}')

except:

print("Error : Can't divide with zero")

OUTPUT:
D:\Python\Learn\venv\Scripts\python.exe D:/Python/Learn/main.py
Enter a:10
Enter b:0
Error : Can't divide with zero

(home)

9. Programs demonstrating the IO operations like reading from file, writing into file
from different file types like data file, binary file, etc.

CODE:
#Open and closeing file in python

try:
f = open("Dev.txt", "r")
finally:
f.close()

#Writing to Files in Python

with open("Dev.txt",'w',encoding = 'utf-8') as f:


f.write("my first file\n")
f.write("This file\n\n")
f.write("contains three lines\n")

#Reading Files in Python


f = open("Dev.txt",'r',encoding = 'utf-8')

content = f.read()
print(content)

#to use read function


f.read(4) # read the first 4 data
'This'

20
f.read(4) # read the next 4 data
' is '

f.read() # read in the rest till end of file


'my first file\nThis file\ncontains three lines\n'

f.read() # further reading returns empty sting


''
OUTPUT:

(home)

10. Programs to perform searching, adding, updating the content from the file.

CODE:
#adding
import pickle
list =[]
while True:
roll = input("Enter student Roll No:")
sname = input("Enter student Name :")
student = {"roll":roll,"name":sname}
list.append(student)
choice= input("Want to add more record(y/n) :")
if(choice=='n'):
break

file = open("E:\student.dat","wb")
pickle.dump(list,file)
file.close()

#Searching:
import pickle

name = input('Enter name that you want to search in binary file :')

file = open("E:\student.dat", "rb")


list = pickle.load(file)
file.close()

found = 0

21
for x in list:
if name in x['name']:
found = 1
print("Found in binary file" if found == 1 else "Not found")

#Update:
import pickle

name = input('Enter name that you want to update in binary file :')

file = open("E:\student.dat", "rb+")


list = pickle.load(file)

found = 0
lst = []
for x in list:
if name in x['name']:
found = 1
x['name'] = input('Enter new name ')
lst.append(x)

if(found == 1):
file.seek(0)
pickle.dump(lst, file)
print("Record Updated")
else:
print('Name does not exist')

file.close()

OUTPUT:

(home)

22
11. Program for performing CRUD operation with MongoDB and Python.

CODE:
from pymongo import MongoClient

# Creating a pymongo client


client = MongoClient('localhost', 27017) # Getting the database instance db =
client['St']

# Creating a collection
coll = db['Del']

# Inserting document into a collection


doc1 = {"id": "list of id", "name": "list of names", "dept": "enter department", "mark": "enter marks"}
coll.insert_one(doc1)
print(coll.find_one())
data = [
{
"_id": "1",
"name": "Ram",
"dept": "MCA",
"mark": "95%"
},
{
"_id": "2",
"name": "Sham",
"dept": "MCA",
"mark": "98%"
},
{
"_id": "3",
"name": "Sita",
"dept": "ADP",
"mark": "59%"
},
{
"_id": "4",
"name": "Gita",
"dept": "MCA",
"mark": "73%"
},
{
"_id": "5",
"name": "rina",
"dept": "MCA",
"mark": "53%"
},
{
"_id": "6",
"name": "kamla",
"dept": "MCA",

"mark": "71%"
},
{
"_id": "7",
"name": "seema",
"dept": "KCN",
"mark": "40%"

23
},
{
"_id": "8",
"name": "ajit",
"dept": "MCA",
"mark": "59%"
}
]
res = coll.insert_many(data)
print("Data inserted ")
myquery = {"_id": {"$lte": "2"}}
x = coll.delete_many(myquery)
print(x.deleted_count, " documents deleted.")

for doc2 in coll.find():


print(doc2)

OUTPUT:

24
(home)

12. Basic programs with NumPy as Array, Searching and Sorting, date & time and
String handling.

CODE:
# Python program for
# Creation of Arrays

import numpy as np

# Creating a rank 1 Array


arr = np.array([1, 2, 3])
print("Array with Rank 1: \n", arr)

# Creating a rank 2 Array


arr = np.array([[1, 2, 3],
[4, 5, 6]])

print("Array with Rank 2: \n", arr)

# Creating an array from tuple

25
arr = np.array((1, 3, 2))
print("\nArray created using " "passed tuple:\n", arr)

#Searching

def linearsearch(arr, x):

for i in range(len(arr)):
if arr[i] == x:

return i

return -1

arr = ['t','u','t','o','r','i','a','l']

x = 'a'

print("element found at index "+str(linearsearch(arr,x)))

#Sorting

# Initialize array arr


= [5, 2, 8, 7, 1];
temp = 0;

# Displaying elements of original array


print("Elements of original array: "); for i
in range(0, len(arr)):
print(arr[i], end=" ");

# Sort the array in ascending order for


i in range(0, len(arr)):
for j in range(i + 1, len(arr)):
if(arr[i] > arr[j]):
temp = arr[i];

arr[i] = arr[j];
arr[j] = temp;
print();

# Displaying elements of the array after sorting


print("Elements of array sorted in ascending order: "); for i
in range(0, len(arr)):
print(arr[i], end=" ");

#Date and time

from datetime import datetime

# datetime object containing current date and time now =


datetime.now()
print("now =", now) # dd/mm/YY H:M:S
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print("date and time =", dt_string)

26
#String handling

# Defining strings in Python


# all of the following are equivalent my_string = 'Hello' print(my_string)

my_string = "Hello"
print(my_string)

my_string = '''Hello'''
print(my_string)

# triple quotes string can extend multiple lines


my_string = """Hello, welcome to
the world of Python"""
print(my_string)

OUTPUT:

27
28
(home)

29
13. Programs for series and data frames should be covered.

CODE:
#series
import pandas as pd
d1 = {'a': 100, 'b': 200, 'c':300, 'd':400, 'e':800}
print("Original dictionary:")
print(d1)
new_series = pd.Series(d1)
print("Converted series:")
print(new_series)

#data frames
import pandas as pd
import numpy as np
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura',
'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],

'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],

'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}

labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

df = pd.DataFrame(exam_data , index=labels)
print(df)

OUTPUT:

30
(home)

14. Programs to demonstrate data pre-processing and data handling with data frame

CODE:
# Importing pandas
import pandas as pd
# Importing training data set
X_train=pd.read_csv('X_train.csv')
Y_train=pd.read_csv('Y_train.csv')

# Importing testing data set


X_test=pd.read_csv('X_test.csv')
Y_test=pd.read_csv('Y_test.csv')
print (X_train.head())

31
OUTPUT:

(home)

15. Program for data visualization should be covered.

CODE:
# import pandas and matplotlib
import pandas as pd
import matplotlib.pyplot as plt

# create 2D array of table given above

data = [['E001', 'M', 34, 123, 'Normal', 350],

['E002', 'F', 40, 114, 'Overweight', 450],

['E003', 'F', 37, 135, 'Obesity', 169],

['E004', 'M', 30, 139, 'Underweight', 189],

['E005', 'F', 44, 117, 'Underweight', 183],

32
['E006', 'M', 36, 121, 'Normal', 80],

['E007', 'M', 32, 133, 'Obesity', 166],

['E008', 'F', 26, 140, 'Normal', 120],

['E009', 'M', 32, 133, 'Normal', 75],

['E010', 'M', 36, 133, 'Underweight', 40] ]

# dataframe created with # the above data array


df = pd.DataFrame(data, columns = ['EMPID', 'Gender',

'Age', 'Sales',

'BMI', 'Income'] )

# create histogram for numeric data


df.hist()

# show plot
plt.show()

OUTPUT:

(home)

33
INDEX2

ADVANCED INTERNET TECHNOLOGY

SR. NO. TITLE PAGE NO.


1 Program to implement Audio and Video features for 35
your web page.
2 Program to design form using HTML5 elements, 36
attributes and Semantics.
3 Programs using Canvas and SVG. 38
4 Programs to demonstrate external and internal styles in the 40
web page using font, text, background, borders, opacity
and other CSS 3 properties.
5 Implement Transformation using Translation, Rotation and 42
Scaling in your web page.
6 Program to show current date and time using user 43
defined module
7 Program using built-in modules to split the query 43
string into readable parts.
8 Program using NPM which will convert entered string 44
into either case
9 Write a program to create a calculator using Node JS. 44
(Install and configure Node JS and Server)
10 Write Program for Form validation in Angular. 47
11 Program to demonstrate the ngif, ngfor, ngswitch 48
statements.
12 Create angular project which will demonstrate the usage of 52
component directive, structural directive and attribute
directives
13 Create angular project which has HTML template and 54
handle the click event on click of the button (Installation of
Angular and Bootstrap 4 CSS Framework)

14 Program for basic operations, array and user 55


interface handling.
15 Program to demonstrate session management using 57
various techniques.
16 Program to perform the CRUD Operations using PHP 58
Script.

34
1. Program to implement Audio and Video features for your web page.

CODE:
<!Doctype>
<Html>
<body>
<h1> The video element </h1>
<video width="390" height="400" controls>
<source src="elephant.mp4" type="video/mp4">
<source src="elephant.ogg" type="video/mp4">
</video>

<h1> The Audio element </h1>


<p> click on the play button to play sound: </p>
<audio controls>
<source src="elephant" type=audio/WAV>
<source src="elephant.mp3" type="audio/WAV">
</audio>
</body>
</html>

OUTPUT:

(home)

35
2. Program to design form using HTML5 elements, attributes and Semantics.

CODE:

<html>
<body>
<form action="/signup" method="post">
<p>
<h3><label>Sign up form:</label></h3><br><br>
<label>
<input type="radio" name="title" value="mr">
Mr
</label>
<label>
<input type="radio" name="title" value="mrs">
Mrs
</label>
<label>
<input type="radio" name="title" value="miss">
Miss
</label>
</p>
<p>
<label>First name</label><br>
<input type="text" name="first_name">
</p>
<p>
<label>Last name</label><br>
<input type="text" name="last_name">
</p>
<p>
<label>Email</label><br>
<input type="email" name="email" required>
</p>
<p>
<label>Phone number</label><br>
<input type="tel" name="phone" placeholder="123-45-678" pattern="[0-9]{3}-[0-9]{2}-[0-9]{3}"
requierd>
</p>
<p>
<label>Password</label><br>
<input type="password" name="password">
</p>
<p>
<label for="date">
<span>Birth date:</span>
<strong>
<abbr title="required">*</abbr>
</strong>
</label>

<input type="date" id="date" name="birth date">


</p>
<p>

36
<label>Country</label><br>
<select>
<option>India</option>
<option>Australia</option>
<option>United States</option>
<option>Indonesia</option>
<option>Brazil</option>
</select>
</p>
<p>
<br>
<label>
<input type="checkbox" value="terms">
I agree to the <a href="/terms">terms and conditions</a>
</label>
</p>
<p>
<button>Sign up</button>
<button type="reset">Reset form</button>
</p>
</form>
</body>
</html>

OUTPUT:

(home)

37
3. Programs using Canvas and SVG.

CODE:
<!DOCTYPE html>
<html>
<body>
<p>This is example of HTML Canvas Graphics </p>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML canvas tag.</canvas>

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

// Create gradient
var grd = ctx.createRadialGradient(75,50,5,90,60,100);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");

// Fill with gradient


ctx.fillStyle = grd;
ctx.fillRect(10,10,150,80);
</script>

</body>
</html>

<!DOCTYPE html>
<html>
<body>
<p>
This is example of SVG Graphics
</p>
<svg height="130" width="500">
<defs>
<linearGradient id="grad1" x1="0%" y1="20%" x2="100%" y2="0%">
<stop offset="10%"
style="stop-color:rgb(255,105,180);stop-opacity:1" />
<stop offset="90%"
style="stop-color:rgb(139,0,139);stop-opacity:1" />
</linearGradient>
</defs>
<ellipse cx="100" cy="70" rx="85" ry="55" fill="url(#grad1)" />
<text fill="#ffffff" font-size="45" font-family="Verdana"
x="50" y="86">Dev</text>
Sorry, your browser does not support inline SVG.
</svg>

</body>
</html>

38
OUTPUT:

(home)

39
4. Programs to demonstrate external and internal styles in the web page using font,
text, background, borders, opacity and other CSS 3 properties.

CODE:
Internal CSS:-
<html>
<head>
<style>
img {
opacity: 0.5;;
}
body {
background-color:#FFBF00;
}
h1 {
font-family: "Lucida Handwriting",monospace;
color: red(245, 241, 245);
padding: 50px;
}
h3{
font-family: "Lucida Console", "Courier New", monospace;
color:red(3, 7, 7);
}
</style>
</head>
<body>
<div class="background">
<h1>Internal CSS</h1>
<p><h3>Cascading Style sheet types: inline, external and internal</h3></p>
</div>
<p>Image with 50% opacity:</p>
<img src="forest.JFIF" alt="loading" width="320" height="250">
</body>
</html>

<html>
<head>
<link rel="stylesheet" href="External CSS.css">
</head>
<body>
<h1>External CSS </h1>
<p><p><h3>Cascading Style sheet types: inline, external and internal</h3></p>
</p>
<p>Image with 50% opacity:</p>
<img src="waterfall.JFIF" alt="Palace" width="320" height="250">
<img src="nature.JFIF" alt="Bell" width="320" height="250">
<img src="fort.JFIF" alt="Lizard" width="320" height="250">
</body>
</html>

40
OUTPUT:

(home)

41
5. Implement Transformation using Translation, Rotation and Scaling in your web
page.

CODE:
<html>
<head>
<p>Dev</p><br><br><br>
<style>
div {
width: 190px;
height: 20px;
text-align: center;
background-color: pink;
}
.rotate1 {
/* specify rotation properties for class rotate1 */
transform: rotate(20deg);
background-color: skyblue;
}
.rotate2 {
/* specify rotation properties for class rotate2 */
transform: rotate(50deg);
background-color: red;
}
</style>
</head>
<body>

<div class="rotate1">Rotated:20 Degree</div><br><br><br>


<!-- Here class rotate1 properties are applied-->

<div class="rotate2">Rotated:50 Degree</div>


<!-- Here class rotate2 properties are applied-->
</body>
</html>

OUTPUT:

42
(home)

6. Program to show current date and time using user defined module.

CODE:
import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))

OUTPUT:
Current date and time:
2021-10-14 19:54:16

(home)

7. Program using built-in modules to split the query string into readable parts.

CODE:
const querystring = require('querystring');
const url = "http://example.com/index.html?code=string&key=12&id=false";
const qs = "code=string&key=12&id=false";
console.log(querystring.parse(qs));
// > { code: 'string', key: '12', id: 'false' }
console.log(querystring.parse(url));

OUTPUT:

(home)

43
8. Program using NPM which will convert entered string into either case.

CODE:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
string = fruits.join(' ').toUpperCase();
console.log("convert the string lowercase to uppercase",string)

OUTPUT:

(home)

9. Write a program to create a calculator using Node JS. (Install and configure Node
JS and Server)

CODE:
//Hapi framework
import { Server } from 'hapi';

//Address and port


const host = 'localhost';
const port = 3000;

//Create server
const server = Server({
host: host,
port: port
});

//Routes
require('./routes')(server);

//Start server
const init = async () => {
await server.start();
console.log("Server up! Port: " + port);
}

//Start App
init();
export default function (server) {

44
//route - about
server.route({
method: 'GET',
path: '/calculadora/about',
handler: function (request, h) {

var data = {
message: 'Calculator API - made by Bernardo Rocha'
};

return data;
}
});
//route - sum
server.route({
method: 'GET',

path: '/calculator/sum/{num1}+{num2}',
handler: function (request, h) {

const num1 = parseInt(request.params.num1);


const num2 = parseInt(request.params.num2);

var data = {
answer: num1 + num2
};

return data;
}
});

//route - subtraction
server.route({
method: 'GET',

path: '/calculator/sub/{num1}-{num2}',
handler: function (request, h) {

const num1 = parseInt(request.params.num1);


const num2 = parseInt(request.params.num2);

var data = {
answer: num1 - num2
};

return data;
}

45
});

//route - multiplication
server.route({
method: 'GET',

path: '/calculator/multi/{num1}*{num2}',
handler: function (request, h) {

const num1 = parseInt(request.params.num1);


const num2 = parseInt(request.params.num2);

var data = {
answer: num1 * num2
};

return data;
}
});

//route - division
server.route({
method: 'GET',

path: '/calculator/div/{num1}/{num2}',
handler: function (request, h) {

const num1 = parseInt(request.params.num1);


const num2 = parseInt(request.params.num2);
var data = {
answer: num1 / num2
};

return data;
}
});
}

OUTPUT:

(home)

46
10. Write Program for Form validation in Angular.

CODE:
import { Component, OnInit } from '@angular/core';
//import validator and FormBuilder
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})

export class TestComponent implements OnInit {


//Create FormGroup
requiredForm: FormGroup;
constructor(private fb: FormBuilder) {
this.myForm();
}
//Create required field validator for name
myForm() {
this.requiredForm = this.fb.group({
name: ['', Validators.required ]
});
}
ngOnInit()
{

}
}
<div>
<h2>
Required Field validation
</h2>
<form[formGroup]="requiredForm" novalidate>
<div class="form-group">
<label class="center-block">Name:
<input class="form-control" formControlName="name">
</label>
</div>
<div *ngIf="requiredForm.controls['name'].invalid && requiredForm.controls['name'].touched "
class="alert alert-danger">
<div *ngIf="requiredForm.controls['name'].errors.required">
Name is required.
</div>
</div>
</form>
<p>Form value: {{ requiredForm.value | json }}</p>
<p>Form status: {{ requiredForm.status | json }}</p>

47
</div>

OUTPUT:

(home)

11. Program to demonstrate the ngif, ngfor, ngswitch statements.

CODE:
:- import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-server2',
templateUrl: './server2.component.html',
styleUrls: ['./server2.component.css']
})
export class Server2Component implements OnInit { allowNewServer = false;
serverCreationStatus = 'No server is created.';
serverName = 'TestServer';
serverCreated = false;
/*constructor() { setTimeout(() =>{ this.allowNewServer = true;
Submit
}, 5000);
}*/
ngOnInit() {
}
onCreateServer() { this.serverCreated = true;
this.serverCreationStatus = 'Server is created. Name of the server is' + this.serverName;
}
OnUpdateServerName(event: Event) {
this.serverName = (<HTMLInputElement>event.target).value;
}

ngif

48
@Component({
selector: 'ngif-example',
template: `
<h4>NgIf</h4>
<ul *ngFor="let person of people">
<li *ngIf="person.age < 30"> (1)
{{ person.name }} ({{ person.age }})
</li>
</ul>
`
})
class NgIfExampleComponent {

people: any[] = [
{
"name": "Douglas Pace", "age":
35
},
{
"name": "Mcleod Mueller",
"age": 32
},
{
"name": "Day Meyers",
"age": 21
},
{
"name": "Aguirre Ellis",
"age": 34
},
{
"name": "Cook Tyson",
"age": 32
}
];
}

Ngswitch:

<ul *ngFor="let person of people">


<li *ngIf="person.country ==='UK'"
class="text-success">{{ person.name }} ({{ person.country }})
</li>
<li *ngIf="person.country === 'USA'"
class="text-primary">{{ person.name }} ({{ person.country }})
</li>
<li *ngIf="person.country === 'HK'"
class="text-danger">{{ person.name }} ({{ person.country }})

49
</li>
<li *ngIf="person.country !== 'HK' && person.country !== 'UK' && person.country !== 'USA'"
class="text-warning">{{ person.name }} ({{ person.country }})
</li>
</ul>

.html
@Component({
selector: 'ngswitch-example',
template: `<h4>NgSwitch</h4>
<ul *ngFor="let person of people"
[ngSwitch]="person.country"> (1)

<li *ngSwitchCase="'UK'" (2)


class="text-success">{{ person.name }} ({{ person.country }})
</li>
<li *ngSwitchCase="'USA'"
class="text-primary">{{ person.name }} ({{ person.country }})
</li>
<li *ngSwitchCase="'HK'"
class="text-danger">{{ person.name }} ({{ person.country }})
</li>
<li *ngSwitchDefault (3)
class="text-warning">{{ person.name }} ({{ person.country }})
</li>
</ul>`
})
class NgSwitchExampleComponent {

people: any[] = [
{
"name": "Douglas Pace", "age":
35,
"country": 'MARS'
},
{
"name": "Mcleod Mueller",
"age": 32,
"country": 'USA'
},
{
"name": "Day Meyers",
"age": 21,
"country": 'HK'
},
{
"name": "Aguirre Ellis",
"age": 34,

50
"country": 'UK'
},
{
"name": "Cook Tyson",
"age": 32,
"country": 'USA'
}
];
}

OUTPUT:

51
(home)
12. Create angular project which will demonstrate the usage of component
directive, structural directive and attribute directives.

CODE:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

// Custom directive imported here by Angular CLI


import { ChangeColorDirective } from './change-color.directive';

@NgModule({
declarations: [
AppComponent,
ChangeColorDirective // Custom directive is declared in declartions array by Angular CLI
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

52
// Custom directive imported here by Angular CLI
import { ChangeColorDirective } from './change-color.directive';

@NgModule({
declarations: [
AppComponent,
ChangeColorDirective // Custom directive is declared in declartions array by Angular CLI
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

change-color.directive.ts
import { Directive } from '@angular/core';

@Directive({
selector: '[appChangeColor]'
})

export class ChangeColorDirective {

constructor() { }

App.component.html
<div style="text-align:center">

<img width="250" alt="Angular Logo" src="data:image/svg+xml;base64,jcgMTQuMi0xMjMuMXo


iIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4Ljkt
NDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZ
D0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgz
TDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">

<div style="padding-top: 30px">


// appChangeColor custom Directive
<h1 appChangeColor>I got colored by Angular Custom Directive</h1>
</div>
</div>

OUTPUT:

53
(home)
13. Create angular project which has HTML template and handle the click event
on click of the button (Installation of Angular and Bootstrap 4 CSS
Framework).

CODE:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Angular Bootstrap Demo</title>
<base href="/">

<meta name="viewport" content="width=device-width, initial-scale=1">


<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min. css"
integrity="sha384-
BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigi
n="anonymous">
</head>
<body>
<app-root>Loading...</app-root>
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-
hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha 384-
Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigi
n="anonymous"></script>
</body>
</html>

54
<div class="container">
<div class="jumbotron">
<h1>Welcome</h1>
<h2>Angular & Bootstrap Demo</h2>
</div>

<div class="panel panel-primary">


<div class="panel-heading">Status</div>
<div class="panel-body">
<h3>{{title}}</h3>
</div>
</div>
</div>

OUTPUT:

(home)
14. Program for basic operations, array and user interface handling.

CODE:
Array.php
<?php
class myclass implements ArrayAccess {
private $arr = array();
public function construct() {
$this->arr = array("Mumbai", "Hyderabad", "Patna");
}
public function offsetSet($offset, $value) {
if (is_null($offset)) {
$this->arr[] = $value;
} else {
$this->arr[$offset] = $value;
}

55
}
public function offsetExists($offset) {
eturn isset($this->arr[$offset]);
}
public function offsetUnset($offset) {
unset($this->arr[$offset]);
}
public function offsetGet($offset) {
return isset($this->arr[$offset]) ? $this->arr[$offset] : null;
}
}
$obj = new myclass();
var_dump(isset($obj[0]));
var_dump($obj[0]);
unset($obj[0]);
var_dump(isset($obj[0]));
$obj[3] = "Pune";
var_dump($obj[3]);
$obj[4] = 'Chennai';
$obj[] = 'NewDelhi';
$obj[2] = 'Benguluru';
print_r($obj);
?>

OUTPUT:

(home)

56
15. Program to demonstrate session management using various techniques.

CODE:
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>

OUTPUT:

(home)

57
16. Program to perform the CRUD Operations using PHP Script.

CODE:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Print host information
echo "Connect Successfully. Host info: " . mysqli_get_host_info($link);
?>

OUTPUT:

CODE:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "");

// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt create database query execution
$sql = "CREATE DATABASE demo";
if(mysqli_query($link, $sql)){
echo "Database created successfully";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>

58
OUTPUT:

CODE:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Attempt create table query execution


$sql = "CREATE TABLE persons(
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
first_name VARCHAR(30) NOT NULL,
last_name VARCHAR(30) NOT NULL,
email VARCHAR(70) NOT NULL UNIQUE
)";
if(mysqli_query($link, $sql)){
echo "Table created successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>

OUTPUT:

59
CODE:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt insert query execution
$sql = "INSERT INTO persons (first_name, last_name, email) VALUES ('Yograj', 'Shirsath', 'yogr
[email protected]')";
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['first_name'] . "</td>";
echo "<td>" . $row['last_name'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>

60
OUTPUT:

CODE:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt update query execution
$sql = "UPDATE persons SET email='[email protected]' WHERE id=1";
if(mysqli_query($link, $sql)){
echo "Records were updated successfully.";
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>

OUTPUT:

61
CODE:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");

// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Attempt delete query execution


$sql = "DELETE FROM persons WHERE first_name='Yograj'";
if(mysqli_query($link, $sql)){
echo "Records were deleted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

// Close connection
mysqli_close($link);
?>

OUTPUT:

62
(home)

63
64

You might also like