slips
November 30, 2023

SLIP19

Q.1 Write a Java Program to implement command pattern to test Remote Control

// Command interface
interface Command {
    void execute();
}

// Concrete Command classes
class LightOnCommand implements Command {
    private Light light;

    public LightOnCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.turnOn();
    }
}

class LightOffCommand implements Command {
    private Light light;

    public LightOffCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.turnOff();
    }
}

// Receiver class
class Light {
    public void turnOn() {
        System.out.println("Light is ON");
    }

    public void turnOff() {
        System.out.println("Light is OFF");
    }
}

// Invoker class
class RemoteControl {
    private Command command;

    public void setCommand(Command command) {
        this.command = command;
    }

    public void pressButton() {
        command.execute();
    }
}

// Client
public class RemoteControlTest {
    public static void main(String[] args) {
        // Creating instances
        Light light = new Light();
        Command lightOnCommand = new LightOnCommand(light);
        Command lightOffCommand = new LightOffCommand(light);

        RemoteControl remoteControl = new RemoteControl();

        // Testing the remote control with the light
        remoteControl.setCommand(lightOnCommand);
        remoteControl.pressButton();

        remoteControl.setCommand(lightOffCommand);
        remoteControl.pressButton();
    }
}

Q.2 Write a python program to Implement Decision Tree Model for classification. Use Decision_Tree_Dataset.csv.

import pandas as pd

from sklearn.model_selection import train_test_split

from sklearn.tree import DecisionTreeClassifier

from sklearn.metrics import accuracy_score, classification_report, confusion_matrix

data = pd.read_csv('./csv/Decision_Tree_Dataset.csv')

X = data.drop('Target', axis=1)

y = data['Target']

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

clf = DecisionTreeClassifier()

clf.fit(X_train, y_train)

predictions = clf.predict(X_test)

accuracy = accuracy_score(y_test, predictions)

print("Accuracy:", accuracy)

print("\nClassification Report:")

print(classification_report(y_test, predictions))

print("\nConfusion Matrix:")

print(confusion_matrix(y_test, predictions))

# program to make csv file

# import pandas as pd

# from sklearn.datasets import make_classification

# # Create a synthetic dataset for Decision Tree

# X, y = make_classification(

#     n_samples=1000,        # Number of samples

#     n_features=5,          # Number of features

#     n_informative=3,       # Number of informative features

#     n_redundant=2,         # Number of redundant features

#     n_classes=2,           # Number of classes (binary classification)

#     random_state=42        # Random state for reproducibility

# )

# # Create a DataFrame to hold the synthetic dataset

# columns = [f"Feature_{i+1}" for i in range(X.shape[1])]

# columns.append('Target')

# decision_tree_data = pd.DataFrame(data=pd.concat([pd.DataFrame(X, columns=columns[:-1]), pd.DataFrame(y, columns=['Target'])], axis=1))

# # Save the synthetic dataset to a CSV file

# decision_tree_data.to_csv('./csv/Decision_Tree_Dataset.csv', index=False)

Q.3 Implement useEffect hook and print all three life cycle states a. e.g Inside mount b. e.g Inside update c. e.g Inside unmount

Paste LifecycleExample.jsx in src folder

After Running The React App On Port . Press Right Click On Web Page And Choose Inspect Option And Select The Console Tab To Show The Log .

import React, { useState, useEffect } from 'react';

const LifecycleExample = () => {
  // Mounting
  useEffect(() => {
    console.log('Inside mount');
    
    // Cleanup function (will be called on unmount)
    return () => {
      console.log('Inside unmount');
    };
  }, []);

  // Updating
  useEffect(() => {
    console.log('Inside update');

    // Cleanup function (will be called on update and unmount)
    return () => {
      console.log('Inside unmount (from update)');
    };
  });

  // State for updating
  const [count, setCount] = useState(0);

  return (
    <div>
      <h1>Slip 7</h1>
      <h2>Lifecycle Example</h2>
      <p>Current Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increase Count</button>
    </div>
  );
};

export default LifecycleExample;