Snippets Collections
import java.sql.Statement;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Date;
public class jdbcInsert {
    public static void main(String[] args) throws ClassNotFoundException,SQLException{
        Connection conn = null;
        Statement st = null;
        try
        {
            conn = DriverManager.getConnection("jdbc:oracle:thin:@//localhost:1521/XE", "system", "1808");
            st = conn.createStatement();
            int row= st.executeUpdate("Insert into employee values (7990,'manish','salesman',7755,TO_DATE('17-DEC-24', 'DD-MON-RRRR'),1000,30,25)");
            ResultSet rs1 = st.executeQuery("select * from employee");
            while (rs1.next()) {
                int id=rs1.getInt(1);
                String ename = rs1.getString(2);
                String job = rs1.getString(3);
                int mgr = rs1.getInt(4);
                Date hiredate = rs1.getDate(5);
                int sal = rs1.getInt(6);
                int com = rs1.getInt(7);
                int deptno = rs1.getInt(8);
                System.out.println(id+" "+ename+" "+job+" "+mgr+" "+hiredate+" "+sal + " "+com+" "+deptno);
            }
        }catch(SQLException e)
        {
            e.printStackTrace();
        }
    }
}
import java.sql.Statement;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class jdbcselect {
    public static void main(String[] args) {
        Connection conn = null;
        Statement st = null;
        try{
            conn = DriverManager.getConnection("jdbc:oracle:thin:@//localhost:1521/XE", "system", "1808");
            st = conn.createStatement();
            ResultSet rs1 = st.executeQuery("select * from employee");
            while(rs1.next())
            {
                int id = rs1.getInt(1);
                String name = rs1.getString(2);
                String job = rs1.getString(3);
                int mgr = rs1.getInt(4);
                Date date = rs1.getDate(5);
                int sal = rs1.getInt(6);
                int com = rs1.getInt(7);
                int deptno = rs1.getInt(8);
                System.out.println(
                        id + "," + name + "," + job + "," + mgr + "," + date + "," + sal + "," + com + "," + deptno); 
            }
        }catch(SQLException e)
        {
            e.printStackTrace();
        }
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Grid Layout</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
        }
        header {
            background-color: #4CAF50;
            color: white;
            padding: 15px;
            text-align: center;
        }
        .grid-container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 10px;
            padding: 20px;
        }
        .card {
            background-color: #f9f9f9;
            border: 1px solid #ccc;
            border-radius: 5px;
            padding: 20px;
            text-align: center;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
    </style>
</head>
<body>
    <header>
        <h1>Simple Grid Layout</h1>
    </header>
    <main>
        <div class="grid-container">
            <div class="card">
                <h2>Card 1</h2>
                <p>This is a simple card.</p>
            </div>
            <div class="card">
                <h2>Card 2</h2>
                <p>This is another simple card.</p>
            </div>
            <div class="card">
                <h2>Card 3</h2>
                <p>This is yet another simple card.</p>
            </div>
            <div class="card">
                <h2>Card 4</h2>
                <p>This is an additional card.</p>
            </div>
        </div>
    </main>
</body>
</html>
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
import seaborn as sns

df_petrol = pd.read_csv('petrol_consumption.csv')
print(df_petrol.head())
df_petrol.info()
#
df_petrol.isnull().sum()
#
df_petrol.fillna(df_petrol.mean(),inplace=True)
#
sns.pairplot(df_petrol,hue="Petrol_Consumption")
plt.show()
#
#PCA
scaler = StandardScaler()
df = scaler.fit_transform(df)

pca = PCA(n_components=2)
df_pca = pca.fit_transform(df)
df = pd.DataFrame(data = df_pca,columns=['PC1','PC2'])
df["Petrol_Consumption"] = df_petrol["Petrol_Consumption"]
sns.scatterplot(x='PC1',y='PC2',data = df,hue="Petrol_Consumption")
plt.show()

#Rfe
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.feature_selection import RFE
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

df = pd.read_csv("Fish.csv")
print(df.head())
df.info()
#
X = df.drop('Species',axis=1)
y = df['Species']

y.info()
#
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.2,random_state=42)

dtc = DecisionTreeClassifier()
dtc.fit(X_train,y_train)
y_pred = dtc.predict(X_test)
print(y_pred)
print(y_test)

accuracy = accuracy_score(y_test,y_pred)
print(accuracy)
#
from sklearn.tree import DecisionTreeClassifier
from sklearn.preprocessing import LabelEncoder

df = pd.read_csv('Iris.csv')
df.info()
#
encoder = LabelEncoder()
df["Species"] = encoder.fit_transform(df["Species"])
#
df.info()
#
X = df.iloc[:,:-1] #df.drop(columns=["speices"])
y = df.iloc[:,-1] #df["species"]
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=42)
dtc = DecisionTreeClassifier()
dtc.fit(X_train,y_train)
y_pred = dtc.predict(X_test)
print(y_test,y_pred)
#
from sklearn.metrics import accuracy_score,classification_report,confusion_matrix

accuracy = accuracy_score(y_pred,y_test)
print(accuracy)
print(classification_report(y_pred,y_test))
print(confusion_matrix(y_pred,y_test))
#
# prompt: Visualize insights of Above decision tree classification on iris dataset

from sklearn import tree
import matplotlib.pyplot as plt

plt.figure(figsize=(15,10))
tree.plot_tree(dtc,filled=True,feature_names=X.columns,class_names=['0','1','2'])
plt.show()
#from sklearn.neighbors import KNeighborsClassifier

df = pd.read_csv('diabetes.csv')
df.info()
#
X = df.iloc[:,:-1] #df.drop("Outcome",axis=1)
y = df.iloc[:,-1]
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=42)
knn = KNeighborsClassifier(n_neighbors=2)
knn.fit(X_train,y_train)
y_pred = knn.predict(X_test)
print(y_test,y_pred)
#
accuracy = accuracy_score(y_pred,y_test)
print(accuracy)
print(classification_report(y_pred,y_test))
print(confusion_matrix(y_pred,y_test))
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flexbox Layout Example</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
        }
        header {
            background-color: #4CAF50;
            color: white;
            padding: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        nav {
            display: flex;
            gap: 15px;
        }
        .container {
            display: flex;
            justify-content: space-around;
            margin: 20px;
            flex-wrap: wrap;
        }
        .card {
            background-color: #f9f9f9;
            border: 1px solid #ccc;
            border-radius: 5px;
            padding: 20px;
            width: 30%;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            text-align: center;
            margin: 10px;
        }
        @media (max-width: 768px) {
            .card {
                width: 100%; /* Full width on small screens */
            }
        }
    </style>
</head>
<body>
    <header>
        <h1>Flexbox Layout</h1>
        <nav>
            <a href="#" style="color: white;">Home</a>
            <a href="#" style="color: white;">About</a>
            <a href="#" style="color: white;">Services</a>
            <a href="#" style="color: white;">Contact</a>
        </nav>
    </header>
    <main>
        <div class="container">
            <div class="card">
                <h2>Card 1</h2>
                <p>This is a simple card.</p>
            </div>
            <div class="card">
                <h2>Card 2</h2>
                <p>This is another simple card.</p>
            </div>
            <div class="card">
                <h2>Card 3</h2>
                <p>This is yet another simple card.</p>
            </div>
        </div>
    </main>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Demo</title>
    <link rel="stylesheet" href="styles.css"> <!-- Link to external CSS -->
    <style>
        /* Internal CSS */
        h2 {
            color: green;
            text-align: center;
        }
    </style>
</head>
<body>
    <h1 style="color: blue; text-align: center;">Welcome to CSS Demo</h1> <!-- Inline CSS -->

    <h2>Internal CSS Example</h2>
    <p>This paragraph demonstrates the use of internal CSS for styling headings.</p>

    <h2 style="color: orange;">Inline CSS Example</h2>
    <p>This paragraph is styled using inline CSS for the heading.</p>

    <h2 class="external-header">External CSS Example</h2>
    <p>This paragraph demonstrates the use of external CSS for styling.</p>
</body>
</html>


/* External CSS */
body {
    background-color: #f4f4f4;
    font-family: Arial, sans-serif;
}

.external-header {
    color: purple;
    text-align: center;
}
#Decision Tree Classification

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score,classification_report,confusion_matrix
import pandas as pd

iris = load_iris()
df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
df['species'] = iris.target
print(df.head())
print(df.info())
X = df.drop('species', axis=1)
y = df['species']
x_train,x_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=42)
model = DecisionTreeClassifier()
model.fit(x_train,y_train)
y_pred = model.predict(x_test)
accuracy = accuracy_score(y_test,y_pred)
print("Accuracy:",accuracy)
print("Classification Report:\n",classification_report(y_test,y_pred))
print("Confusion Matrix:\n",confusion_matrix(y_test,y_pred))
output:
   sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)  \
0                5.1               3.5                1.4               0.2   
1                4.9               3.0                1.4               0.2   
2                4.7               3.2                1.3               0.2   
3                4.6               3.1                1.5               0.2   
4                5.0               3.6                1.4               0.2   

   species  
0        0  
1        0  
2        0  
3        0  
4        0  
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 150 entries, 0 to 149
Data columns (total 5 columns):
 #   Column             Non-Null Count  Dtype  
---  ------             --------------  -----  
 0   sepal length (cm)  150 non-null    float64
 1   sepal width (cm)   150 non-null    float64
 2   petal length (cm)  150 non-null    float64
 3   petal width (cm)   150 non-null    float64
 4   species            150 non-null    int64  
dtypes: float64(4), int64(1)
memory usage: 6.0 KB
None
Accuracy: 1.0
Classification Report:
               precision    recall  f1-score   support

           0       1.00      1.00      1.00        10
           1       1.00      1.00      1.00         9
           2       1.00      1.00      1.00        11

    accuracy                           1.00        30
   macro avg       1.00      1.00      1.00        30
weighted avg       1.00      1.00      1.00        30

Confusion Matrix:
 [[10  0  0]
 [ 0  9  0]
 [ 0  0 11]]
2.#K-Neareast Nrighbour
#K-Neareast Nrighbour
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
from sklearn.metrics import accuracy_score,classification_report,confusion_matrix
from sklearn.neighbors import KNeighborsClassifier
iris = load_iris()
df = pd.DataFrame(data=iris.data,columns=iris.feature_names)
df['species']=iris.target
print(df.head())
print(df.info())
x = df.drop('species',axis=1)
y = df['species']
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.2,random_state=42)
knn = KNeighborsClassifier(n_neighbors=1)
knn.fit(x_train,y_train)
y_pred = knn.predict(x_test)
accuracy = accuracy_score(y_test,y_pred)
print("Accuracy:",accuracy)
print("Classification Report:\n",classification_report(y_test,y_pred))
print("Confusion Matrix:\n",confusion_matrix(y_test,y_pred))
output:
]
#K-Neareast Nrighbour
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
from sklearn.metrics import accuracy_score,classification_report,confusion_matrix
from sklearn.neighbors import KNeighborsClassifier
iris = load_iris()
df = pd.DataFrame(data=iris.data,columns=iris.feature_names)
df['species']=iris.target
print(df.head())
…print("Confusion Matrix:\n",confusion_matrix(y_test,y_pred))
   sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)  \
0                5.1               3.5                1.4               0.2   
1                4.9               3.0                1.4               0.2   
2                4.7               3.2                1.3               0.2   
3                4.6               3.1                1.5               0.2   
4                5.0               3.6                1.4               0.2   

   species  
0        0  
1        0  
2        0  
3        0  
4        0  
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 150 entries, 0 to 149
Data columns (total 5 columns):
 #   Column             Non-Null Count  Dtype  
---  ------             --------------  -----  
 0   sepal length (cm)  150 non-null    float64
 1   sepal width (cm)   150 non-null    float64
 2   petal length (cm)  150 non-null    float64
 3   petal width (cm)   150 non-null    float64
 4   species            150 non-null    int64  
dtypes: float64(4), int64(1)
memory usage: 6.0 KB
None
Accuracy: 1.0
Classification Report:
               precision    recall  f1-score   support

           0       1.00      1.00      1.00        10
           1       1.00      1.00      1.00         9
           2       1.00      1.00      1.00        11

    accuracy                           1.00        30
   macro avg       1.00      1.00      1.00        30
