Calculator
<!DOCTYPE html>
<html>
<head>
<title>Mathematical Calculator</title>
</head>
<body>
<h1>Mathematical Calculator</h1>
<form method="post" action="calculator.php">
<label for="num1">Enter the first number:</label>
<input type="number" name="num1" id="num1" required><br><br>
<label for="num2">Enter the second number:</label>
<input type="number" name="num2" id="num2" required><br><br>
<input type="submit" name="calculate" value="Calculate">
</form>
</body>
</html>
calculator.php
<?php
if (isset($_POST['calculate'])) {
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
// Addition
$addition = $num1 + $num2;
echo "Addition: $addition<br>";
// Subtraction
$subtraction = $num1 - $num2;
echo "Subtraction: $subtraction<br>";
// Multiplication
$multiplication = $num1 * $num2;
echo "Multiplication: $multiplication<br>";
// Division
if ($num2 != 0) {
$division = $num1 / $num2;
echo "Division: $division<br>";
} else {
echo "Division by zero is not allowed<br>";
}
}
?>
Registration
<!DOCTYPE html>
<html>
<head>
<title>Registration Page</title>
</head>
<body>
<h1>Registration Page</h1>
<form method="post" action="Registration.php">
<label for="name">Name:</label>
<input type="text" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" name="email" required><br><br>
<label for="age">Age:</label>
<input type="number" name="age" required><br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
Registration php
<!DOCTYPE html>
<html>
<head>
<title>Registration Details</title>
</head>
<body>
<h1>Registration Details</h1>
<?php
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$age = $_POST['age'];
echo "<p>Name: $name</p>";
echo "<p>Email: $email</p>";
echo "<p>Age: $age</p>";
}
?>
</body>
</html>
Registration mysql
<html>
<head>
<title>Registration page</title>
</head>
<body>
<h1>Registration form</h1>
<form method="post" action="RegistrationMysql.php">
Name:
<input type="name" name="name">
Mobile:
<input type="number" name="mobile">
address:
<input type="text" name="address">
<input type="submit" value="submit">
</form>
</body>
</html>
Registration mysql php
<?php
if(isset($_POST['submit']))
{
$name=$_POST['name'];
$mobile=$_POST['mobile'];
$address=$_POST['address'];
$host='localhost';
$username='root';
$pass='supriya@1432';
$db='Student';
$conn=mysqli_connect($host,$username,$pass,$db)
$query="INSERT INTO 'Student'('name','mobile','address')values('$name','$mobile','$address');";
if(mysqli_query($conn,$query))
echo" Registration suuccessfull";
else
echo"error"
}
mysqli_close($conn)
?>
Login
<html>
<head>
<title>Login page</title>
</head>
<body>
<h1>Login page</h1>
<form>
Email:
<input type="email" name="name">
password:
<input type="password" name="name">
<input type="submit" value="submit">
</form>
</body>
</html>
login.php
<?php
if(isset($_POST['submit']))
{
$Email=$_POST['email']
$password=$_POST['password']
$conn=mysqli_connect('localhost','root','supriya@1432','Student')
if(!$conn)
{
die("connection failed")
}
$query="INSERT INTO student('email','password')values('[email protected]','Supriya@1234');";
if(mysqli_query($conn,$query))
{
echo"successfuul"
}
else
{
echo"not login"
}
mysqli_close($conn)
}
</html>
file copy
<?php
// Read from existing file
$sourceFile = "abc.txt";
$content = file_get_contents($sourceFile);
// Write to another file
$destinationFile = "xyz.txt";
file_put_contents($destinationFile, $content);
echo "File copied successfully!";
?>
banck data
<!DOCTYPE html>
<html ng-app="bankApp">
<head>
<title>Bank Details</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
<script>
angular.module('bankApp', [])
.controller('BankController', function($scope) {
$scope.banks = [
{
name: 'Bank A',
micrCode: '123456',
ifcCode: 'ABC123',
address: 'Address 1'
},
{
name: 'Bank B',
micrCode: '987654',
ifcCode: 'XYZ987',
address: 'Address 2'
},
{
name: 'Bank C',
micrCode: '456789',
ifcCode: 'PQR789',
address: 'Address 3'
}
];
});
</script>
</head>
<body>
<div ng-controller="BankController">
<table>
<thead>
<tr>
<th>Bank Name</th>
<th>MICR Code</th>
<th>IFC Code</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="bank in banks">
<td>{{ bank.name }}</td>
<td>{{ bank.micrCode }}</td>
<td>{{ bank.ifcCode }}</td>
<td>{{ bank.address }}</td>
</tr>
</tbody>
AIT practical Based Assessment -2
</table>
</div>
</body>
</html>
2. Write an AngularJS script for addition of two numbers using ng-init,
ng-model & ng-bind. And also Demonstrate ng-show, ng-disabled,
ng-click directives on button component
<!DOCTYPE html>
<html ng-app="additionApp">
<head>
<title>Addition of Two Numbers</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"
>
</script>
<script>
angular.module('additionApp', [])
.controller('AdditionController', function($scope) {
$scope.num1 = 0;
$scope.num2 = 0;
$scope.result = 0;
$scope.addNumbers = function() {
$scope.result = $scope.num1 + $scope.num2;
};
});
</script>
</head>
<body>
<div ng-controller="AdditionController">
<label>Number 1:</label>
<input type="number" ng-model="num1" ng-init="num1=0" />
<label>Number 2:</label>
<input type="number" ng-model="num2" ng-init="num2=0" />
<button
ng-click="addNumbers()"
ng-disabled="num1 === 0 && num2 ===0"
>
Add
</button>
<div ng-show="result !== 0">
<label>Result:</label>
<span ng-bind="result"></span>
</div>
</div>
</body>
</html>
3. Create a Node.js file that Insert Multiple Records in "student"
table, and display the result object on console. (5 Marks)
const mysql = require('mysql');
const connection =
mysql.createConnection({
host:
'localhost',
user: 'root',
password: '',
database:
'student_db'
});
const students = [
{ name: 'Shubham', age: 20, grade: 'A' },
{ name: 'Swapnil', age: 22, grade: 'B' },
{ name: 'Ajay', age: 19, grade: 'A+' }
];
connection.connect((err) => {
if (err) {
console.error('Error connecting to the database:',
err); return;
}
const query = 'INSERT INTO student (name, age, grade) VALUES ?';
const values = students.map(student => [student.name, student.age, student.grade]);
connection.query(query, [values], (err, result) => {
if (err) {
console.error('Error inserting records:', err);
} else {
console.log('Records inserted successfully:', result);
}
connection.end();
});
});
connection.on('error', (err) => {
console.error('Database connection error:', err);
});
4. Create a Node.js application that uses user defined module to find area of
rectangle and display details on console. (5 Marks)
// Import the rectangle module
const rectangle = require('./rectangle');
// Define the dimensions of the rectangle
const length = 5;
const width = 3;
// Calculate the area using the imported module
const area = rectangle.calculateArea(length, width);
// Display the details on the console
console.log(`Rectangle Details:\nLength: ${length}\nWidth:
${width}\nArea: ${area}`);
// Export a function to calculate the area of a rectangle
module.exports.calculateArea = function(length, width)
{
return length * width;
};
canvass
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas id="mycanvas"></canvas>
<script>
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");
// ctx.fillStyle="green";
// ctx.fillRect(0,0,190,95);
ctx.moveTo(0,0);
ctx.lineTo(900,900);
ctx.stroke();
</script>
</body>
</html>
3pages
1
<!DOCTYPE html>
<html>
<head>
<title>Product 1</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<h1>Product 1</h1>
<p>This is the information about Product 1.</p>
</body>
</html>
2
<!DOCTYPE html>
<html>
<head>
<title>Product 2</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<h1>Product 2</h1>
<p>This is the information about Product 2.</p>
</body>
</html>
3
<!DOCTYPE html>
<html>
<head>
<title>Product 3</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<h1>Product 3</h1>
<p>This is the information about Product 3.</p>
</body>
</html>
main code
<!DOCTYPE html>
<html>
<head>
<title>Online Shopping</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<h1>Welcome to Online Shopping</h1>
<ul>
<li><a href="product1.html">Product 1</a></li>
<li><a href="product2.html">Product 2</a></li>
<li><a href="product3.html">Product 3</a></li>
<!-- Add more items as required -->
</ul>
</body>
</html>
style.css
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
}
h1 {
color: #333;
margin-bottom: 20px;
}
ul {
list-style: none;
padding: 0;
margin: 0;
}
li {
margin-bottom: 10px;
}
a {
color: #007bff;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
Que1
<!DOCTYPE html>
<html>
<head>
<title>City Information Web Page</title>
<style>
body {
display: grid;
grid-template-columns: 50% 50%;
font-size: 2rem;
}
#heading {
grid-column: 1 / span 2;
text-align: center;
padding: 20px;
background-color: #f2f2f2;
border: 2px solid black;
}
#cityList {
padding: 20px;
border: 2px solid black;
height: 100%;
}
.cityInfo {
display: none;
padding: 20px;
background-color: #f9f9f9;
border: 2px solid black;
height: 100%;
}
</style>
<script>
function showCityInfo(cityId) {
// Hide all city info divs
var cityInfoDivs = document.getElementsByClassName("cityInfo");
for (var i = 0; i < cityInfoDivs.length; i++) {
cityInfoDivs[i].style.display = "none";
}
// Show the selected city info div
var selectedCityInfo = document.getElementById(cityId);
if (selectedCityInfo) {
selectedCityInfo.style.display = "block";
}
}
window.onload = function() {
showCityInfo('city1');
};
</script>
</head>
<body>
<div id="heading">
<h1>IT companies in India</h1>
</div>
<div id="cityList">
<h2>City:</h2>
<ul>
<li><a href="javascript:void(0);" onclick="showCityInfo('city1')">Pune</a></li>
<li><a href="javascript:void(0);" onclick="showCityInfo('city2')">Mumbai</a></li>
<li><a href="javascript:void(0);" onclick="showCityInfo('city3')">Banglore</a></li>
<!-- Add more cities as required -->
</ul>
</div>
<div id="cityInfo">
<div id="city1" class="cityInfo">
<h2>Pune</h2>
<p><li>Infosys</li><li>Persistent</li><li>Hexaware</li></p>
</div>
<div id="city2" class="cityInfo">
<h2>Mumbai</h2>
<p><li>Apple</li><li>Google</li><li>TCS</li></p>
</div>
<div id="city3" class="cityInfo">
<h2>Banglore</h2>
<p><li>Whipro</li><li>Salesforce</li><li>HCL</li></p>
</div>
<!-- Add more city information divs as required -->
</div>
</body>
</html>
Registration
<!DOCTYPE html>
<html>
<head>
<title>Aadhar Card Registration</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
h1 {
margin-bottom: 20px;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
font-weight: bold;
margin-bottom: 5px;
}
input[type="text"],
input[type="number"] {
width: 100%;
padding: 10px;
font-size: 16px;
border: 1px solid #ccc;
border-radius: 4px;
}
.error {
color: red;
font-size: 14px;
}
input[type="submit"] {
background-color: #007bff;
color: #fff;
padding: 10px 20px;
font-size: 16px;
border: none;
border-radius: 4px;
cursor: pointer;
}
</style>
<script>
function validateForm() {
var name = document.forms["registrationForm"]["name"].value;
var age = document.forms["registrationForm"]["age"].value;
var mobile = document.forms["registrationForm"]["mobile"].value;
// Reset error messages
document.getElementById("nameError").textContent = "";
document.getElementById("ageError").textContent = "";
document.getElementById("mobileError").textContent = "";
// Validate name
if (!name.match(/^[A-Z a-z]+$/)) {
document.getElementById("nameError").textContent = "Please Enter a valid Name";
return false;
}
// Validate age
if (!age.match(/^[0-9]+$/)) {
document.getElementById("ageError").textContent = "Age must be a number";
return false;
} else if (parseInt(age) < 0 || parseInt(age) > 150) {
document.getElementById("ageError").textContent = "Invalid age";
return false;
}
// Validate mobile number
if (!mobile.match(/^[0-9]{10}$/)) {
document.getElementById("mobileError").textContent = "Mobile number must be 10 digits";
return false;
}
// Show success message
alert("All credentials are valid !! Registration successful!");
}
</script>
</head>
<body>
<h1>Aadhar Card Registration</h1>
<form name="registrationForm" onsubmit="return validateForm()" >
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<span class="error" id="nameError"></span>
</div>
<div class="form-group">
<label for="age">Age:</label>
<input type="number" id="age" name="age" required>
<span class="error" id="ageError"></span>
</div>
<div class="form-group">
<label for="mobile">Mobile:</label>
<input type="text" id="mobile" name="mobile" required>
<span class="error" id="mobileError"></span>
</div>
<div class="form-group">
<input type="submit" value="Register">
</div>
</form>
</body>
</html>
SVG
<!DOCTYPE html>
<html>
<head>
<title>Star Shape</title>
</head>
<body>
<svg width="200" height="200">
<polygon points="100,10 40,198 190,78 10,78 160,198" style="fill:none; stroke:black; stroke-width:2" />
</svg>
</body>
</html>
Audio video
<!DOCTYPE html>
<html>
<head>
<title>Audio and Video Example</title>
</head>
<body>
<h2>Audio : </h2>
<audio controls>
<source src="audio_file.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<h2>Video :</h2>
<video controls width="480" height="360">
<source src="video_file.mp4" type="video/mp4">
Your browser does not support the video element.
</video>
</body>
</html>
#############################################
############################################360
python
#pythone
#assig 1
Write a program to perform following operations on list
1. Sum all the items in a list.
def sum_list(items):
return sum(items)
my_list = [1, 2, 3, 4, 5]
print("Sum of the list:", sum_list(my_list))
2. Get the largest number from a list.
def get_largest_number(items):
return max(items)
my_list = [1, 10, 5, 7, 3]
print("Largest number in the list:", get_largest_number(my_list))
3. Remove duplicates from a list.
def remove_duplicates(items):
return list(set(items))
my_list = [1, 2, 2, 3, 4, 4, 5]
print("List without duplicates:", remove_duplicates(my_list))
4. Separate positive and negative number from a list.
def separate_positive_negative(items):
positive = [num for num in items if num > 0]
negative = [num for num in items if num < 0]
return positive, negative
my_list = [1, -2, 3, -4, 5]
positive_nums, negative_nums = separate_positive_negative(my_list)
print("Positive numbers:", positive_nums)
print("Negative numbers:", negative_nums)
5. Filter even and odd number from a list.
def filter_even_odd(items):
even = [num for num in items if num % 2 == 0]
odd = [num for num in items if num % 2 != 0]
return even, odd
my_list = [1, 2, 3, 4, 5]
even_nums, odd_nums = filter_even_odd(my_list)
print("Even numbers:", even_nums)
print("Odd numbers:", odd_nums)
#############################
Write a program to perform following operations on string
1. Reverse string.
def reverse_string(input_string):
return input_string[::-1]
my_string = "Hello, World!"
print("Reversed string:", reverse_string(my_string))
2. Count vowels and consonants in a string.
def count_vowels_consonants(input_string):
vowels = 0
consonants = 0
for char in input_string.lower():
if char.isalpha():
if char in 'aeiou':
vowels += 1
else:
consonants += 1
return vowels, consonants
my_string = "Hello, World!"
vowel_count, consonant_count = count_vowels_consonants(my_string)
print("Vowel count:", vowel_count)
print("Consonant count:", consonant_count)
3. Count the number of letters in a word.
def count_letters(word):
return len(word)
my_word = "Hello"
print("Number of letters:", count_letters(my_word))
4. Convert lower letter to upper and upper letter to lower in a string.
def convert_case(input_string):
return input_string.swapcase()
my_string = "Hello, World!"
print("Converted string:", convert_case(my_string))
5. Count lower, upper, numeric and special characters in a string
def count_characters(input_string):
lowercase = 0
uppercase = 0
numeric = 0
special = 0
for char in input_string:
if char.islower():
lowercase += 1
elif char.isupper():
uppercase += 1
elif char.isnumeric():
numeric += 1
else:
special += 1
return lowercase, uppercase, numeric, special
my_string = "Hello, World! 123"
lowercase_count, uppercase_count, numeric_count, special_count = count_characters(my_string)
print("Lowercase count:", lowercase_count)
print("Uppercase count:", uppercase_count)
print("Numeric count:", numeric_count)
print("Special count:", special_count)
#########################
Write a program to perform following operations on dictionary
1. Check whether a given key exists in a dictionary or not.
def check_key_exists(dictionary, key):
return key in dictionary
my_dictionary = {"apple": 3, "banana": 5, "orange": 2}
key = "banana"
if check_key_exists(my_dictionary, key):
print(f"Key '{key}' exists in the dictionary")
else:
print(f"Key '{key}' does not exist in the dictionary")
2. Iterate over dictionary items using for loop.
def iterate_dictionary(dictionary):
for key, value in dictionary.items():
print(key, ":", value)
my_dictionary = {"apple": 3, "banana": 5, "orange": 2}
print("Dictionary items:")
iterate_dictionary(my_dictionary)
3. Concatenate two dictionaries to create one.
def concatenate_dictionaries(dict1, dict2):
return {**dict1, **dict2}
my_dictionary = {"apple": 3, "banana": 5, "orange": 2}
another_dictionary = {"grapes": 4, "kiwi": 1}
concatenated_dict = concatenate_dictionaries(my_dictionary, another_dictionary)
print("Concatenated dictionary:", concatenated_dict)
4. Sum all the values of a dictionary.
def sum_dictionary_values(dictionary):
return sum(dictionary.values())
my_dictionary = {"apple": 3, "banana": 5, "orange": 2}
total_sum = sum_dictionary_values(my_dictionary)
print("Sum of dictionary values:", total_sum)
5. Get the maximum and minimum value of dictionary.
def get_max_min_values(dictionary):
values = list(dictionary.values())
return max(values), min(values)
my_dictionary = {"apple": 3, "banana": 5, "orange": 2}
max_value, min_value = get_max_min_values(my_dictionary)
print("Maximum value:", max_value)
print("Minimum value:", min_value)
##########################
. Write a program to print
1. First 10 natural numbers
def print_first_10_natural_numbers():
for i in range(1, 11):
print(i)
print("First 10 natural numbers:")
print_first_10_natural_numbers()
2. First 10 even numbers in reverse order
def print_first_10_even_numbers_reverse():
for i in range(20, 0, -2):
print(i)
print("First 10 even numbers in reverse order:")
print_first_10_even_numbers_reverse()
3. Table of a number accepted from user
def print_number_table(number):
print(f"Table of {number}:")
for i in range(1, 11):
print(f"{number} x {i} = {number * i}")
user_input = int(input("Enter a number: "))
print_number_table(user_input)
4. First 10 prime numbers
def is_prime(number):
if number < 2:
return False
for i in range(2, int(number ** 0.5) + 1):
if number % i == 0:
return False
return True
def print_first_10_prime_numbers():
count = 0
number = 2
while count < 10:
if is_prime(number):
print(number)
count += 1
number += 1
print("First 10 prime numbers:")
print_first_10_prime_numbers()
###################
patterns
1
12
123
1234
def print_number_pattern():
for i in range(1, 5):
for j in range(1, i + 1):
print(j, end='')
print()
print("Pattern 1:")
print_number_pattern()
****
***
**
*
def print_asterisk_pattern():
for i in range(4, 0, -1):
for j in range(1, i + 1):
print('*', end='')
print()
print("Pattern 2:")
print_asterisk_pattern()
55555
4444
333
22
1
def print_number_decreasing_pattern():
for i in range(5, 0, -1):
for j in range(1, i + 1):
print(i, end='')
print()
print("Pattern 3:")
print_number_decreasing_pattern()
A
BC
DEF
GHIJ
KLMNO
def print_alphabet_pattern():
count = 65 # ASCII value of 'A'
for i in range(1, 6):
for j in range(1, i + 1):
print(chr(count), end='')
count += 1
print()
print("Pattern 4:")
print_alphabet_pattern()
###################################
#################################
Asssignment on functions
1. Write a program to demonstrate Nested function
def outer_function():
print("Outer function started.")
def inner_function():
print("Inner function executed.")
inner_function()
print("Outer function ended.")
outer_function()
2. Write a program to calculate factorial of a given number using recrursion
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
number = 5
print("Factorial of", number, "is", factorial(number))
3. Write a program to create decorators and generators
# Decorator
def uppercase_decorator(function):
def wrapper():
result = function()
return result.upper()
return wrapper
@uppercase_decorator
def greet():
return "hello, world!"
print(greet())
# Generator
def even_numbers(n):
for i in range(n):
if i % 2 == 0:
yield i
n = 10
even_nums = even_numbers(n)
print("Even numbers up to", n, ":", list(even_nums))
4. Create two different user defined modules and access respective functions from one file to another
# module1.py
def greet():
return "Hello, from module 1!"
# module2.py
def welcome():
return "Welcome, from module 2!"
# main.py
import module1
import module2
print(module1.greet())
print(module2.welcome())
5. write a program to access built in functions available in math, random and datetime modules
import math
import random
import datetime
# Math module
print("Square root of 25:", math.sqrt(25))
print("Ceiling of 4.6:", math.ceil(4.6))
# Random module
print("Random integer between 1 and 10:", random.randint(1, 10))
print("Random floating point number between 0 and 1:", random.random())
# Datetime module
current_time = datetime.datetime.now()
print("Current date and time:", current_time)
################################
################################
File io
1. Write Python program to read file word by word
def read_file_word_by_word(file_name):
with open(file_name, 'r') as file:
for line in file:
words = line.split()
for word in words:
print(word)
file_name = "sample.txt"
read_file_word_by_word(file_name)
2. Write Python program to read character by character from a file
def read_file_character_by_character(file_name):
with open(file_name, 'r') as file:
while True:
char = file.read(1)
if not char:
break
print(char)
file_name = "sample.txt"
read_file_character_by_character(file_name)
3. Write Python program to Get number of characters, words, spaces and lines in a file
def count_file_statistics(file_name):
lines = words = characters = spaces = 0
with open(file_name, 'r') as file:
for line in file:
lines += 1
words += len(line.split())
characters += len(line)
spaces += line.count(' ')
print("Number of lines:", lines)
print("Number of words:", words)
print("Number of characters:", characters)
print("Number of spaces:", spaces)
file_name = "sample.txt"
count_file_statistics(file_name)
4. Write Python program to Count the Number of occurrences of a key-value pair in a text file
def count_key_value_occurrences(file_name, key, value):
count = 0
with open(file_name, 'r') as file:
for line in file:
if key in line and value in line:
count += 1
print("Number of occurrences:", count)
file_name = "sample.txt"
key = "color"
value = "blue"
count_key_value_occurrences(file_name, key, value)
5. Write Python program to Find ānā Character Words in a Text File
def find_n_character_words(file_name, n):
with open(file_name, 'r') as file:
for line in file:
words = line.split()
for word in words:
if len(word) == n:
print(word)
file_name = "sample.txt"
n = 5
find_n_character_words(file_name, n)
6. Write Python program to Count number of lines in a text file in Python
def count_number_of_lines(file_name):
count = 0
with open(file_name, 'r') as file:
for line in file:
count += 1
print("Number of lines:", count)
file_name = "sample.txt"
count_number_of_lines(file_name)
7. Write Python program to read List of Dictionaries from File
import ast
def read_list_of_dictionaries(file_name):
with open(file_name, 'r') as file:
data = file.read()
dictionaries = ast.literal_eval(data)
for dictionary in dictionaries:
print(dictionary)
file_name = "sample.txt"
read_list_of_dictionaries(file_name)
8. Write Python program to Append content of one text file to another
def append_file_content(source_file, target_file):
with open(source_file, 'r') as source:
with open(target_file, 'a') as target:
target.write(source.read())
source_file = "source.txt"
target_file = "target.txt"
append_file_content(source_file, target_file)
9. Write Python program to reverse the content of a file and store it in another file
def reverse_file_content(source_file, target_file):
with open(source_file, 'r') as source:
content = source.read()
with open(target_file, 'w') as target:
target.write(content[::-1])
source_file = "source.txt"
target_file = "target.txt"
reverse_file_content(source_file, target_file)
10.Write Python program to merge two files into a third file
def merge_files(file1, file2, merged_file):
with open(file1, 'r') as f1:
content1 = f1.read()
with open(file2, 'r') as f2:
content2 = f2.read()
with open(merged_file, 'w') as merged:
merged.write(content1)
merged.write(content2)
file1 = "file1.txt"
file2 = "file2.txt"
merged_file = "merged.txt"
merge_files(file1, file2, merged_file)
#################################
#################################
Assignment on Exception Handling
A] Write Python program to demonstrate the following:
1. SyntaxError
2. TypeError
3. IndexError
4. ValueError
5. ZeroDivisionError
6. fileNotFound
# SyntaxError
print("Hello, World!" # missing closing parenthesis
# TypeError
x = "5"
y = 10
z = x + y # trying to concatenate string and integer
# IndexError
my_list = [1, 2, 3]
print(my_list[3]) # accessing element at index 3 (which is out of bounds)
# ValueError
number = int("abc") # trying to convert a non-numeric string to an integer
# ZeroDivisionError
result = 10 / 0 # dividing a number by zero
# FileNotFoundError
file = open("nonexistent.txt") # trying to open a non-existent file
B] Write Python program to raise user defined exception
def calculate_square_root(num):
if num < 0:
raise ValueError("Cannot calculate square root of a negative number.")
return num ** 0.5
try:
number = -10
result = calculate_square_root(number)
print("Square root:", result)
except ValueError as error:
print("Error:", error)
C] Write Python program to demonstrate the use of try, except and finally block
try:
numerator = 10
denominator = 0
result = numerator / denominator
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
finally:
print("Finally block executed.")
D] Write Python program to demonstrate default except block
try:
x = 10
y = "5"
sum = x + y
print("Sum:", sum)
except:
print("Error occurred.")
E] Write Python program to handle multiple exceptions in single except block
try:
num = int("abc")
result = 10 / 0
my_list = [1, 2, 3]
print(my_list[3])
except (ValueError, ZeroDivisionError, IndexError) as error:
print("Error:", error)
#######################
##########################
Assignment on Multithreading
Write a program to create two threads and execute them parallelly.
import threading
# Function to be executed in the first thread
def thread_one_function():
for i in range(5):
print("Thread One -", i)
# Function to be executed in the second thread
def thread_two_function():
for i in range(5):
print("Thread Two -", i)
# Create two threads
thread_one = threading.Thread(target=thread_one_function)
thread_two = threading.Thread(target=thread_two_function)
# Start the threads
thread_one.start()
thread_two.start()
# Wait for the threads to finish
thread_one.join()
thread_two.join()
print("Threads execution completed.")
#######################
#######################
Assignment on Regular Expression
Write a program to validate 1) URL 2) Email ID and 3) Password
Write 3 different functions.
import re
# Function to validate a URL
def validate_url(url):
pattern = re.compile(r'^(https?://)?(www\.)?\w+\.\w{2,3}$')
if re.match(pattern, url):
return True
else:
return False
# Function to validate an email ID
def validate_email(email):
pattern = re.compile(r'^[\w\.-]+@[\w\.-]+\.\w+$')
if re.match(pattern, email):
return True
else:
return False
# Function to validate a password
def validate_password(password):
pattern = re.compile(r'^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@#$%^&+=]).{8,}$')
if re.match(pattern, password):
return True
else:
return False
# Test the functions
url = "https://www.example.com"
email = "[email protected]"
password = "Pass@123"
# Validate URL
if validate_url(url):
print("URL is valid.")
else:
print("URL is invalid.")
# Validate email
if validate_email(email):
print("Email is valid.")
else:
print("Email is invalid.")
# Validate password
if validate_password(password):
print("Password is valid.")
else:
print("Password is invalid.")
##############################
##############################
MongoDB
Install PyMongo:
pip install pymongo
Connect to MongoDB:
from pymongo import MongoClient
# Create a MongoClient instance
client = MongoClient('mongodb://localhost:27017/')
# Select a database
db = client['mydatabase']
# Select a collection
collection = db['mycollection']
#################
Create (Insert):
# Insert a single document
document = {'name': 'John', 'age': 30}
result = collection.insert_one(document)
print('Inserted ID:', result.inserted_id)
# Insert multiple documents
documents = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 35}]
result = collection.insert_many(documents)
print('Inserted IDs:', result.inserted_ids)
###################
Read (Query):
# Find all documents in the collection
all_documents = collection.find()
for document in all_documents:
print(document)
# Find documents that match a specific condition
query = {'age': {'$gte': 30}} # Find documents where age is greater than or equal to 30
matching_documents = collection.find(query)
for document in matching_documents:
print(document)
###########################
Update:
# Update a single document
query = {'name': 'John'}
new_values = {'$set': {'age': 32}}
result = collection.update_one(query, new_values)
print('Modified Count:', result.modified_count)
# Update multiple documents
query = {'age': {'$lt': 30}} # Update documents where age is less than 30
new_values = {'$inc': {'age': 2}} # Increment age by 2
result = collection.update_many(query, new_values)
print('Modified Count:', result.modified_count)
###############
Delete:
# Delete a single document
query = {'name': 'John'}
result = collection.delete_one(query)
print('Deleted Count:', result.deleted_count)
# Delete multiple documents
query = {'age': {'$gte': 40}} # Delete documents where age is greater than or equal to 40
result = collection.delete_many(query)
print('Deleted Count:', result.deleted_count)
##########
client.close()
Write, Run & Share Java code online using OneCompiler's Java online compiler for free. It's one of the robust, feature-rich online compilers for Java language, running the Java LTS version 17. Getting started with the OneCompiler's Java editor is easy and fast. The editor shows sample boilerplate code when you choose language as Java and start coding.
OneCompiler's Java online editor supports stdin and users can give inputs to the programs using the STDIN textbox under the I/O tab. Using Scanner class in Java program, you can read the inputs. Following is a sample program that shows reading STDIN ( A string in this case ).
import java.util.Scanner;
class Input {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your name: ");
String inp = input.next();
System.out.println("Hello, " + inp);
}
}
OneCompiler supports Gradle for dependency management. Users can add dependencies in the build.gradle file and use them in their programs. When you add the dependencies for the first time, the first run might be a little slow as we download the dependencies, but the subsequent runs will be faster. Following sample Gradle configuration shows how to add dependencies
apply plugin:'application'
mainClassName = 'HelloWorld'
run { standardInput = System.in }
sourceSets { main { java { srcDir './' } } }
repositories {
jcenter()
}
dependencies {
// add dependencies here as below
implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'
}
Java is a very popular general-purpose programming language, it is class-based and object-oriented. Java was developed by James Gosling at Sun Microsystems ( later acquired by Oracle) the initial release of Java was in 1995. Java 17 is the latest long-term supported version (LTS). As of today, Java is the world's number one server programming language with a 12 million developer community, 5 million students studying worldwide and it's #1 choice for the cloud development.
short x = 999; // -32768 to 32767
int x = 99999; // -2147483648 to 2147483647
long x = 99999999999L; // -9223372036854775808 to 9223372036854775807
float x = 1.2;
double x = 99.99d;
byte x = 99; // -128 to 127
char x = 'A';
boolean x = true;
When ever you want to perform a set of operations based on a condition If-Else is used.
if(conditional-expression) {
// code
} else {
// code
}
Example:
int i = 10;
if(i % 2 == 0) {
System.out.println("i is even number");
} else {
System.out.println("i is odd number");
}
Switch is an alternative to If-Else-If ladder and to select one among many blocks of code.
switch(<conditional-expression>) {
case value1:
// code
break; // optional
case value2:
// code
break; // optional
...
default:
//code to be executed when all the above cases are not matched;
}
For loop is used to iterate a set of statements based on a condition. Usually for loop is preferred when number of iterations is known in advance.
for(Initialization; Condition; Increment/decrement){
//code
}
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while(<condition>){
// code
}
Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.
do {
// code
} while (<condition>);
Class is the blueprint of an object, which is also referred as user-defined data type with variables and functions. Object is a basic unit in OOP, and is an instance of the class.
class keyword is required to create a class.
class Mobile {
public: // access specifier which specifies that accessibility of class members
string name; // string variable (attribute)
int price; // int variable (attribute)
};
Mobile m1 = new Mobile();
public class Greeting {
static void hello() {
System.out.println("Hello.. Happy learning!");
}
public static void main(String[] args) {
hello();
}
}
Collection is a group of objects which can be represented as a single unit. Collections are introduced to bring a unified common interface to all the objects.
Collection Framework was introduced since JDK 1.2 which is used to represent and manage Collections and it contains:
This framework also defines map interfaces and several classes in addition to Collections.
| Collection | Description |
|---|---|
| Set | Set is a collection of elements which can not contain duplicate values. Set is implemented in HashSets, LinkedHashSets, TreeSet etc |
| List | List is a ordered collection of elements which can have duplicates. Lists are classified into ArrayList, LinkedList, Vectors |
| Queue | FIFO approach, while instantiating Queue interface you can either choose LinkedList or PriorityQueue. |
| Deque | Deque(Double Ended Queue) is used to add or remove elements from both the ends of the Queue(both head and tail) |
| Map | Map contains key-values pairs which don't have any duplicates. Map is implemented in HashMap, TreeMap etc. |