Wednesday, December 20, 2023

AL/ML

Command to open jupiter

python  -m jupyter lab


Read the file

 import pandas as pd

# Specify the path to your CSV file

csv_file_path = 'path/to/your/file.csv'


# Read the CSV file into a DataFrame

df = pd.read_csv(csv_file_path)


# Display the DataFrame

print(df)


# Display the first 5 rows of the DataFrame
print(df.head())

# Display specific columns
print(df[['Column1', 'Column2']])

------------------------------------------------------------------------------------------
#install
pip install pandas
----------------------------------------------------------------------------

histogram

import matplotlib.pyplot as plt
import pandas as pd

# Specify the path to your CSV file
csv_file_path = 'manish.csv'

# Read the CSV file into a DataFrame
df = pd.read_csv(csv_file_path)

# Choose the column for which you want to create a histogram
selected_column = 'Number of employees'

# Create a histogram
plt.hist(df[selected_column], bins=10, color='blue', edgecolor='black')

# Customize the plot
plt.title('Histogram of {}'.format(selected_column))
plt.xlabel(selected_column)
plt.ylabel('Frequency')

# Show the plot
plt.show()
---------------------------------------------------------------------------------------------------------------
DATA CLEANINIG

    import pandas as pd

# Specify the path to your CSV file
csv_file_path = 'manish.csv'

# Read the CSV file into a DataFrame
df = pd.read_csv(csv_file_path)

# Check for missing values
print(df.isnull().sum())

# Drop rows with missing values
df_cleaned = df.dropna()

# Alternatively, fill missing values with a specific value
# df_cleaned = df.fillna(value)
df_cleaned = df.drop_duplicates()

Monday, December 18, 2023

Demonstrate WebView to display the web pages in an android application.

 activity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context=".MainActivity">



    <WebView

        android:id="@+id/web"

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        tools:layout_editor_absoluteX="8dp"

        tools:layout_editor_absoluteY="8dp" />

</RelativeLayout>


activity.java

import androidx.appcompat.app.AppCompatActivity;

import android.webkit.WebView;

import android.webkit.WebViewClient;

import android.os.Bundle;


public class MainActivity extends AppCompatActivity {


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        WebView webView = findViewById(R.id.web);


        webView.loadUrl("https://www.geeksforgeeks.org/how-to-use-webview-in-android/");


        webView.getSettings().setJavaScriptEnabled(true);

         webView.setWebViewClient(new WebViewClient());

    }


}

Q:- Write an android code to turn ON/OFF the Wi-Fi

 activity.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:layout_margin="16dp"

    android:gravity="center"

    android:orientation="vertical">


    <ToggleButton

        android:id="@+id/toggleButton"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:checked="false"

        />


    <TextView

        android:id="@+id/textView"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_marginTop="16dp"

        />


</LinearLayout>


activity.java


import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;

import android.net.wifi.WifiManager;

import android.os.Bundle;

import android.widget.CompoundButton;

import android.widget.TextView;

import android.widget.ToggleButton;



public class MainActivity extends AppCompatActivity {


    ToggleButton toggleButton;

    TextView textView;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        toggleButton = (ToggleButton) findViewById(R.id.toggleButton);

        textView = (TextView) findViewById(R.id.textView);


       

        toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override

            public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {

                if (checked) {

                    textView.setText("WiFi is ON");

                    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

                    wifi.setWifiEnabled(true);

                } else {

                    textView.setText("WiFi is OFF");

                    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

                    wifi.setWifiEnabled(false);

                }

            }

        });


        if (toggleButton.isChecked()) {

            textView.setText("WiFi is ON");

            WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

            wifi.setWifiEnabled(true);

        } else {

            textView.setText("WiFi is OFF");

            WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

            wifi.setWifiEnabled(false);

        }

    }


    }

Q:-Demonstrate Array Adapter using List View to display list of fruits.

 activity.xml

<RelativeLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context=".MainActivity">


    <ListView

        android:id="@+id/simpleListView"

        android:layout_width="match_parent"

        android:layout_height="wrap_content" />


</RelativeLayout>


activity.java

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.widget.ListView;

import android.widget.ArrayAdapter;

public class MainActivity extends AppCompatActivity {

        ListView simpleListView;


        // array objects

        String fruit[] = {"Apple", "Banana", "Mango", "strawberry"};


        @Override

        protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            setContentView(R.layout.activity_main);


            simpleListView = (ListView) findViewById(R.id.simpleListView);


            ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,

                    R.layout.item_view, R.id.itemTextView, fruit);

            simpleListView.setAdapter(arrayAdapter);

        }

    }

fruits,xml

<LinearLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical">


    <TextView

        android:id="@+id/itemTextView"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_gravity="center" />


</LinearLayout>

write an application to demonstrate Alert Dialog Box in android

 activity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context=".MainActivity">


    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_marginTop="180dp"

        android:gravity="center_horizontal"

        android:text="Press The Back Button of Your Phone."

        android:textSize="30dp"

        android:textStyle="bold" />


</RelativeLayout>


activity.java

import androidx.appcompat.app.AppCompatActivity;

import androidx.appcompat.app.AlertDialog;

import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;


import android.os.Bundle;


public class MainActivity extends AppCompatActivity {


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

    }


    @Override

    public void onBackPressed() {

        // Create the object of AlertDialog Builder class

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);


        // Set the message show for the Alert time

        builder.setMessage("Do you want to exit ?");


        // Set Alert Title

        builder.setTitle("Alert !");


        // Set Cancelable false for when the user clicks on the outside the Dialog Box then it will remain show

        builder.setCancelable(false);


        // Set the positive button with yes name Lambda OnClickListener method is use of DialogInterface interface.

        builder.setPositiveButton("Yes", (DialogInterface.OnClickListener) (dialog, which) -> {

            // When the user click yes button then app will close

            finish();

        });


        // Set the Negative button with No name Lambda OnClickListener method is use of DialogInterface interface.

        builder.setNegativeButton("No", (DialogInterface.OnClickListener) (dialog, which) -> {

            // If user click no then dialog box is canceled.

            dialog.cancel();

        });


        // Create the Alert dialog

        AlertDialog alertDialog = builder.create();

        // Show the Alert Dialog box

        alertDialog.show();

    }

}



Design android application for login activity. Write android code to check login credentials with username = "mca" and password = "android". Display appropriate toast message to the user

 activity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent">



    <EditText

        android:id="@+id/usernameEditText"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginTop="50dp"

        android:hint="Username"

        android:inputType="textEmailAddress" />


    <EditText

        android:id="@+id/passwordEditText"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_below="@id/usernameEditText"

        android:layout_marginTop="16dp"

        android:hint="Password"

        android:inputType="textPassword" />


    <Button

        android:id="@+id/loginButton"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_below="@id/passwordEditText"

        android:layout_marginTop="24dp"

        android:text="Login" />

</RelativeLayout>


activitymain.java

import androidx.appcompat.app.AppCompatActivity;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

import android.os.Bundle;


public class MainActivity extends AppCompatActivity {

    private EditText usernameEditText, passwordEditText;

    private Button loginButton;


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        usernameEditText = findViewById(R.id.usernameEditText);

        passwordEditText = findViewById(R.id.passwordEditText);

        loginButton = findViewById(R.id.loginButton);


        loginButton.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                performLogin();

            }

        });

    }


    private void performLogin() {

        String enteredUsername = usernameEditText.getText().toString().trim();

        String enteredPassword = passwordEditText.getText().toString().trim();


        // Check login credentials

        if (enteredUsername.equals("mca") && enteredPassword.equals("android")) {

            // Successful login

            showToast("Login successful!");

        } else {

            // Incorrect credentials

            showToast("Incorrect username or password. Please try again.");

        }

    }


    private void showToast(String message) {

        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();

    }}


Q.8) write a android program to used View.

 activity.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent">


    <com.example.customview.customview

        android:id="@+id/customview"

        android:layout_width="match_parent"

        android:layout_height="match_parent" />


</RelativeLayout>


customview.java

import android.content.Context;

import android.graphics.Canvas;

import android.graphics.Color;

import android.graphics.Paint;

import android.util.AttributeSet;

import android.view.View;


public class customview extends View {


    private Paint paint;


    public customview(Context context) {

        super(context);

        init();

    }


    public customview(Context context, AttributeSet attrs) {

        super(context, attrs);

        init();

    }


    private void init() {

        paint = new Paint();

        paint.setColor(Color.BLUE);

        paint.setStyle(Paint.Style.FILL);

    }


    @Override