weighted avg       1.00      1.00      1.00        30

Confusion Matrix:
 [[10  0  0]
 [ 0  9  0]
 [ 0  0 11]]
1.
from sklearn.datasets import load_iris
import pandas as pd
iris=load_iris()
df=pd.DataFrame(data=iris.data, columns=iris.feature_names)
print("DataFrame Head:\n",df.head())
print("DataInfo:\n",df.info())

output
DataFrame Head:
    sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)
0                5.1               3.5                1.4               0.2
1                4.9               3.0                1.4               0.2
2                4.7               3.2                1.3               0.2
3                4.6               3.1                1.5               0.2
4                5.0               3.6                1.4               0.2
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 150 entries, 0 to 149
Data columns (total 4 columns):
 #   Column             Non-Null Count  Dtype  
---  ------             --------------  -----  
 0   sepal length (cm)  150 non-null    float64
 1   sepal width (cm)   150 non-null    float64
 2   petal length (cm)  150 non-null    float64
 3   petal width (cm)   150 non-null    float64
dtypes: float64(4)
memory usage: 4.8 KB
DataInfo:
 None
2.
from sklearn.preprocessing import StandardScaler
scaler=StandardScaler()
x_scaled=scaler.fit_transform(df)
from sklearn.cluster import KMeans
Kmeans=KMeans(n_clusters=3, random_state=42)
Kmeans.fit((x_scaled))
clusters_labels=Kmeans.labels_
df['cluster']=clusters_labels
cluster_centers=Kmeans.cluster_centers_
print("cluster centers:\n",cluster_centers)

ouput

cluster centers:
 [[ 1.13597027  0.08842168  0.99615451  1.01752612]
 [-1.01457897  0.85326268 -1.30498732 -1.25489349]
 [-0.05021989 -0.88337647  0.34773781  0.2815273 ]]

3.

from sklearn.metrics import adjusted_rand_score,silhouette_score
true_labels=iris.target
ari=adjusted_rand_score(true_labels,clusters_labels)
print(f"Adjusted Rand_Index(ARI):{ari}")
silhouette_avg=silhouette_score(x_scaled,clusters_labels)
print(f"sithouette score : {silhouette_avg}")

ouput

Adjusted Rand_Index(ARI):0.6201351808870379
sithouette score : 0.45994823920518635

ll.1

#Hierarchial clustering
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
from scipy.cluster.hierarchy import dendrogram,linkage
from scipy.cluster.hierarchy import fcluster
iris=load_iris()
data=pd.DataFrame(iris.data,columns=iris.feature_names)
scaler=StandardScaler()
scaled_data=scaler.fit_transform(data)
z=linkage(scaled_data,method="ward")
plt.figure(figsize=(10,7))
plt.title("Dendogram for Iris dataset")
dendrogram(z,labels=iris.target)
plt.show()
clusters=fcluster(z,3,criterion="maxclust")
data['cluster']=clusters
data['species']=iris.target
print(data.groupby(['cluster','species']).size())
silhouette_avg=silhouette_score(scaled_data,clusters)
print(f"Silhouette score: {silhouette_avg}")

output
 

cluster  species
1        0          49
2        0           1
         1          27
         2           2
3        1          23
         2          48
