WT&DA
WT&DA
Q. 1) Write a PHP script to keep track of number of times the web page has been accessed (Use
Session Tracking).
Solution:
<?php
session_start();
if(isset($_SESSION['page_views'])) {
$_SESSION['page_views']++;
} else {
$_SESSION['page_views'] = 1;
?>
Q. 2)Create ‘Position_Salaries’ Data set. Build a linear regression model by identifying independent
and target variable. Split the variables into training and testing sets. then divide the training and
testing sets into a 7:3 ratio, respectively and print them. Build a simple linear regression model.
Solution:
import pandas as pd
data = {
'CEO'],
df = pd.DataFrame(data)
one_hot_encoder = OneHotEncoder(sparse_output=False)
encoded_positions = one_hot_encoder.fit_transform(df[['Position']])
encoded_positions_df = pd.DataFrame(encoded_positions,
columns=one_hot_encoder.get_feature_names_out(['Position']))
1
df_encoded.drop(columns=['Position'], inplace=True)
X = df_encoded.drop(columns=['Salary'])
y = df_encoded['Salary']
print("Training data:")
print(X_train)
print(y_train)
print("\nTesting data:")
print(X_test)
print(y_test)
model = LinearRegression()
model.fit(X_train, y_train)
Slip 2)
Q. 1Write a PHP script to change the preferences of your web page like font style, font size, font
color, background color using cookie. Display selected setting on next web page and actual
implementation (with new settings) on third page (Use Cookies).
Solution:
<!DOCTYPE html>
<html>
<head>
<title>Change Preferences</title>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
2
setcookie('bg_color', $_POST['bg_color'], time() + (86400 * 30), "/");
header("Location: {$_SERVER['PHP_SELF']}");
exit;
?>
<h2>Change Preferences</h2>
Font Style:
<select name="font_style">
<option value="Arial">Arial</option>
</select><br><br>
Font Size:
<select name="font_size">
<option value="small">Small</option>
<option value="medium">Medium</option>
<option value="large">Large</option>
</select><br><br>
Font Color:
Background Color:
</form>
<?php
&& isset($_COOKIE['bg_color'])) {
3
echo "</div>";
?>
</body>
</html>
Q. 2)Create ‘Salary’ Data set . Build a linear regression model by identifying independent and target
variable. Split the variables into training and testing sets and print them. Build a simple linear
regression model for predicting purchases.
Solution:
import numpy as np
salary = np.array([30000, 35000, 40000, 45000, 50000, 55000, 60000, 65000, 70000, 75000])
print("Training set:")
print("X_train:", X_train)
print("y_train:", y_train)
print("\nTes ng set:")
print("X_test:", X_test)
print("y_test:", y_test)
model = LinearRegression()
model.fit(X_train, y_train)
predicted_salary = model.predict(new_experience)
Slip 3)
Q. 1) Write a PHP script to accept username and password. If in the first three chances, username
and password entered is correct then display second form with “Welcome message” otherwise
display error message. [Use Session]
Solution:
4
<?php
session_start();
$correct_username = "user";
$correct_password = "pass";
if (!isset($_SESSION['login_attempts'])) {
$_SESSION['login_attempts'] = 0;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$_SESSION['login_attempts']++;
$entered_username = $_POST['username'];
$entered_password = $_POST['password'];
$_SESSION['login_attempts'] = 0;
header("Location: welcome.php");
exit();
} else {
if ($_SESSION['login_attempts'] >= 3) {
$_SESSION['login_attempts'] = 0;
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
5
<p><?php echo $error_message; ?></p>
<?php } ?>
<h2>Login</h2>
</form>
</body>
</html>
2)welcome.php
<!DOCTYPE html>
<html>
<title>Welcome</title>
<h1>Welcome</h1>
</html>
Q. 2)Create ‘User’ Data set having 5 columns namely: User ID, Gender, Age, Estimated Salary and
Purchased. Build a logistic regression model that can predict whether on the given parameter a
person will buy a car or not.
Solution:
import pandas as pd
data = {
'Purchased': [0, 1, 0, 1, 0]
6
}
df = pd.DataFrame(data)
y = df['Purchased']
X = pd.get_dummies(X, drop_first=True)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
model = LogisticRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print("Confusion Matrix:")
print(confusion_matrix(y_test, y_pred))
print("\nClassification Report:")
print(classification_report(y_test, y_pred))
Slip10)
Q1.Create a HTML fileto insert text before and after a Paragraph using jQuery. [Hint : Use before( )
and after( )]
Solution:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
7
// Function to insert text before and after a paragraph
$("#btnInsertText").click(function(){
});
});
</script>
</head>
<body>
</body>
</html>
Q. 2)Create the following dataset in python & Convert the categorical values into numeric
format.Apply the apriori algorithm on the above dataset to generate the frequent itemsets and
association rules. Repeat the process with different min_sup values.
TID Items
1 'eggs', 'milk','bread'
2 'eggs', 'apple'
3 'milk', 'bread'
4 'apple', 'milk'
5 'milk', 'apple', 'bread'
Solution:
import pandas as pd
data = {
'bread']]}
8
df = pd.DataFrame(data)
min_sup = 0.5
min_support=min_sup, use_colnames=True)
print("Frequent itemsets:")
print(frequent_itemsets)
print("Association rules:")
print(rules)
Slip11)
Q1.)Write a Javascript program to accept name of student, change font color to red, font size to 18 if
student name is present otherwise on clicking on empty text box display image which changes its size
Solution:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student Details</title>
<style>
.red-text {
color: red;
.big-size {
font-size: 18px;
</style>
</head>
<body>
9
<script>
function changeStyle() {
if (name) {
} else {
function displayImageSize() {
</script>
<h2>Student Details</h2>
onmouseout="this.style.border='none'" onclick="displayImageSize()"
onmouseup="this.style.border='none'">
</body>
</html>
Q. 2)Create the following dataset in python & Convert the categorical values into numeric
format.Apply the apriori algorithm on the above dataset to generate the frequent itemsets and
associationrules. Repeat the process with different min_sup values.
TID Items
1 butter, bread, milk
2 butter, flour, milk, sugar
3 butter, eggs, milk, salt
10
4 eggs
5 butter, flour, milk, salt
Solution:
import pandas as pd
[],
[],
df = pd.DataFrame(data)
te = TransactionEncoder()
encoded_data = te.fit_transform(df['Items'])
print(df_encoded)
min_sup = 0.5
print("Frequent itemsets:")
print(frequent_itemsets)
print("Association rules:")
print(association_rules_df)
Slip12)
Q. 1)Write AJAX program to read contact.dat file and print the contents of the file in a tabular format
when the user clicks on print button. Contact.dat file should contain srno, name, residence number,
Solution:
<!DOCTYPE html>
11
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Information</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div id="contactTable"></div>
<script>
$(document).ready(function(){
$("#printBtn").click(function(){
$.ajax({
url: 'contact.dat',
type: 'GET',
dataType: 'text',
success: function(data) {
Number</th><th>Address</th></tr>';
table += '<tr>';
table += '</tr>';
table += '</table>';
12
$("#contactTable").html(table);
},
error: function() {
});
});
});
</script>
</body>
</html>
Solution:
import numpy as np
np.random.seed(0)
X = heights.reshape(-1, 1)
y = weights
print("X_train:", X_train.shape)
print("y_train:", y_train.shape)
print("X_test:", X_test.shape)
print("y_test:", y_test.shape)
model = LinearRegression()
model.fit(X_train, y_train)
13
train_score = model.score(X_train, y_train)
Slip 16)
Q1.Write Ajax program to get book details from XML file when user select a book name. Create XML
file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Book Details</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#bookName').change(function(){
$.ajax({
url: 'books.xml',
dataType: 'xml',
success: function(data){
$(data).find('book').each(function(){
14
bookDetails += '<tr><td>Title:</td><td>' + title + '</td></tr>';
});
$('#bookDetails').html(bookDetails);
});
});
});
</script>
</head>
<body>
<h2>Select a Book:</h2>
<select id="bookName">
<option value="">Select</option>
</select>
<br><br>
<h2>Book Details:</h2>
</body>
</html>
Q. 2)Consider any text paragraph. Preprocess the text to remove any special characters and digits.
Generate the summary using extractive summarization process
Solution:
import re
15
from nltk.tokenize import sent_tokenize
def preprocess_text(text):
return text
preprocessed_text = preprocess_text(text)
sentences = sent_tokenize(preprocessed_text)
word_freq = Counter(preprocessed_text.split())
top_sentences = sorted(sentence_scores,
key=sentence_scores.get,reverse=True)[:num_sentences]
return summary
processing frequently
16
NLP technologies are having a profound impact on the way people
summary = generate_summary(text)
print("Summary:")
print(summary)
Slip17)
Q1)Write a Java Script Program to show Hello Good Morning message onload event using alert
boxand display the Student registration from
Solution:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student Registration</title>
<script>
window.onload = function() {
};
</script>
</head>
<body>
<form id="registrationForm">
17
<label for="name">Name:</label><br>
<label for="email">Email:</label><br>
<label for="course">Course:</label><br>
<option value="Mathematics">Mathematics</option>
<option value="Physics">Physics</option>
</select><br><br>
</form>
</body>
</html>
Q. 2)Consider text paragraph.So, keep working. Keep striving. Never give up. Fall down seven times,
getup eight. Ease is a greater threat to progress than hardship. Ease is a greater threat to progress
thanhardship. So, keep moving, keep growing, keep learning. See you at work.Preprocess the text to
removeany special characters and digits. Generate the summary using extractive summarization
process.
Solution:
import re
import nltk
nltk.download('punkt')
text = """So, keep working. Keep striving. Never give up. Fall down seven times, get up eight.
So, keep moving, keep growing, keep learning. See you at work."""
def preprocess_text(text):
18
return text.lower()
sentences = sent_tokenize(text)
processed_text = preprocess_text(text)
tfidf_vectorizer = TfidfVectorizer().fit_transform(sentences)
tfidf_matrix = tfidf_vectorizer.toarray()
scores = cosine_matrix.sum(axis=1)
cleaned_text = preprocess_text(text)
summary = extractive_summary(text)
print("Summary:", summary)
Slip18)
Q. 1) Write a Java Script Program to print Fibonacci numbers on onclick event.
Solution:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Fibonacci Numbers</title>
<script>
function generateFibonacci() {
let n = parseInt(document.getElementById("number").value);
19
document.getElementById("result").innerText = fib.slice(0, n).join(", ");
</script>
</head>
<body>
<p id="result"></p>
</body>
</html>
Q. 2)Consider any text paragraph. Remove the stopwords. Tokenize the paragraph to extract words
and sentences. Calculate the word frequency distribution and plot the frequencies. Plot the
wordcloud of the text.
Solution:
import nltk
text_paragraph = """
words = word_tokenize(text_paragraph.lower())
stop_words = set(stopwords.words("english"))
20
filtered_words = [word for word in words if word not in stop_words]
sentences = sent_tokenize(text_paragraph)
word_freq = FreqDist(filtered_words)
plt.figure(figsize=(10, 5))
background_color='white').generate_from_frequencies(word_freq)
plt.figure(figsize=(10, 5))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.title('Word Cloud')
plt.show()
21