    protected void onDraw(Canvas canvas) {

        super.onDraw(canvas);


        // Draw a colored rectangle

        canvas.drawRect(100, 100, getWidth() - 100, getHeight() - 100, paint);

    }

}


Q.4) Write android program to check the number is prime or not

activity.xml 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent">


    <EditText

        android:id="@+id/inputNumberEditText"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:hint="Enter a number"

        android:inputType="number" />


    <Button

        android:id="@+id/checkPrimeButton"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_below="@id/inputNumberEditText"

        android:layout_marginTop="16dp"

        android:text="Check Prime" />


    <TextView

        android:id="@+id/resultTextView"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_below="@id/checkPrimeButton"

        android:layout_marginTop="16dp"

        android:text="" />

</RelativeLayout>


activity.java

import androidx.appcompat.app.AppCompatActivity;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import android.os.Bundle;


public class MainActivity extends AppCompatActivity {


    private EditText inputNumberEditText;

    private Button checkPrimeButton;

    private TextView resultTextView;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        inputNumberEditText = findViewById(R.id.inputNumberEditText);

        checkPrimeButton = findViewById(R.id.checkPrimeButton);

        resultTextView = findViewById(R.id.resultTextView);


        checkPrimeButton.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                checkPrime();

            }

        });

    }

    private void checkPrime() {

        String inputNumberStr = inputNumberEditText.getText().toString().trim();


        if (!inputNumberStr.isEmpty()) {

            int number = Integer.parseInt(inputNumberStr);

            boolean isPrime = isPrime(number);


            if (isPrime) {

                resultTextView.setText(number + " is a prime number.");

            } else {

                resultTextView.setText(number + " is not a prime number.");

            }

        } else {

            resultTextView.setText("Please enter a number.");

        }

    }


    private boolean isPrime(int number) {

        if (number <= 1) {

            return false;

        }


        for (int i = 2; i <= Math.sqrt(number); i++) {

            if (number % i == 0) {

                return false; // Found a divisor, not a prime number

            }

        }


        return true; // No divisors found, it's a prime number

    }


}

Wednesday, August 9, 2023

Q1)Given a file called myfile.txt which contains the text: “Python is object oriented programming language”. Write a program in Python that transforms the content of the file by writing each word in a separate line.

 # Read the content from the file

with open("myfile.txt", "r") as file:

    content = file.read()

 

# Split the content into words

words = content.split()

 

# Write each word in a separate line to a new file

with open("transformed_file.txt", "w") as new_file:

    for word in words:

        new_file.write(word + "\n")

 

print("Content transformed and saved to transformed_file.txt")

10) Write a Menu Driver Program to add, display, search, sort and exit in book database containing Book_id, Book_name, Book_author through Python-MongoDB connectivity.

from pymongo import MongoClient

import pprint

 

# Connect to MongoDB

client = MongoClient("mongodb://localhost:27017/")

db = client["BookDatabase"]

collection = db["Books"]

 

def add_book():

    book_id = input("Enter Book ID: ")

    book_name = input("Enter Book Name: ")

    book_author = input("Enter Book Author: ")

   

    book_data = {

        "Book_id": book_id,

        "Book_name": book_name,

        "Book_author": book_author

    }

   

    result = collection.insert_one(book_data)

    print("Book added with ID:", result.inserted_id)

 

def display_books():

    books = collection.find()

    print("\nBooks in the database:")

    for book in books:

        pprint.pprint(book)

 

def search_book():

    book_name = input("Enter Book Name to search: ")

    query = {"Book_name": book_name}

    book = collection.find_one(query)

    if book:

        pprint.pprint(book)

    else:

        print("Book not found")

 

def sort_books():

    sort_key = input("Enter Sort Key (Book_id, Book_name, Book_author): ")

    books = collection.find().sort(sort_key)

    print("\nSorted Books:")

    for book in books:

        pprint.pprint(book)

 

  

Q9) Write a python program to validate the URL by using regular expression.

import re

 

def validate_url(url):

    pattern = r'^(http|https)://([a-zA-Z0-9.-]+)\.([a-zA-Z]{2,6})(/[a-zA-Z0-9.-]*)*([?][a-zA-Z0-9.-]*)*$'

    if re.match(pattern, url):

        return True

    else:

        return False

 

# Test the program

url_to_validate = input("Enter a URL: ")

 

if validate_url(url_to_validate):

    print("Valid URL")

else:

    print("Invalid URL")