dtype: int64
Silhouette score: 0.446689041028591
import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 
import seaborn as sns 
from sklearn.preprocessing import StandardScaler 
from sklearn.cluster import AgglomerativeClustering 
from sklearn.metrics import accuracy_score, confusion_matrix 
from scipy.cluster.hierarchy import dendrogram, linkage 
from sklearn.decomposition import PCA 
# Load the Iris dataset 
df = pd.read_csv('Iris.csv') 
# Display the first few rows to understand the structure (optional) 
print(df.head()) 
# Remove the 'Id' column if present 
df = df.drop(columns=['Id']) 
# Separate features and the actual labels (for comparison) 
X = df.drop(columns=['Species']) 
y_true = df['Species'] 
# Standardize the features 
scaler = StandardScaler() 
X_scaled = scaler.fit_transform(X) 
# Generate a dendrogram to visualize hierarchical clustering structure 
plt.figure(figsize=(10, 7)) 
linked = linkage(X_scaled, method='ward') 
dendrogram(linked, labels=y_true.values, orientation='top', distance_sort='descending', show_leaf_counts=True) 
plt.title("Dendrogram for Iris Dataset") 
plt.xlabel("Samples") 
plt.ylabel("Euclidean Distance") 
plt.show() 
# Apply Hierarchical Clustering 
hc = AgglomerativeClustering(n_clusters=3, affinity='euclidean', linkage='ward') 
y_hc = hc.fit_predict(X_scaled) 
# Map cluster labels to actual classes for accuracy estimation 
y_hc_mapped = np.zeros_like(y_hc) 
for i in range(3): 
mask = (y_hc == i) 
y_hc_mapped[mask] = np.bincount(y_true[mask].factorize()[0]).argmax() 
# Estimate accuracy by comparing clusters to actual labels 
accuracy = accuracy_score(y_true.factorize()[0], y_hc_mapped) 
print("Estimated Accuracy of Hierarchical Clustering:", accuracy) 
# Confusion matrix to visualize clustering performance 
conf_matrix = confusion_matrix(y_true.factorize()[0], y_hc_mapped) 
plt.figure(figsize=(6, 4)) 
sns.heatmap(conf_matrix, annot=True, fmt="d", cmap="Blues", xticklabels=['Setosa', 'Versicolor', 'Virginica'], 
yticklabels=['Setosa', 'Versicolor', 'Virginica']) 
plt.xlabel("Cluster Label") 
plt.ylabel("True Label") 
plt.title("Confusion Matrix of Hierarchical Clustering") 
plt.show() 
# Visualize clusters using PCA (reduce to 2D for plotting) 
pca = PCA(n_components=2) 
X_pca = pca.fit_transform(X_scaled) 
# Plot the clusters and actual labels 
plt.figure(figsize=(12, 5)) 
# Plot hierarchical clusters 
plt.subplot(1, 2, 1) 
plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y_hc, cmap="viridis", s=50) 
plt.title("Hierarchical Clustering on Iris Dataset (PCA-reduced)") 
plt.xlabel("Principal Component 1") 
plt.ylabel("Principal Component 2") 
plt.colorbar(label="Cluster") 
# Plot actual species 
species_to_num = {'Iris-setosa': 0, 'Iris-versicolor': 1, 'Iris-virginica': 2} 
y_true_numeric = y_true.map(species_to_num) 
plt.subplot(1, 2, 2) 
plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y_true_numeric, cmap="viridis", s=50) 
plt.title("Actual Species Labels (PCA-reduced)") 
plt.xlabel("Principal Component 1") 
plt.ylabel("Principal Component 2") 
plt.colorbar(label="Species") 
plt.tight_layout() 
plt.show()
import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 
import seaborn as sns 
from sklearn.preprocessing import StandardScaler 
from sklearn.cluster import KMeans 
from sklearn.metrics import accuracy_score, confusion_matrix 
from sklearn.decomposition import PCA 
# Load the Iris dataset 
df = pd.read_csv('Iris.csv') 
# Display the first few rows (optional) 
print(df.head()) 
# Remove the 'Id' column if present 
df = df.drop(columns=['Id']) 
# Separate features and the actual labels (for comparison) 
X = df.drop(columns=['Species']) 
y_true = df['Species'] 
# Standardize the features 
scaler = StandardScaler() 
X_scaled = scaler.fit_transform(X) 
# Apply k-Means clustering 
kmeans = KMeans(n_clusters=3, random_state=42) 
kmeans.fit(X_scaled) 
y_kmeans = kmeans.labels_ 
# Map cluster labels to the actual classes for accuracy estimation 
# Since k-means labels are arbitrary, we map them using the most common species in each cluster. 
y_kmeans_mapped = np.zeros_like(y_kmeans) 
for i in range(3): 
mask = (y_kmeans == i) 
y_kmeans_mapped[mask] = np.bincount(y_true[mask].factorize()[0]).argmax() 
# Estimate accuracy by comparing clusters to actual labels 
accuracy = accuracy_score(y_true.factorize()[0], y_kmeans_mapped) 
print("Estimated Accuracy of k-Means Clustering:", accuracy) 
# Confusion matrix to visualize clustering performance 
conf_matrix = confusion_matrix(y_true.factorize()[0], y_kmeans_mapped) 
plt.figure(figsize=(6, 4)) 
sns.heatmap(conf_matrix, annot=True, fmt="d", cmap="Blues", xticklabels=['Setosa', 'Versicolor', 'Virginica'], 
yticklabels=['Setosa', 'Versicolor', 'Virginica']) 
plt.xlabel("Cluster Label") 
plt.ylabel("True Label") 
plt.title("Confusion Matrix of k-Means Clustering") 
plt.show() 
# Visualize clusters using PCA (reduce to 2D for plotting) 
pca = PCA(n_components=2) 
X_pca = pca.fit_transform(X_scaled) 
# Plot the clusters and actual labels 
plt.figure(figsize=(12, 5)) 
# Plot k-Means clusters 
plt.subplot(1, 2, 1) 
plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y_kmeans, cmap="viridis", s=50) 
plt.title("k-Means Clustering on Iris Dataset (PCA-reduced)") 
plt.xlabel("Principal Component 1") 
plt.ylabel("Principal Component 2") 
plt.colorbar(label="Cluster") 
# Plot actual species 
species_to_num = {'Iris-setosa': 0, 'Iris-versicolor': 1, 'Iris-virginica': 2} 
y_true_numeric = y_true.map(species_to_num) 
plt.subplot(1, 2, 2) 
plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y_true_numeric, cmap="viridis", s=50) 
plt.title("Actual Species Labels (PCA-reduced)") 
plt.xlabel("Principal Component 1") 
plt.ylabel("Principal Component 2") 
plt.colorbar(label="Species") 
plt.tight_layout() 
plt.show()
import pandas as pd 
import matplotlib.pyplot as plt 
import seaborn as sns 
from sklearn.model_selection import train_test_split 
from sklearn.ensemble import RandomForestClassifier 
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix 
from sklearn.preprocessing import StandardScaler 
# Load the dataset 
df = pd.read_csv('bank_loans.csv') 
# Display the first few rows to understand the structure (optional) 
print(df.head()) 
print(df.info()) 
# Check for missing values (optional) 
print("Missing values:\n", df.isnull().sum()) 
# Handle missing values if any (optional, assuming numerical columns filled with mean) 
df.fillna(df.mean(), inplace=True) 
# Encode categorical variables (assuming 'Gender', 'Married', etc. as example categorical features) 
df = pd.get_dummies(df, drop_first=True) 
# Separate features and target variable 
X = df.drop(columns=['Loan_Status'])  # Assuming 'Loan_Status' is the target column (1 = Approved, 0 = Not Approved) 
y = df['Loan_Status'] 
# Split the data into training and testing sets 
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) 
# Standardize the features 
scaler = StandardScaler() 
X_train_scaled = scaler.fit_transform(X_train) 
X_test_scaled = scaler.transform(X_test) 
# Initialize and train the Random Forest Classifier 
rf_model = RandomForestClassifier(n_estimators=100, random_state=42) 
rf_model.fit(X_train_scaled, y_train) 
# Predict on the test set 
y_pred = rf_model.predict(X_test_scaled) 
# Calculate accuracy and other performance metrics 
accuracy = accuracy_score(y_test, y_pred) 
print("Random Forest Model Accuracy:", accuracy) 
print("\nClassification Report:\n", classification_report(y_test, y_pred)) 
# Plot confusion matrix for better insight into model performance 
conf_matrix = confusion_matrix(y_test, y_pred) 
plt.figure(figsize=(6, 4)) 
sns.heatmap(conf_matrix, annot=True, fmt="d", cmap="Blues", xticklabels=['Not Approved', 'Approved'], 
yticklabels=['Not Approved', 'Approved']) 
plt.xlabel("Predicted") 
plt.ylabel("Actual") 
plt.title("Confusion Matrix") 
plt.show() 
# Feature importance visualization 
feature_importances = rf_model.feature_importances_ 
features = X.columns 
# Create a dataframe for feature importances 
feature_df = pd.DataFrame({'Feature': features, 'Importance': feature_importances}) 
feature_df = feature_df.sort_values(by='Importance', ascending=False) 
# Plot feature importances 
plt.figure(figsize=(10, 6)) 
sns.barplot(x='Importance', y='Feature', data=feature_df, palette="viridis") 
plt.title("Feature Importances in Random Forest Model") 
plt.xlabel("Importance") 
plt.ylabel("Feature") 
plt.show()
import pandas as pd 
from sklearn.model_selection import train_test_split 
from sklearn.preprocessing import StandardScaler 
from sklearn.neighbors import KNeighborsClassifier 
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, classification_report 
# Load the dataset 
df = pd.read_csv('diabetes.csv') 
# Display the first few rows to understand the dataset structure (optional) 
print(df.head()) 
# Separate features and target 
X = df.drop(columns=['Outcome'])  # Assuming 'Outcome' is the target column (0 = No Diabetes, 1 = Diabetes) 
y = df['Outcome'] 
# Split the data into training and testing sets 
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) 
# Standardize the features 
scaler = StandardScaler() 
X_train_scaled = scaler.fit_transform(X_train) 
X_test_scaled = scaler.transform(X_test) 
# Initialize and train the k-NN classifier 
k = 5  # You can tune this value 
knn = KNeighborsClassifier(n_neighbors=k) 
knn.fit(X_train_scaled, y_train) 
# Predict on the test set 
y_pred = knn.predict(X_test_scaled) 
# Calculate performance measures 
accuracy = accuracy_score(y_test, y_pred) 
precision = precision_score(y_test, y_pred) 
recall = recall_score(y_test, y_pred) 
f1 = f1_score(y_test, y_pred) 
# Display the performance measures 
print("Performance Measures for k-NN Classifier:") 
print(f"Accuracy: {accuracy:.4f}") 
print(f"Precision: {precision:.4f}") 
print(f"Recall: {recall:.4f}") 
print(f"F1-Score: {f1:.4f}") 
# Detailed classification report 
print("\nClassification Report:\n", classification_report(y_test, y_pred)) 
import pandas as pd 
# Load the dataset 
df = pd.read_csv('Iris.csv') 
# Display the first few rows and basic information 
print(df.head()) 
print(df.describe()) 
print(df.info()) 
from sklearn.model_selection import train_test_split 
from sklearn.preprocessing import LabelEncoder 
# Encode the target variable 
label_encoder = LabelEncoder() 
df['Species'] = label_encoder.fit_transform(df['Species']) 
# Separate features and target variable 
X = df.drop(columns=['Species']) 
y = df['Species'] 
# Split the data into training and testing sets 
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) 
from sklearn.tree import DecisionTreeClassifier 
from sklearn.metrics import accuracy_score 
# Initialize the Decision Tree Classifier 
model = DecisionTreeClassifier(random_state=42) 
model.fit(X_train, y_train) 
# Predict on the test set 
y_pred = model.predict(X_test) 
# Estimate the accuracy of the model 
accuracy = accuracy_score(y_test, y_pred) 
print("Accuracy of Decision Tree Classifier:", accuracy) 
from sklearn.tree import plot_tree 
import matplotlib.pyplot as plt 
# Plot the decision tree 
plt.figure(figsize=(12, 8)) 
plot_tree(model, feature_names=X.columns, class_names=label_encoder.classes_, filled=True) 
plt.title("Decision Tree Structure") 
plt.show() 
importances = model.feature_importances_ 
feature_names = X.columns 
# Plot feature importances 
plt.figure(figsize=(8, 6)) 
plt.barh(feature_names, importances, color='skyblue') 
plt.xlabel("Feature Importance") 
plt.ylabel("Feature") 
plt.title("Feature Importances in Decision Tree Model") 
plt.show() 
import numpy as np 
from matplotlib.colors import ListedColormap 
# Define a function to plot decision boundaries 
def plot_decision_boundary(model, X, y): 
# Set up the grid for plotting decision boundaries 
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), 
np.arange(y_min, y_max, 0.02)) 
# Predict over the grid 
Z = model.predict(np.c_[xx.ravel(), yy.ravel()]) 
Z = Z.reshape(xx.shape) 
# Plot the contour and training examples 
plt.figure(figsize=(10, 6)) 
plt.contourf(xx, yy, Z, alpha=0.3, cmap=ListedColormap(('red', 'green', 'blue'))) 
scatter = plt.scatter(X[:, 0], X[:, 1], c=y, s=30, cmap=ListedColormap(('red', 'green', 'blue'))) 
plt.xlabel("Petal Length") 
plt.ylabel("Petal Width") 
plt.title("Decision Boundary (Petal Length vs Petal Width)") 
plt.legend(handles=scatter.legend_elements()[0], labels=label_encoder.classes_) 
plt.show() 
# Extract PetalLength and PetalWidth for visualization 
X_2d_train = X_train[['PetalLengthCm', 'PetalWidthCm']].values 
y_train_2d = y_train.values 
# Train a new model on these two features for simplicity 
model_2d = DecisionTreeClassifier(random_state=42) 
model_2d.fit(X_2d_train, y_train_2d) 
# Plot the decision boundary 
plot_decision_boundary(model_2d, X_2d_train, y_train_2d)
import pandas as pd 
# Load the dataset 
df = pd.read_csv('student_scores.csv') 
# Display the first few rows and basic information 
print(df.head()) 
print(df.describe()) 
print(df.info()) 
from sklearn.model_selection import train_test_split 
# Separate features and target 
X = df.drop(columns=['Score'])  # Assuming 'Score' is the target column 
y = df['Score'] 
# Split into training and testing sets 
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) 
from sklearn.preprocessing import StandardScaler 
# Initialize and fit the scaler on training data 
scaler = StandardScaler() 
X_train_scaled = scaler.fit_transform(X_train) 
X_test_scaled = scaler.transform(X_test) 
from sklearn.linear_model import LinearRegression 
from sklearn.metrics import mean_absolute_error, mean_squared_error 
import numpy as np 
# Initialize and train the model 
model = LinearRegression() 
model.fit(X_train_scaled, y_train) 
# Predict on the test set 
y_pred = model.predict(X_test_scaled) 
# Evaluate performance 
mae = mean_absolute_error(y_test, y_pred) 
rmse = np.sqrt(mean_squared_error(y_test, y_pred)) 
print("Without Dimensionality Reduction") 
print("Mean Absolute Error (MAE):", mae) 
print("Root Mean Squared Error (RMSE):", rmse) 
from sklearn.decomposition import PCA 
# Initialize PCA and fit on the scaled training data 
pca = PCA(n_components=0.95)  # Retain 95% variance 
X_train_pca = pca.fit_transform(X_train_scaled) 
X_test_pca = pca.transform(X_test_scaled) 
# Check the number of components 
print("Number of components selected:", pca.n_components_) 
# Train the regression model on PCA-reduced data 
model_pca = LinearRegression() 
model_pca.fit(X_train_pca, y_train) 
# Predict on the PCA-transformed test set 
y_pred_pca = model_pca.predict(X_test_pca) 
# Evaluate performance 
mae_pca = mean_absolute_error(y_test, y_pred_pca) 
rmse_pca = np.sqrt(mean_squared_error(y_test, y_pred_pca)) 
print("With Dimensionality Reduction (PCA)") 
print("Mean Absolute Error (MAE):", mae_pca) 
print("Root Mean Squared Error (RMSE):", rmse_pca) 
print("Comparison of Model Performance:") 
print("Without Dimensionality Reduction - MAE:", mae, ", RMSE:", rmse) 
print("With Dimensionality Reduction (PCA) - MAE:", mae_pca, ", RMSE:", rmse_pca)
import pandas as pd 
# Load the dataset 
df = pd.read_csv('Pune_rent.csv') 
# Display the first few rows and basic information 
print(df.head()) 
print(df.describe()) 
print(df.info()) 
# Check for missing values 
print(df.isnull().sum()) 
# Convert categorical variables to dummy/indicator variables if necessary 
# For demonstration, assuming 'location', 'house_type' are categorical variables 
df = pd.get_dummies(df, columns=['location', 'house_type'], drop_first=True) 
from sklearn.model_selection import train_test_split 
# Separate features and target 
X = df.drop(columns=['Rent']) 
y = df['Rent'] 
# Split into training and testing sets 
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) 
from sklearn.preprocessing import StandardScaler 
# Standardize the features 
scaler = StandardScaler() 
X_train_scaled = scaler.fit_transform(X_train) 
X_test_scaled = scaler.transform(X_test) 
from sklearn.linear_model import LinearRegression 
# Initialize and train the model 
model = LinearRegression() 
model.fit(X_train_scaled, y_train) 
# Predict on the test set 
y_pred = model.predict(X_test_scaled) 
from sklearn.metrics import mean_absolute_error, mean_squared_error 
import numpy as np 
# Calculate MAE and RMSE 
mae = mean_absolute_error(y_test, y_pred) 
rmse = np.sqrt(mean_squared_error(y_test, y_pred)) 
print("Mean Absolute Error (MAE):", mae) 
print("Root Mean Squared Error (RMSE):", rmse)
import pandas as pd 
# Load the dataset 
df = pd.read_csv('Fish.csv') 
# Display the first few rows and basic information 
print(df.head()) 
print(df.describe()) 
print(df.info()) 
from sklearn.model_selection import train_test_split 
from sklearn.preprocessing import LabelEncoder 
# Encode the target variable if it's categorical 
label_encoder = LabelEncoder() 
df['Species'] = label_encoder.fit_transform(df['Species']) 
# Separate the features and target variable 
X = df.drop(columns=['Species']) 
y = df['Species'] 
# Split into training and testing sets 
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) 
from sklearn.preprocessing import StandardScaler 
# Standardize the features 
scaler = StandardScaler() 
X_train_scaled = scaler.fit_transform(X_train) 
X_test_scaled = scaler.transform(X_test) 
from sklearn.svm import SVC 
from sklearn.feature_selection import RFE 
# Initialize the classifier and RFE 
svc = SVC(kernel="linear", random_state=42) 
rfe = RFE(estimator=svc, n_features_to_select=3)  # Choose 3 features for demonstrate on 
# Fit RFE 
rfe.fit(X_train_scaled, y_train) 
# Print the ranking of features 
print("Feature ranking (1 indicates selected features):", rfe.ranking_) 
print("Selected features:", X.columns[rfe.support_]) 
from sklearn.metrics import accuracy_score, classification_report 
# Select the features indicated by RFE 
X_train_rfe = X_train_scaled[:, rfe.support_] 
X_test_rfe = X_test_scaled[:, rfe.support_] 
# Train the classifier on the selected features 
svc.fit(X_train_rfe, y_train) 
# Make predictions and evaluate performance 
y_pred = svc.predict(X_test_rfe) 
print("Accuracy:", accuracy_score(y_test, y_pred)) 
print("Classification Report:\n", classification_report(y_test, y_pred)) 
import pandas as pd 
# Load the dataset 
df = pd.read_csv('petrol_consumption.csv') 
# Display basic information about the dataset 
print(df.head()) 
print(df.describe()) 
print(df.info()) 
from sklearn.preprocessing import StandardScaler 
# Separate the features and target variable if there's one 
X = df.drop(columns=['Petrol_Consumption'])  # Assuming 'Petrol_Consumption' is the target variable 
y = df['Petrol_Consumption'] 
# Standardize the features 
scaler = StandardScaler() 
X_scaled = scaler.fit_transform(X) 
from sklearn.decomposition import PCA 
# Apply PCA 
pca = PCA(n_components=2) 
X_pca = pca.fit_transform(X_scaled) 
# Check the explained variance 
print("Explained variance by each component:", pca.explained_variance_ratio_) 
print("Cumulative explained variance:", pca.explained_variance_ratio_.cumsum())
Task-6
Implement OBST using dynamic programming
Algorithm:
Algorithm OBST(p, q, n)
// Given n distinct identifiers a1 < a2 < ··· < an and probabilities
// p[i], 1 ≤ i ≤ n, and q[i], 0 ≤ i ≤ n, this algorithm computes
// the cost c[i, j] of optimal binary search tree for identifiers
// a_i, ..., a_j. It also computes r[i, j], the root of t[i, j].
// w[i, j] is the weight of t[i, j].
{
  for i := 0 to n do
  { 
    // Initialize.
    w[i, i] := q[i]; r[i, i] := 0; c[i, i] := 0.0;
    // Optimal trees with one node
    w[i, i + 1] := q[i] + q[i + 1] + p[i + 1];
    c[i, i + 1] := w[i, i + 1]; r[i, i + 1] := i + 1;
  }
  
  for m := 2 to n do // Find optimal trees with m nodes.
    for i := 0 to n - m do
    {
      j := i + m;
      w[i, j] := w[i, j - 1] + p[j] + q[j];
      c[i, j] := ∞; // Solve 5.12 using Knuth's result.
      k := Find(c, r, i, j);
      // A value of k in the range [r[i, j - 1], r[i + 1, j]] that minimizes c[i, k - 1] + c[k, j];
      c[i, j] := w[i, j] + c[i, k - 1] + c[k, j];
      r[i, j] := k;
    }
  write (c[0, n], w[0, n], r[0, n]);
}

Algorithm Find(c, r, i, j)
{
  min := ∞;
  for m := r[i, j - 1] to r[i + 1, j] do
    if (c[i, m - 1] + c[m, j] < min) then
    {
      min := c[i, m - 1] + c[m, j];
      l_i := m;
    }
  return l_i;
}

Program:
#include <stdio.h>
#define MAX 10
#define INF 300000

void main() {
    char ele[MAX][MAX];
    int w[MAX][MAX], c[MAX][MAX], r[MAX][MAX];
    int p[MAX], q[MAX];
    int temp, min, min1;
    int i, j, k, b, n;

    // Input number of elements
    printf("Enter the number of elements: ");
    scanf("%d", &n);

    // Input probabilities for elements p[i]
    for (i = 1; i <= n; i++) {
        printf("Enter the element P(%d): ", i);
        scanf("%d", &p[i]);
    }
    printf("\n");

    // Input probabilities for dummy keys q[i]
    for (i = 0; i <= n; i++) {
        printf("Enter the element q(%d): ", i);
        scanf("%d", &q[i]);
    }
    printf("\n");

    printf("W \t\t C \t\t R\n");

    // Initialization of w, c, and r matrices for single elements
    for (i = 0; i <= n; i++) {
        for (j = 0; j <= n; j++) {
            if (i == j) {
                w[i][i] = q[i];
                c[i][i] = 0;
                r[i][i] = 0;
                printf("w[%d][%d] : %d \t c[%d][%d]: %d \t r[%d][%d] : %d\n", i, j, w[i][j], i, j, c[i][j], i, j, r[i][j]);
            }
        }
    }
    printf("\n");

    // Fill w, c, and r matrices for ranges [i, j]
    for (b = 0; b < n; b++) {
        for (i = 0, j = b + 1; j <= n; i++, j++) {
            if (i != j && i < j) {
                // Calculate w[i][j]
                w[i][j] = w[i][j - 1] + p[j] + q[j];
                min = INF;

                // Find minimum cost and root for this subproblem
                for (k = i + 1; k <= j; k++) {
                    min1 = c[i][k - 1] + c[k][j] + w[i][j];
                    if (min > min1) {
                        min = min1;
                        temp = k;
                    }
                }

                // Store minimum cost and root for this range
                c[i][j] = min;
                r[i][j] = temp;
            }
            // Print w[i][j], c[i][j], and r[i][j]
            printf("w[%d][%d] : %d \t c[%d][%d]: %d \t r[%d][%d] : %d\n", i, j, w[i][j], i, j, c[i][j], i, j, r[i][j]);
        }
        printf("\n");
    }

    // Print minimum cost for the entire tree
    printf("Minimum cost: %d\n", c[0][n]);
}
Output:
/tmp/VsdNZE6fYV.o
Enter the number of elements: 4
Enter the element P(1): 3
Enter the element P(2): 3
Enter the element P(3): 1
Enter the element P(4): 1

Enter the element q(0): 2
Enter the element q(1): 3
Enter the element q(2): 1
Enter the element q(3): 1
Enter the element q(4): 1

W 		 C 		 R
w[0][0] : 2 	 c[0][0]: 0 	 r[0][0] : 0
w[1][1] : 3 	 c[1][1]: 0 	 r[1][1] : 0
w[2][2] : 1 	 c[2][2]: 0 	 r[2][2] : 0
w[3][3] : 1 	 c[3][3]: 0 	 r[3][3] : 0
w[4][4] : 1 	 c[4][4]: 0 	 r[4][4] : 0

w[0][1] : 8 	 c[0][1]: 8 	 r[0][1] : 1
w[1][2] : 7 	 c[1][2]: 7 	 r[1][2] : 2
w[2][3] : 3 	 c[2][3]: 3 	 r[2][3] : 3
w[3][4] : 3 	 c[3][4]: 3 	 r[3][4] : 4

w[0][2] : 12 	 c[0][2]: 19 	 r[0][2] : 1
w[1][3] : 9 	 c[1][3]: 12 	 r[1][3] : 2
w[2][4] : 5 	 c[2][4]: 8 	 r[2][4] : 3

w[0][3] : 14 	 c[0][3]: 25 	 r[0][3] : 2
w[1][4] : 11 	 c[1][4]: 19 	 r[1][4] : 2

w[0][4] : 16 	 c[0][4]: 32 	 r[0][4] : 2

Minimum cost: 32


=== Code Exited With Errors ===
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>External Style Example</title>
    <!-- Link to the external CSS file -->
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <h1 class="heading">Welcome to External CSS Styling</h1>
        <p class="text">This is an example using external styling. All CSS rules are in a separate file.</p>
        <p class="text highlight">This paragraph uses both the `text` and `highlight` classes.</p>
    </div>
</body>
</html>
------
CSS (styles.css):
/* External CSS file: styles.css */

body {
    font-family: Arial, sans-serif;
    background-color: #f0f0f0;
    margin: 0;
    padding: 0;
}

.container {
    padding: 40px;
    background-color: #ffffff;
    border: 1px solid #ddd;
    max-width: 800px;
    margin: 20px auto;
}

.heading {
    color: #333;
    text-align: center;
    padding: 20px;
}

.text {
    color: #666;
    font-size: 18px;
    line-height: 1.6;
    margin: 20px;
}

.highlight {
    color: #0056b3;
    font-weight: bold;
}

Task-5
Implement Dijkstra's algorithm to compute the shortest path through a graph.
Algorithm:
Algorithm ShortestPaths(v, cost, dist, n)
// dist[j], 1 ≤ j ≤ n, is set to the length of the shortest
// path from vertex v to vertex j in a digraph G with n
// vertices. dist[v] is set to zero. G is represented by its
// cost adjacency matrix cost[1 : n, 1 : n].
{
  for i := 1 to n do
  { // Initialize S.
    S[i] := false; dist[i] := cost[v, i];
  }
  S[v] := true; dist[v] := 0.0; // Put v in S.
  for num := 2 to n − 1 do
  {
    // Determine n − 1 paths from v.
    Choose u from among those vertices not
    in S such that dist[u] is minimum;
    S[u] := true; // Put u in S.
    for (each w adjacent to u with S[w] = false) do
    // Update distances.
    if (dist[w] > dist[u] + cost[u, w]) then
      dist[w] := dist[u] + cost[u, w];
  }
}
Program:
#include <stdio.h> 
#include <limits.h>
#define M 8

int n;

void spath(int graph[n][n], int u) {
    int dist[M];
    int s[M] = {0};
    for (int i = 0; i < n; i++) {
        dist[i] = INT_MAX;
    }
    dist[u] = 0;
    for (int i = 0; i < n - 1; i++) {
        int v;
        int min = INT_MAX;
        for (int j = 0; j < n; j++) {
            if (dist[j] < min && s[j] == 0) {
                min = dist[j];
                v = j;
            }
        }
        s[v] = 1;
        for (int j = 0; j < n; j++) {
            if (graph[v][j] != 0 && s[j] == 0) {
                if (dist[j] > dist[v] + graph[v][j]) {
                    dist[j] = dist[v] + graph[v][j];
                }
            }
        }
    }
    for (int i = 0; i < n; i++) {
        printf("%d ", dist[i]);
    }
    printf("\n");
}

int main() {
    printf("Enter the number of vertices (up to %d): ", M);
    scanf("%d", &n);

    int graph[M][M];
    printf("Enter the adjacency matrix (use 0 for no direct path):\n");
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            scanf("%d", &graph[i][j]);
        }
    }

    int startNode;
    printf("Enter the starting node (0 to %d): ", n - 1);
    scanf("%d", &startNode);

    spath(graph, startNode);
    return 0;
}
Output:
/tmp/q6mNdkXwgB.o
Enter the number of vertices (up to 8): 8
Enter the adjacency matrix (use 0 for no direct path):
0 0 0 0 0 0 0 0
300 0 0 0 0 0 0 0
1000 800 0 0 0 0 0 0
0 0 1200 0 0 0 0 0
0 0 0 1500 0 250 0 0
0 0 0 1000 0 0 900 1400
0 0 0 0 0 0 0 1000
1700 0 0 0 0 0 0 0
Enter the starting node (0 to 7): 4
3350 3250 2450 1250 0 250 1150 1650 


=== Code Execution Successful ===
Task-4
Implement Fractional Knapsack Algorithm
Algorithm:
Algorithm Sort(p, w, n){
  int r[n], index[n];
  int p[n], w[n];
  
  for i := 1 to n
    r[i] := p[i] / w[i];
  
  for i := n to n do{
    j := i;
    for k := i + 1 to n do
      if (r[k] <= r[j]) then 
	j := k;
    if(j!-i){
     index[i] := j;
     t := r[i];
     r[i] := r[j];
     r[j] := t;
    }
  }
  
  for i := 1 to n
  {
    p[i] := p[index[i]];
    w[i] := w[index[i]];
  }
}
Program:
#include <stdio.h>

void knapsack(int n, float weight[], float profit[], float capacity) {
    float tp = 0;
    int i, u;
    u = capacity;
    for (i = 0; i < n; i++) {
        if (weight[i] > u)
            break;
        else {
            tp = tp + profit[i];
            u = u - weight[i];
        }
    }
    if (i < n)
        tp = tp + (u / weight[i] * profit[i]);
    printf("\nMaximum profit is:- %f", tp);
}

int main() {
    float weight[20], profit[20], capacity;
    int num, i, j;
    float ratio[20], temp;

    printf("\nEnter the no. of objects:- ");
    scanf("%d", &num);

    printf("\nEnter the wts and profits of each object:-\n");
    for (i = 0; i < num; i++) {
        scanf("%f %f", &weight[i], &profit[i]);
    }

    printf("\nEnter the capacity of knapsack:- ");
    scanf("%f", &capacity);

    // Calculate profit/weight ratio
    for (i = 0; i < num; i++) {
        ratio[i] = profit[i] / weight[i];
    }

    // Sort items by profit/weight ratio in descending order
    for (i = 0; i < num; i++) {
        for (j = i + 1; j < num; j++) {
            if (ratio[i] < ratio[j]) {
                // Swap ratios
                temp = ratio[j];
                ratio[j] = ratio[i];
                ratio[i] = temp;

                // Swap weights and profits to keep arrays aligned
                temp = weight[j];
                weight[j] = weight[i];
                weight[i] = temp;

                temp = profit[j];
                profit[j] = profit[i];
                profit[i] = temp;
            }
        }
    }

    knapsack(num, weight, profit, capacity);
    return 0;
}
Output:
Enter the no. of objects:- 5
Enter the wts and profits of each object:-
4 12
1 2
2 2
1 1
4 10
Enter the capacity of knapsack:- 15
Maximum profit is:- 17.333334

=== Code Execution Successful ===
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Internal Style Example</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            margin: 0;
            padding: 0;
        }
        
        #main-content {
            padding: 40px;
            background-color: #ffffff;
            border: 1px solid #ddd;
            max-width: 800px;
            margin: 20px auto;
        }
        
        h1 {
            color: #333;
            text-align: center;
            padding: 20px;
        }
        
        p {
            color: #666;
            font-size: 18px;
            line-height: 1.6;
            margin: 20px;
        }
        
        p.highlight {
            color: #0056b3;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div id="main-content">
        <h1>Welcome to Internal CSS Styling</h1>
        <p>This is an example of internal styling. All CSS rules are within a style block in the head section.</p>
        <p class="highlight">This paragraph has specific styling defined in the internal CSS.</p>
    </div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Inline Style Example</title>
</head>
<body style="font-family: Arial, sans-serif; background-color: #f0f0f0; margin: 0; padding: 0;">
    <div style="padding: 40px; background-color: #ffffff; border: 1px solid #ddd; max-width: 800px; margin: 20px auto;">
        <h1 style="color: #333; text-align: center; padding: 20px;">Welcome to Inline CSS Styling</h1>
        <p style="color: #666; font-size: 18px; line-height: 1.6; margin: 20px;">
            This is an example of inline styling. All CSS rules are directly within the HTML elements.
        </p>
        <p style="color: #0056b3; font-weight: bold; margin: 20px;">
            This paragraph uses inline styling for specific text color and font weight.
        </p>
    </div>
</body>
</html>
Task-2
Write a program to identify the articulation points present in a graph.
Algorithm:
Algorithm Art(u, v)
// u is a start vertex for depth first search. v is its parent if any
// in the depth first spanning tree. It is assumed that the global
// array dfn is initialized to zero and that the global variable
// num is initialized to 1. n is the number of vertices in G.
{
    dfn[u] := num; L[u] := num; num := num + 1;
    for each vertex w adjacent from u do`
    {
        if (dfn[w] = 0) then
        {
            Art(w, u);     // w is unvisited.
            L[u] := min(L[u], L[w]);
        }
        else if (w ≠ v) then L[u] := min(L[u], dfn[w]);
    }
}
Program:
#include <stdio.h>

int dfn[10], a[10][10], l[10], n, num = 1, children[10];
int artp[10]; // Array to store articulation points

// Function to find the minimum of two values
int min(int a, int b) {
    return (a > b ? b : a);
}

// Depth-first search to find articulation points
void art(int u, int v) {
    dfn[u] = num;
    l[u] = num;
    num++;
    children[u] = 0;

    for (int i = 1; i <= n; i++) {
        if (a[u][i] == 1) { // Check if there is an edge from u to i
            int w = i;
            if (dfn[w] == 0) { // w is unvisited
                children[u]++;
                art(w, u);

                // Update the low value of u for parent function calls
                l[u] = min(l[u], l[w]);

                // Check articulation point conditions
                if (v != -1 && l[w] >= dfn[u]) {
                    artp[u] = 1; // Mark u as an articulation point
                }
            } else if (w != v) { // Update low value of u for back edges
                l[u] = min(l[u], dfn[w]);
            }
        }
    }
}

// Main function
int main() {
    printf("Enter no. of vertices: ");
    scanf("%d", &n);

    int s;
    printf("Enter root vertex: ");
    scanf("%d", &s);

    printf("Enter adjacency matrix:\n");
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            scanf("%d", &a[i][j]);
        }
    }

    // Initialize arrays
    for (int i = 0; i <= n; i++) {
        dfn[i] = 0;
        l[i] = 0;
        children[i] = 0;
        artp[i] = 0;
    }

    printf("Articulation points are:\n");
    
    // Run DFS from the root vertex
    art(s, -1);

    // Check if the root is an articulation point (special case)
    if (children[s] > 1) {
        printf("%d\n", s);
    }

    // Print other articulation points
    for (int i = 1; i <= n; i++) {
        if (artp[i]) {
            printf("%d\n", i);
        }
    }

    return 0;
}
Output:
/tmp/96iN6R0Irx.o
Enter no. of vertices: 6
Enter root vertex: 1
Enter adjacency matrix:
0 1 0 1 0 0
1 0 1 0 0 0
0 1 0 1 1 1
1 0 1 0 0 0
0 0 1 0 0 0
0 0 1 0 0 0
Articulation points are:
3


=== Code Execution Successful ===
Task-1
a) Implement Merge sort algorithm and plot its time complexity with reference to the size of the input.
Algorithm:
Algorithm MergeSort(low, high)
// a[low : high] is a global array to be sorted.
// Small(P) is true if there is only one element
// to sort. In this case the list is already sorted.
{
    if (low < high) then     // If there are more than one element
    {
        // Divide P into subproblems.
        // Find where to split the set.
        mid := ⌊(low + high) / 2⌋;
        // Solve the subproblems.
        MergeSort(low, mid);
        MergeSort(mid + 1, high);
        // Combine the solutions.
        Merge(low, mid, high);
    }
}
Algorithm Merge(low, mid, high)
// a[low : high] is a global array containing two sorted
// subsets in a[low : mid] and in a[mid + 1 : high]. The goal
// is to merge these two sets into a single set residing
// in a[low : high]. b[ ] is an auxiliary global array.
{
  h := low; i := low; j := mid + 1;
  while ((h ≤ mid) and (j ≤ high)) do
  {
    if (a[h] ≤ a[j]) then
    {
      b[i] := a[h]; h := h + 1;
    }
    else
    {
      b[i] := a[j]; j := j + 1;
    }
    i := i + 1;
  }
  if (h > mid) then
    for k := j to high do
    {
      b[i] := a[k]; i := i + 1;
    }
  else
    for k := h to mid do
    {
      b[i] := a[k]; i := i + 1;
    }
  for k := low to high do a[k] := b[k];
}

Program:
#include <stdio.h>
#include <time.h>
void merge(int a[],int i1,int j1,int i2,int j2) {
	int i,j,k=0;
	i=i1;
	j=i2;
	int temp[100];
	while(i<=j1 && j<=j2) {
		if(a[i]<a[j])
			temp[k++]=a[i++];
		else
			temp[k++]=a[j++];
	}
	while(i<=j1)
		temp[k++]=a[i++];
	while(j<=j2)
		temp[k++]=a[j++];
	for(i=i1,j=0; i<=j2; i++,j++)
		a[i]=temp[j];
}
void partition(int a[],int l,int h) {
	if(l<h) {
		int mid=(l+h)/2;
		partition(a,l,mid);
		partition(a,mid+1,h);
		merge(a,l,mid,mid+1,h);
	}
}
int main() {
	int n;
	printf("enter the size of array: ");
	scanf("%d",&n);
	int a[n];
	for(int i=0; i<n; i++)
		a[i] = n - i;
	clock_t t = clock();
	partition(a,0,n-1);
	t = clock() - t;
	printf("Time taken: %f \n",((float)t*1000)/CLOCKS_PER_SEC);
	for(int i=0; i<n; i++)
		printf("%d ",a[i]);
	return 0;
}
Output:
enter the size of array: 5
Time taken: 0.002000 
1 2 3 4 5 

=== Code Execution Successful ===
b) Implement Quick sort algorithm and plot its time complexity regarding asymptotic notations (Best, average, and worst).
Algorithm:
Algorithm QuickSort(p, q)
// Sorts the elements a[p], ..., a[q] which reside in the global
// array a[1 : n] into ascending order; a[n + 1] is considered to
// be defined and must be ≥ all the elements in a[1 : n].
{
    if (p < q) then     // If there are more than one element
    {
        // divide P into two subproblems.
        j := Partition(a, p, q + 1);
        // j is the position of the partitioning element.
        // Solve the subproblems.
        QuickSort(p, j - 1);
        QuickSort(j + 1, q);
        // There is no need for combining solutions.
    }
}
Algorithm Partition(a, m, p)
// Within a[m], a[m + 1], ..., a[p − 1] the elements are
// rearranged in such a manner that if initially t = a[m],
// then after completion a[q] = t for some q between m
// and p − 1, a[k] ≤ t for m ≤ k < q, and a[k] ≥ t
// for q < k < p. q is returned. Set a[p] = ∞.
{
  v := a[m]; i := m; j := p;
  repeat
  {
    repeat
      i := i + 1;
    until (a[i] ≥ v);
    
    repeat
      j := j − 1;
    until (a[j] ≤ v);
    
    if (i < j) then Interchange(a, i, j);
  } until (i ≥ j);
  
  a[m] := a[j]; a[j] := v; return j;
}

Algorithm Interchange(a, i, j)
// Exchange a[i] with a[j].
{
  p := a[i];
  a[i] := a[j]; a[j] := p;
}

Program:
#include <stdio.h>
#include <time.h>

void quicksort(int number[25], int first, int last) {
    int i, j, pivot, temp;
    if (first < last) {
        pivot = first;
        i = first;
        j = last;
        while (i < j) {
            while (number[i] <= number[pivot] && i < last)
                i++;
            while (number[j] > number[pivot])
                j--;
            if (i < j) {
                temp = number[i];
                number[i] = number[j];
                number[j] = temp;
            }
        }
        temp = number[pivot];
        number[pivot] = number[j];
        number[j] = temp;
        quicksort(number, first, j - 1);
        quicksort(number, j + 1, last);
    }
}

int main() {
    int i, count, number[25];
    printf("SIZE OF ARRAY?: ");
    scanf("%d", &count);

    printf("Enter array elements: ");
    for (i = 0; i < count; i++) {
        scanf("%d", &number[i]);
    }

    clock_t t = clock(); // Start time
    quicksort(number, 0, count - 1);
    t = clock() - t; // End time

    printf("Time taken: %f ms\n", ((float)t * 1000) / CLOCKS_PER_SEC);
    printf("Sorted elements:");
    for (i = 0; i < count; i++) {
        printf(" %d", number[i]);
    }
    printf("\n");

    return 0;
}
Output:

SIZE OF ARRAY?: 5
Enter array elements: 5 4 3 2 1
Time taken: 0.002000 ms
Sorted elements: 1 2 3 4 5


=== Code Execution Successful ===
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vertical Navigation Bar</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="sidebar">
        <a href="#home" class="active">Home</a>
        <a href="#news">News</a>
        <a href="#contact">Contact</a>
        <a href="#about">About</a>
    </div>

    <div class="content">
        <h1>Welcome to My Website</h1>
        <p>This is a simple vertical navigation bar example.</p>
    </div>
</body>
</html>

* {
    box-sizing: border-box;
}

body {
    font-family: Arial, sans-serif;
}

.sidebar {
    height: 100%; /* Full-height */
    width: 200px; /* Set the width of the sidebar */
    position: fixed; /* Fixed Sidebar (stay in place) */
    background-color: #333; /* Sidebar color */
}

.sidebar a {
    padding: 15px; /* Padding */
    text-decoration: none; /* No underline */
    font-size: 17px; /* Font size */
    color: #f2f2f2; /* Text color */
    display: block; /* Make links appear below each other */
}

.sidebar a:hover {
    background-color: #ddd; /* Add a hover effect */
    color: black; /* Text color on hover */
}

.sidebar a.active {
    background-color: #04AA6D; /* Active link color */
    color: white; /* Active link text color */
}

.content {
    margin-left: 220px; /* Margin to the left of the sidebar */
    padding: 20px; /* Padding for content */
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Horizontal Navigation Bar</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <nav class="navbar">
        <a href="#home" class="active">Home</a>
        <a href="#news">News</a>
        <a href="#contact">Contact</a>
        <a href="#about">About</a>
    </nav>
</body>
</html>

* {
    box-sizing: border-box;
}

body {
    font-family: Arial, sans-serif;
}

.navbar {
    background-color: #333;
    overflow: hidden;
}

.navbar a {
    float: left;
    color: #f2f2f2;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    font-size: 17px;
}

.navbar a:hover {
    background-color: #ddd;
    color: black;
}

.navbar a.active {
    background-color: #04AA6D;
    color: white;
}
//grid.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Grid Layout Example</title>
    <link rel="stylesheet" href="gridstyles.css">
</head>
<body>
    <div class="grid-container">
        <div class="grid-item">1</div>
        <div class="grid-item">2</div>
        <div class="grid-item">3</div>
        <div class="grid-item">4</div>
        <div class="grid-item">5</div>
        <div class="grid-item">6</div>
    </div>
</body>
</html>
//gridstyles.css
* {
    box-sizing: border-box;
}

body {
    font-family: Arial, sans-serif;
}

.grid-container {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 10px; /* Space between grid items */
    padding: 20px;
}

.grid-item {
    background-color: #2196F3;
    color: white;
    padding: 20px;
    text-align: center;
}
//flex.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flexbox Layout Example</title>
    <link rel="stylesheet" href="flexstyles.css">
</head>
<body>
    <div class="flex-container">
        <div class="flex-item">Item 1</div>
        <div class="flex-item">Item 2</div>
        <div class="flex-item">Item 3</div>
        <div class="flex-item">Item 4</div>
        <div class="flex-item">Item 5</div>
    </div>
</body>
</html>
//flexstyles.css
* {
    box-sizing: border-box;
}

body {
    font-family: Arial, sans-serif;
}

.flex-container {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: center;
    background-color: #f4f4f4;
    padding: 20px;
}

.flex-item {
    background-color: #009688;
    color: white;
    padding: 20px;
    margin: 10px;
    flex: 1 1 30%; /* Grow, shrink, and set base width */
    text-align: center;
}
//First, create a database named user_db and a table named users
sql:
CREATE DATABASE user_db;

USE user_db;

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    password VARCHAR(50) NOT NULL
);
//index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>User Registration</title>
</head>
<body>
    <h2>User Registration</h2>
    <form action="InsertUserServlet" method="post">
        Username: <input type="text" name="username" required><br><br>
        Password: <input type="password" name="password" required><br><br>
        <input type="submit" value="Register">
    </form>

    <h2>Update Password</h2>
    <form action="UpdateUserServlet" method="post">
        Username: <input type="text" name="username" required><br><br>
        New Password: <input type="password" name="newPassword" required><br><br>
        <input type="submit" value="Update Password">
    </form>
</body>
</html>

//InsertUserServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/InsertUserServlet")
public class InsertUserServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        String jdbcURL = "jdbc:mysql://localhost:3306/user_db";
        String dbUser = "root"; // Change as needed
        String dbPassword = "password"; // Change as needed

        try (Connection conn = DriverManager.getConnection(jdbcURL, dbUser, dbPassword)) {
            String sql = "INSERT INTO users (username, password) VALUES (?, ?)";
            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setString(1, username);
            statement.setString(2, password);
            statement.executeUpdate();

            PrintWriter out = response.getWriter();
            out.println("<html><body><b>User registered successfully!</b></body></html>");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
//UpdateUserServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/UpdateUserServlet")
public class UpdateUserServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String newPassword = request.getParameter("newPassword");

        String jdbcURL = "jdbc:mysql://localhost:3306/user_db";
        String dbUser = "root"; // Change as needed
        String dbPassword = "password"; // Change as needed

        try (Connection conn = DriverManager.getConnection(jdbcURL, dbUser, dbPassword)) {
            String sql = "UPDATE users SET password = ? WHERE username = ?";
            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setString(1, newPassword);
            statement.setString(2, username);
            int rowsUpdated = statement.executeUpdate();

            PrintWriter out = response.getWriter();
            if (rowsUpdated > 0) {
                out.println("<html><body><b>Password updated successfully!</b></body></html>");
            } else {
                out.println("<html><body><b>User not found!</b></body></html>");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
//web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <servlet>
        <servlet-name>InsertUserServlet</servlet-name>
        <servlet-class>InsertUserServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>InsertUserServlet</servlet-name>
        <url-pattern>/InsertUserServlet</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>UpdateUserServlet</servlet-name>
        <servlet-class>UpdateUserServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>UpdateUserServlet</servlet-name>
        <url-pattern>/UpdateUserServlet</url-pattern>
    </servlet-mapping>

</web-app>
//cookies1
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * Servlet implementation class CookieServlet1      */
 
@WebServlet("/Cookie1")
public class cookie1 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    
    public cookie1() {
        super();
        // TODO Auto-generated constructor stub
    }
 
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
	
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out=response.getWriter();
		
        String name = request.getParameter("username");
        String pass = request.getParameter("password");
        String email=request.getParameter("email");
        
            Cookie ck = new Cookie("username", name);
            Cookie ck1=new Cookie("emailaddr",email);
            
            response.addCookie(ck);
            response.addCookie(ck1);
            out.println("<h1> Hello, welcome " + name 
                    + "!!! </h1>"); 
        out.println( 
            "<h1><a href =\"Cookie2\">Course Details</a></h1>");
 
        	     		}
 
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
 
}
 
//cooki2
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * Servlet implementation class CookieServlet2     */
@WebServlet("/Cookie2")
public class CookieServlet2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CookieServlet2() {
        super();
        // TODO Auto-generated constructor stub
    }
 
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
 
		response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        response.setContentType("text/html");
        out.println("<h1> Welcome Back!!!</h1>");
        
        Cookie[] cks = request.getCookies();
        
        for(int i=0;i<cks.length;i++)
        out.println("<h1> "+cks[i].getName()+": "+ cks[i].getValue()+"</h1>");
	}
 
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
 
}

//index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>LoginPage</title>
<style >
div{
display:block;
height:600px;
color:white;
}
</style> 
</head> 
<body style="text-align:center;background-color:green;">
<div >
 
<form action="Cookie1" method="post" >
 
<h1> Login to Cookie Application </h1>
 
<label>Username:</label><input type="text" name="username" ><br>
 
<label>Password:</label><input type="password" name="password"><br>
 
<label>email: </label><input type="text" name="email"><br>

<button type="submit" value="Login" >Submit</button>
</form>
</div>
</body>
</html>
// Array Destructuring Example

const fruits = ["Apple", "Banana", "Cherry"];
const [firstFruit, secondFruit] = fruits;

console.log("First Fruit:", firstFruit);   // Output: Apple
console.log("Second Fruit:", secondFruit);  // Output: Banana

// Skipping Elements Example
const numbers = [1, 2, 3, 4, 5];
const [one, , three] = numbers;
console.log("One:", one);                   // Output: 1
console.log("Three:", three);               // Output: 3

// Rest Parameter Example
const colors = ["Red", "Green", "Blue", "Yellow"];
const [primaryColor, ...otherColors] = colors;
console.log("Primary Color:", primaryColor);      // Output: Red
console.log("Other Colors:", otherColors);        // Output: ["Green", "Blue", "Yellow"]

// Function Returning Array Example
function getCoordinates() {
    return [10, 20];
}

const [x, y] = getCoordinates();
console.log("X Coordinate:", x);                // Output: 10
console.log("Y Coordinate:", y);                // Output: 20


// Object Destructuring Example

const person = {
    name: "John",
    age: 30,
    city: "New York"
};

const { name, age } = person;
console.log("Name:", name);                     // Output: John
console.log("Age:", age);                       // Output: 30

// Renaming Variables Example
const { name: fullName, age: years } = person;
console.log("Full Name:", fullName);           // Output: John
console.log("Years:", years);                   // Output: 30

// Default Values Example
const { country = "USA" } = person;
console.log("Country:", country);               // Output: USA (default value)

// Nested Destructuring Example
const user = {
    id: 1,
    details: {
        name: "Alice",
        age: 25,
        address: {
            city: "Los Angeles",
            zipCode: "90001"
        }
    }
};

const { details: { name:userName, address:{ city:userCity } } } = user;
console.log("User Name:", userName);           // Output: Alice
console.log("User City:", userCity);           // Output: Los Angeles

// Initialize a string for demonstration
let originalString = "  Hello, World!  ";

console.log("Original String:", originalString);

// 1. charAt()
console.log("Character at index 0:", originalString.charAt(0)); // H

// 2. concat()
let greeting = originalString.concat(" Welcome to JavaScript.");
console.log("Concatenated String:", greeting);

// 3. includes()
console.log("Includes 'World':", originalString.includes("World")); // true

// 4. indexOf()
console.log("Index of 'o':", originalString.indexOf("o")); // 4

// 5. lastIndexOf()
console.log("Last index of 'o':", originalString.lastIndexOf("o")); // 8

// 6. replace()
let replacedString = originalString.replace("World", "JavaScript");
console.log("Replaced String:", replacedString); // Hello, JavaScript!

// 7. split()
let fruitsString = "Apple,Banana,Cherry";
let fruitsArray = fruitsString.split(",");
console.log("Fruits Array:", fruitsArray); // ["Apple", "Banana", "Cherry"]

// 8. toLowerCase()
console.log("Lowercase String:", originalString.toLowerCase()); // hello, world!

// 9. toUpperCase()
console.log("Uppercase String:", originalString.toUpperCase()); // HELLO, WORLD!

// 10. trim()
console.log("Trimmed String:", originalString.trim()); // Hello, World!

/*OUTPUT:
Original String:    Hello, World!  
Character at index 0:  
Concatenated String:    Hello, World!  Welcome to JavaScript.
Includes 'World': true
Index of 'o': 4
Last index of 'o': 8
Replaced String:    Hello, JavaScript!  
Fruits Array: [ 'Apple', 'Banana', 'Cherry' ]
Lowercase String:    hello, world!  
Uppercase String:    HELLO, WORLD!  
Trimmed String: Hello, World!*/
//JavaScript Program
// Initialize an array of fruits
let fruits = ["Banana", "Orange", "Apple"];

// 1. push() - Add an element to the end of the array
console.log("Initial fruits:", fruits);
fruits.push("Mango");
console.log("After push('Mango'):", fruits); // Output: ["Banana", "Orange", "Apple", "Mango"]

// 2. pop() - Remove the last element from the array
const lastFruit = fruits.pop();
console.log("After pop():", fruits); // Output: ["Banana", "Orange", "Apple"]
console.log("Removed fruit:", lastFruit); // Output: "Mango"

// 3. shift() - Remove the first element from the array
const firstFruit = fruits.shift();
console.log("After shift():", fruits); // Output: ["Orange", "Apple"]
console.log("Removed fruit:", firstFruit); // Output: "Banana"

// 4. unshift() - Add an element to the beginning of the array
fruits.unshift("Banana");
console.log("After unshift('Banana'):", fruits); // Output: ["Banana", "Orange", "Apple"]

// 5. splice() - Remove and add elements in the array
fruits.splice(1, 1, "Kiwi"); // Removes 1 element at index 1 and adds "Kiwi"
console.log("After splice(1, 1, 'Kiwi'):", fruits); // Output: ["Banana", "Kiwi", "Apple"]

// 6. slice() - Create a shallow copy of a portion of the array
const citrus = fruits.slice(1, 3);
console.log("Slice from index 1 to 3:", citrus); // Output: ["Kiwi", "Apple"]

// 7. concat() - Merge two or more arrays
const moreFruits = ["Pineapple", "Grapes"];
const allFruits = fruits.concat(moreFruits);
console.log("After concat(moreFruits):", allFruits); // Output: ["Banana", "Kiwi", "Apple", "Pineapple", "Grapes"]

// 8. forEach() - Execute a function for each element in the array
console.log("Listing all fruits:");
allFruits.forEach(function(item, index) {
    console.log(index + ": " + item);
});

// Final output of all operations
console.log("Final fruits array:", allFruits);
//login.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login Page</title>
</head>
<body>
    <h2>Login</h2>
    <form action="LoginServlet" method="post">
        Username: <input type="text" name="username" required><br><br>
        <input type="submit" value="Login">
    </form>
</body>
</html>

//Login Servlet.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");

        // Create a new session or retrieve existing one
        HttpSession session = request.getSession();
        
        // Store the username in the session
        session.setAttribute("username", username);

        // Redirect to welcome page
        response.sendRedirect("welcome.jsp");
    }
}
//welcome.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="javax.servlet.http.HttpSession" %>
<%
    HttpSession session = request.getSession(false); // Get existing session
    String username = null;

    if (session != null) {
        username = (String) session.getAttribute("username");
    }

    if (username == null) {
        response.sendRedirect("login.html"); // Redirect to login if not logged in
    }
%>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Welcome</title>
</head>
<body>
    <h2>Welcome, <%= username %>!</h2>
    <a href="LogoutServlet">Logout</a> <!-- Link to logout -->
</body>
</html>
//logout.java

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/LogoutServlet")
public class LogoutServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Invalidate the session
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate(); // Remove all attributes and invalidate the session
        }
        
        // Redirect to login page
        response.sendRedirect("login.html");
    }
}
//index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Parameter Input Form</title>
</head>
<body>
    <h2>Enter Your Details</h2>
    <form action="ParameterServlet" method="post">
        Name: <input type="text" name="name" required><br><br>
        Age: <input type="text" name="age" required><br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

//ParameterServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/ParameterServlet")
public class ParameterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Retrieve parameters from the request
        String name = request.getParameter("name");
        String age = request.getParameter("age");

        // Set response content type
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        // Generate response
        out.println("<html><body>");
        out.println("<h2>Your Details:</h2>");
        out.println("<p>Name: " + name + "</p>");
        out.println("<p>Age: " + age + "</p>");
        out.println("</body></html>");
        
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Redirect to doPost for GET requests
        doPost(request, response);
    }
}
//Servlet Class
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// Annotate the servlet with a URL pattern
@WebServlet("/lifecycle")
public class ServletLifeCycleExample extends HttpServlet {

    private static final long serialVersionUID = 1L;

    // Constructor
    public ServletLifeCycleExample() {
        System.out.println("Constructor called: Servlet instance created.");
    }

    // init method called once when the servlet is loaded
    @Override
    public void init() throws ServletException {
        System.out.println("Init method called: Servlet initialized.");
    }

    // service method called for each request
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Service method called: Handling request.");

        // Set response content type
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        // Write response to client
        out.println("<html><body>");
        out.println("<h1>Servlet Lifecycle Example</h1>");
        out.println("<p>This is a response from the service method.</p>");
        out.println("</body></html>");
        
        out.close();
    }

    // destroy method called once when the servlet is taken out of service
    @Override
    public void destroy() {
        System.out.println("Destroy method called: Servlet is being destroyed.");
    }
} 

//web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <servlet>
        <servlet-name>lifecycleServlet</servlet-name>
        <servlet-class>ServletLifeCycleExample</servlet-class>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>lifecycleServlet</servlet-name>
        <url-pattern>/lifecycle</url-pattern>
    </servlet-mapping>
</web-app>


//OUTPUT
Constructor called: Servlet instance created.
Init method called: Servlet initialized.
Service method called: Handling request.
Destroy method called: Servlet is being destroyed.
//SQL:
CREATE TABLE Users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(50) NOT NULL,
    password VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL
);

//INSERT
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class InsertUser {
    private static final String INSERT_USER_SQL = "INSERT INTO Users (username, password, email) VALUES (?, ?, ?)";

    public static void main(String[] args) {
        try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");
             PreparedStatement preparedStatement = connection.prepareStatement(INSERT_USER_SQL)) {

            preparedStatement.setString(1, "john_doe");
            preparedStatement.setString(2, "securepassword");
            preparedStatement.setString(3, "john@example.com");

            int rowsAffected = preparedStatement.executeUpdate();
            System.out.println(rowsAffected + " row(s) inserted.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

//SELECT
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class SelectUsers {
    private static final String SELECT_ALL_USERS_SQL = "SELECT * FROM Users";

    public static void main(String[] args) {
        try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");
             PreparedStatement preparedStatement = connection.prepareStatement(SELECT_ALL_USERS_SQL);
             ResultSet resultSet = preparedStatement.executeQuery()) {

            while (resultSet.next()) {
                System.out.println("ID: " + resultSet.getInt("id") +
                                   ", Username: " + resultSet.getString("username") +
                                   ", Email: " + resultSet.getString("email"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

//UPDATE
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class UpdateUserEmail {
    private static final String UPDATE_EMAIL_SQL = "UPDATE Users SET email = ? WHERE username = ?";

    public static void main(String[] args) {
        try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");
             PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_EMAIL_SQL)) {

            preparedStatement.setString(1, "new_email@example.com");
            preparedStatement.setString(2, "john_doe");

            int rowsAffected = preparedStatement.executeUpdate();
            System.out.println(rowsAffected + " row(s) updated.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

//OUTPUT:
ID: 1, Username: john_doe, Email: john@example.com
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sort and Reverse Array Methods</title>
</head>
<body>

<h1>JavaScript Array Sorting and Reversing</h1>

<script>
   
    const fruits = ["Banana", "Apple", "Orange", "Mango"];
    console.log("Original Fruits Array:", fruits);
    fruits.sort();
    console.log("Sorted Fruits Array:", fruits); 

    
    const numbers = [10, 2, 5, 30];
    console.log("\nOriginal Numbers Array:", numbers);
    numbers.sort((a, b) => a - b); 
    console.log("Sorted Numbers (Ascending):", numbers); 

   
    numbers.sort((a, b) => b - a); 
    console.log("Sorted Numbers (Descending):", numbers); 

    
    const letters = ["a", "b", "c", "d"];
    console.log("\nOriginal Letters Array:", letters);
    letters.reverse();
    console.log("Reversed Letters Array:", letters); 


    const mixNumbers = [15, 3, 25, 8];
    mixNumbers.sort((a, b) => a - b).reverse(); 
    console.log("\nMixed Numbers Sorted in Descending Order:", mixNumbers); // Output: [25, 15, 8, 3]
</script>

</body>
</html>
https://github.com/cvrcoe26/wt
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>String Methods in JavaScript</title>
</head>
<body>

<h1>JavaScript String Methods</h1>


<script>
    const str = "   Hello, JavaScript World!   ";

    console.log("Original String:", str);

    
    console.log("\ntrim() method:");
    const trimmedStr = str.trim();
    console.log("Trimmed String:", trimmedStr);

  
    console.log("\ntoUpperCase() method:");
    console.log("Uppercase:", trimmedStr.toUpperCase());

  
    console.log("\ntoLowerCase() method:");
    console.log("Lowercase:", trimmedStr.toLowerCase());

    
    console.log("\nslice() method:");
    console.log("Sliced:", trimmedStr.slice(7, 17)); // Extracts "JavaScript"

    console.log("\nreplace() method:");
    console.log("Replaced:", trimmedStr.replace("JavaScript", "Coding"));

    
    console.log("\nincludes() method:");
    console.log("Includes 'World':", trimmedStr.includes("World")); // true


    console.log("\nsplit() method:");
    console.log("Split by space:", trimmedStr.split(" ")); // ["Hello,", "JavaScript", "World!"]


    console.log("\nrepeat() method:");
    console.log("Repeated String:", "Hi! ".repeat(3));

    
</script>

</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Array Methods Demo</title>
</head>
<body>
    <h1>Array Methods in JavaScript</h1>

    <script>


        console.log("push() method:");
        const fruits = ["Apple", "Banana"];
        fruits.push("Orange");

        console.log("\npop() method:");
        const lastFruit = fruits.pop();
        console.log(lastFruit); 
        console.log(fruits);    

        console.log("\nshift() method:");
        const firstFruit = fruits.shift();
        console.log(firstFruit); 
        console.log(fruits);    

        console.log("\nunshift() method:");
        fruits.unshift("Apple");
        console.log(fruits);

        console.log("\nsplice() method:");
        const newFruits = ["Apple", "Banana", "Orange", "Mango"];
        const removedFruits = newFruits.splice(1, 2, "Grapes");
        console.log("Removed Fruits:", removedFruits); 
        console.log("Updated Fruits:", newFruits);     

        console.log("\nslice() method:");
        const citrus = newFruits.slice(0, 2);
        console.log("Sliced Fruits:", citrus);
        console.log("Original Fruits:", newFruits); 

        console.log("\nmap() method:");
        const numbers = [1, 2, 3, 4];
        const doubled = numbers.map(num => num * 2);
        console.log("Doubled Numbers:", doubled);

        console.log("\nfilter() method:");
        const evenNumbers = numbers.filter(num => num % 2 === 0);
        console.log("Even Numbers:", evenNumbers); 
    </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Destructuring in JavaScript</title>
</head>
<body>
  <h1>JavaScript Destructuring Examples</h1>
  

  <script>
    // ARRAY DESTRUCTURING

    // 1. Basic Array Destructuring
    const fruits = ["Apple", "Banana", "Cherry"];
    const [firstFruit, secondFruit, thirdFruit] = fruits;
    console.log("Basic Array Destructuring:");
    console.log(firstFruit);  
    console.log(secondFruit); 
    console.log(thirdFruit);  
    console.log("------------");

    // 2. Skipping Elements
    const numbers = [1, 2, 3, 4, 5];
    const [, secondNum, , fourthNum] = numbers;
    console.log("Skipping Elements:");
    console.log(secondNum);
    console.log(fourthNum); 
    console.log("------------");

    // 3. Default Values
    const colors = ["Red"];
    const [primaryColor, secondaryColor = "Green"] = colors;
    console.log("Default Values:");
    console.log(primaryColor); 
    console.log(secondaryColor); 
    console.log("------------");

    // 4. Rest Operator with Arrays
    const languages = ["JavaScript", "Python", "Ruby", "C++"];
    const [firstLang, ...otherLangs] = languages;
    console.log("Rest Operator with Arrays:");
    console.log(firstLang);    
    console.log(otherLangs);   
    console.log("------------");

    // OBJECT DESTRUCTURING

    // 1. Basic Object Destructuring
    const person = {
      name: "Alice",
      age: 25,
      country: "USA"
    };
    const { name, age, country } = person;
    console.log("Basic Object Destructuring:");
    console.log(name);    
    console.log(age);     
    console.log(country); 
    console.log("------------");

    // 2. Renaming Variables
    const student = {
      fullName: "John Doe",
      grade: "A"
    };
    const { fullName: studentName, grade: finalGrade } = student;
    console.log("Renaming Variables:");
    console.log(studentName);   
    console.log(finalGrade);    
    console.log("------------");

    // 3. Default Values in Objects
    const settings = {
      theme: "dark"
    };
    const { theme, fontSize = 16 } = settings;
    console.log("Default Values in Objects:");
    console.log(theme);    
    console.log(fontSize); 
    console.log("------------");

    // 4. Rest Operator with Objects
    const car = {
      make: "Toyota",
      model: "Corolla",
      year: 2021,
      color: "Blue"
    };
    const { make, model, ...otherDetails } = car;
    console.log("Rest Operator with Objects:");
    console.log(make);          
    console.log(model);         
    console.log(otherDetails);  
    console.log("------------");

    // FUNCTION PARAMETERS DESTRUCTURING

    // 1. Array Destructuring in Function Parameters
    function printFirstTwo([first, second]) {
      console.log("Array Destructuring in Function Parameters:");
      console.log("First:", first);
      console.log("Second:", second);
    }
    printFirstTwo(["Apple", "Banana", "Cherry"]);
    console.log("------------");

    // 2. Object Destructuring in Function Parameters
    function displayUserInfo({ username, email }) {
      console.log("Object Destructuring in Function Parameters:");
      console.log("Username:", username);
      console.log("Email:", email);
    }
    displayUserInfo({ username: "johndoe", email: "johndoe@example.com" });
    console.log("------------");

  </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>College Website</title>
    <style>
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        html, body {
            height: 100%;
            display: flex;
            flex-direction: column;
        }

      
        header {
            background-color: #4CAF50;
            color: white;
            padding: 10px;
            text-align: center;
        }

        /* Navigation styling */
        nav {
            display: flex;
            background-color: #333;
        }
        nav a {
            color: white;
            text-align: center;
            padding: 14px 20px;
            text-decoration: none;
            flex: 1;
        }
        nav a:hover {
            background-color: #ddd;
            color: black;
        }

        /* Main layout */
        .container {
            display: flex;
            flex: 1;
            padding: 20px;
        }

        /* Sidebar styling */
        .sidebar {
            width: 25%;
            background-color: #f4f4f4;
            padding: 20px;
            border-right: 1px solid #ccc;
        }

        /* Content styling */
        .content {
            flex: 1;
            display: flex;
            flex-direction: column;
            padding: 20px;
        }

        /* Courses section */
        .courses {
            display: flex;
            flex-direction: row;
            flex-wrap: wrap;
            gap: 20px;
            margin-top: 20px;
        }
        .box {
            background-color: #ddd;
            border: 1px solid #ccc;
            padding: 20px;
            width: calc(33.33% - 20px);
        }

        /* Footer styling */
        footer {
            background-color: #333;
            color: white;
            text-align: center;
            padding: 10px;
        }
    </style>
</head>
<body>

    <!-- Header -->
    <header>
        <h1>University Name</h1>
    </header>

    <!-- Navigation Bar -->
    <nav>
        <a href="#home">Home</a>
        <a href="#about">About</a>
        <a href="#courses">Courses</a>
        <a href="#contact">Contact</a>
    </nav>

    <!-- Main Container -->
    <div class="container">

        <!-- Left Sidebar -->
        <div class="sidebar">
            <h2>Menu</h2>
            <ul>
                <li><a href="#menu1">Menu Item 1</a></li>
                <li><a href="#menu2">Menu Item 2</a></li>
                <li><a href="#menu3">Menu Item 3</a></li>
            </ul>
        </div>

        <!-- Main Content -->
        <div class="content">
            <h2>Main Content</h2>
            <p>Welcome to our university's website. Here you can explore the various courses we offer and learn more about our campus life.</p>
            
            <!-- Courses Section -->
            <div class="courses">
                <div class="box">Course 1</div>
                <div class="box">Course 2</div>
                <div class="box">Course 3</div>
                <div class="box">Course 4</div>
                <div class="box">Course 5</div>
                <div class="box">Course 6</div>
            </div>
        </div>

        <!-- Right Sidebar (Optional) -->
        <div class="sidebar">
            <h2>Promotions</h2>
            <p>Check out our latest programs and offers for students.</p>
        </div>
    </div>

    <!-- Footer -->
    <footer>
        <p>&copy; 2024 University Name. All rights reserved.</p>
    </footer>

</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .container{
            border: 2px solid red;
            display: grid;
            grid-template-columns:100px 120px 100px;
            grid-template-rows: 100px 100px 100px;
            background-color: rgb(166, 120, 209);
                     
            
        }
        .item{
            height: 45px;
            width: 45px;
            border: 5px solid black;
            margin: 5px;

        }
    </style>
</head>
<body>
    <div class="container">
        <div class="item">1</div>
        <div class="item">2</div>
        <div class="item">3</div>
        <div class="item">4</div>
        <div class="item">5</div>
        <div class="item">6</div>
        <div class="item">7</div>
        <div class="item">8</div>

    </div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
    <title>Grid Layout</title>
    <style>
        .container {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            /* Define 2 rows, first row 50% of height, second row auto */
            grid-template-rows: 1fr auto;
            gap: 20px;
            background-color: cornflowerblue;
            padding: 20px;
            height: 100vh;
            width: 100%;
        }

        .container > div {
            background-color: rgb(138, 138, 182);
            border: 1px solid black;
            padding: 20px;
            text-align: center;
            font-size: 20px;
        }

        /* Example of grid item properties */
        .item1 {
            grid-column: 1 / span 2; /* Spans across 2 columns */
            grid-row: 1; /* Positions in the first row */
        }

        .item2 {
            grid-column: 3; /* Positions in the third column */
            grid-row: 1; /* Positions in the first row */
        }

        .item3 {
            grid-column: 2 / span 2; /* Spans across columns 2 and 3 */
            grid-row: 2; /* Positions in the second row */
        }
    </style>
</head>
<body>
    <h1 style="text-align: center;">This is my first Grid Layout</h1>
    <div class="container">
        <div class="item1">
            <p>Name: S</p>
            <p>Roll No: 22B81A0</p>
            <p>Branch: CSE</p>
            <p>Section: E</p>
            <p>CGPA: 9.7</p>
        </div>
        <div class="item2">
            <p>Name: S</p>
            <p>Roll No: 22B81A0</p>
            <p>Branch: CSE</p>
            <p>Section: E</p>
            <p>CGPA: 9.0</p>
        </div>
        <div class="item3">
            <p>Name:</p>
            <p>Roll No: 22B81A0</p>
            <p>Branch: CSE</p>
            <p>Section: E</p>
            <p>CGPA: 9.5</p>
        </div>
    </div>
</body>
</html>
var TYPR_CHD_NO_TWO = $('input[name="TYPR_CHD_NO_TWO[]"]').map(function() {
                return $(this).val();
            }).get();
            
<!DOCTYPE html>
<html>
<head>
    <title>Flex Item</title>
    <style>
        .container {
            display: flex;
            flex-wrap: wrap;
            flex-direction: row;
            align-items: center;
            justify-content: space-evenly;
            background-color: cornflowerblue;
            height: 100vh;
            width: 100%;
            position: fixed;
        }

        .item{
            color: black;
            border: 1px solid black;
            padding: 10px;
            margin: 10px;
            background-color: lavender;
            text-align: center;
            padding-top: 50px;
            font-size: 20px;
        }
    </style>
</head>
<body>
    <h1 style="text-align: center;">This is my first Flex</h1>
    <div class="container">
        <div class ="item">
            <p>Name: S</p>
            <p>Roll No: 22B81A05</p>
            <p>Branch: CSE</p>
            <p>Section: E</p>
            <p>CGPA: 9.7</p>
        </div>
        <div class ="item">
            <p>Name: S</p>
            <p>Roll No: 22B81A05</p>
            <p>Branch: CSE</p>
            <p>Section: E</p>
            <p>CGPA: 9.0</p>
        </div>
        <div class ="item">
            <p>Name: S</p>
            <p>Roll No: 22B81A05</p>
            <p>Branch: CSE</p>
            <p>Section: E</p>
            <p>CGPA: 9.5</p>
        </div>
    </div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Inline Style Example</title>
</head>
<body style="font-family: Arial, sans-serif; 
            background-color: #f0f0f0; 
            margin: 0; 
            padding: 0;">


    <div id="main-content" style="padding: 40px; 
            background-color: #ffffff; 
            border: 1px solid #ddd; 
            max-width: 800px; 
            margin: 20px auto;">
        <h1 style="color: #333; 
            text-align: center; 
            padding: 20px;">Welcome to Inline CSS Styling</h1>


        <p style="color: #666; 
            font-size: 18px; 
            line-height: 1.6; 
            margin: 20px;">
            This is an example of inline styling. Each HTML element has its own <code>style</code> attribute for defining CSS rules.
        </p>
        <p style="color: #0056b3;  
            font-weight: bold; 
            margin: 20px;">
            This paragraph uses an inline style to set specific text color and font weight.
        </p>
    </div>

</body>
</html>
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>External Style Sheet Example</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>

    <div id="main-content">
        <h1>Welcome to External CSS Styling</h1>
        <p>This is an example of an external style sheet. The styles are stored in a separate file named <code>styles.css</code>.</p>
        <p class="highlight">This paragraph has additional styling with a specific class.</p>
    </div>

</body>
</html>



CSS:
/* styles.css */

body {
    font-family: Arial, sans-serif;
    background-color: #f0f0f0;
    margin: 0;
    padding: 0;
}

h1 {
    color: #333;
    text-align: center;
    padding: 20px;
}

p {
    color: #666;
    font-size: 18px;
    line-height: 1.6;
    margin: 20px;
}

.highlight {
    color: #0056b3;
    font-weight: bold;
}

#main-content {
    padding: 40px;
    background-color: #ffffff;
    border: 1px solid #ddd;
    max-width: 800px;
    margin: 20px auto;
}
star

Sun Nov 03 2024 13:55:40 GMT+0000 (Coordinated Universal Time)

@login123

star

Sun Nov 03 2024 13:54:31 GMT+0000 (Coordinated Universal Time)

@login123

star

Sun Nov 03 2024 13:52:10 GMT+0000 (Coordinated Universal Time)

@signup_returns #html

star

Sun Nov 03 2024 13:45:01 GMT+0000 (Coordinated Universal Time)

@varuntej #python

star

Sun Nov 03 2024 13:34:53 GMT+0000 (Coordinated Universal Time)

@signup_returns #html

star

Sun Nov 03 2024 13:30:43 GMT+0000 (Coordinated Universal Time)

@signup_returns #html

star

Sun Nov 03 2024 13:27:38 GMT+0000 (Coordinated Universal Time)

@varuntej #python

star

Sun Nov 03 2024 13:14:38 GMT+0000 (Coordinated Universal Time)

@varuntej #python

star

Sun Nov 03 2024 12:49:12 GMT+0000 (Coordinated Universal Time)

@varuntej #c

star

Sun Nov 03 2024 12:49:09 GMT+0000 (Coordinated Universal Time)

@signup1

star

Sun Nov 03 2024 12:48:01 GMT+0000 (Coordinated Universal Time)

@varuntej #c

star

Sun Nov 03 2024 12:45:43 GMT+0000 (Coordinated Universal Time)

@varuntej #c

star

Sun Nov 03 2024 12:45:37 GMT+0000 (Coordinated Universal Time)

@signup1

star

Sun Nov 03 2024 12:43:54 GMT+0000 (Coordinated Universal Time)

@signup1

star

Sun Nov 03 2024 12:41:56 GMT+0000 (Coordinated Universal Time)

@varuntej #kotlin

star

Sun Nov 03 2024 12:40:56 GMT+0000 (Coordinated Universal Time)

@varuntej #c

star

Sun Nov 03 2024 12:36:33 GMT+0000 (Coordinated Universal Time)

@signup1

star

Sun Nov 03 2024 12:35:57 GMT+0000 (Coordinated Universal Time)

@signup1

star

Sun Nov 03 2024 12:33:52 GMT+0000 (Coordinated Universal Time)

@signup1

star

Sun Nov 03 2024 12:32:50 GMT+0000 (Coordinated Universal Time)

@signup1

star

Sun Nov 03 2024 12:13:49 GMT+0000 (Coordinated Universal Time)

@signup1

star

Sun Nov 03 2024 12:09:19 GMT+0000 (Coordinated Universal Time)

@signup1

star

Sun Nov 03 2024 12:01:22 GMT+0000 (Coordinated Universal Time)

@signup1

star

Sun Nov 03 2024 11:53:55 GMT+0000 (Coordinated Universal Time)

@signup1

star

Sun Nov 03 2024 11:50:03 GMT+0000 (Coordinated Universal Time)

@signup1

star

Sun Nov 03 2024 11:44:42 GMT+0000 (Coordinated Universal Time)

@signup1

star

Sun Nov 03 2024 11:32:58 GMT+0000 (Coordinated Universal Time)

@signup1

star

Sun Nov 03 2024 11:21:15 GMT+0000 (Coordinated Universal Time)

@signup1

star

Sun Nov 03 2024 11:02:32 GMT+0000 (Coordinated Universal Time)

@signup1

star

Sun Nov 03 2024 11:01:03 GMT+0000 (Coordinated Universal Time)

@login123

star

Sun Nov 03 2024 10:51:17 GMT+0000 (Coordinated Universal Time)

@abhigna

star

Sun Nov 03 2024 10:31:05 GMT+0000 (Coordinated Universal Time)

@login123

star

Sun Nov 03 2024 10:11:34 GMT+0000 (Coordinated Universal Time)

@login123

star

Sun Nov 03 2024 09:44:31 GMT+0000 (Coordinated Universal Time)

@login123

star

Sun Nov 03 2024 08:59:32 GMT+0000 (Coordinated Universal Time)

@login123

star

Sun Nov 03 2024 08:59:07 GMT+0000 (Coordinated Universal Time)

@login123

star

Sun Nov 03 2024 08:58:45 GMT+0000 (Coordinated Universal Time)

@login123

star

Sun Nov 03 2024 07:01:01 GMT+0000 (Coordinated Universal Time)

@Sifat_H #php

star

Sun Nov 03 2024 06:34:57 GMT+0000 (Coordinated Universal Time)

@login123

star

Sun Nov 03 2024 05:43:52 GMT+0000 (Coordinated Universal Time)

@login123

star

Sun Nov 03 2024 05:40:23 GMT+0000 (Coordinated Universal Time)

@login123

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension