Snippets Collections
DECLARE
    radius NUMBER := &radius;
    area NUMBER;
BEGIN
    area := 3.14159 * radius * radius;
    DBMS_OUTPUT.PUT_LINE('Radius: ' || radius);
    DBMS_OUTPUT.PUT_LINE('Area of the circle: ' || area);
END;
/
 
vector<string> valid;
  void generate(string& s , int open,int close)
  {
    
    if(open==0 && close==0)
    {
        valid.push_back(s);
        return;
    }
    if(open>0)
    {
        s.push_back('(');
        generate(s,open-1,close);
        s.pop_back();
    }
    if(close>0 && open<close)
    {
        s.push_back(')');
        generate(s,open,close-1);
        s.pop_back();
    }
  }
package test;

import java.sql.*;

public class TesteConexao {
    public static void main(String[] args) {
        String url = "jdbc:mysql://root:VCIiGnIpVpAUCfAXxdaPSTvTvAJSNGuE@viaduct.proxy.rlwy.net:21894/railway";
        String usuario = "root";
        String senha = "VCIiGnIpVpAUCfAXxdaPSTvTvAJSNGuE";

        try (Connection conexao = DriverManager.getConnection(url, usuario, senha)) {
            String sql = "SELECT * FROM Funcionarios";
            Statement statement = conexao.createStatement();
            ResultSet resultSet = statement.executeQuery(sql);

            while (resultSet.next()) {
                int id = resultSet.getInt("idFuncionario");
                String nome = resultSet.getString("nomeFuncionario");
                String email = resultSet.getString("email");
                String senhaFuncionario = resultSet.getString("senha");
                String estadoLogin = resultSet.getString("estadoLogin");
                System.out.println("ID: " + id + ", Nome: " + nome + ", Email: " + email + ", Senha: " + senhaFuncionario + ", Estado de Login: " + estadoLogin);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

#include<bits/stdc++.h>
using namespace std;
int sum=0;
vector<int> rev(vector<int>& nums,int f,int r)
{
    if(f<=r)
    {
        swap(nums[f],nums[r]);
        rev(nums,f+1,r-1);
    }
    return nums;
}
int main()
{

    vector<int> v = {4,5,2,6,3,56,5};
    rev(v,0,6);
    for(int i=0;i<=6;++i)
    cout<<v[i]<<" ";
    
}
void f(int n)
{
    n--;
    if(n)
    f(n);
    cout<<"AYUSH"<<endl;
}

void f(int n)
{
    if(n)
    f(n-1);
    cout<<"AYUSH"<<endl;
}
-- Define the function
CREATE OR REPLACE FUNCTION PowerNN (x IN NUMBER, n IN NUMBER) 
RETURN NUMBER 
IS
   result NUMBER;
BEGIN
   result := POWER(x, n);
   RETURN result;
END;
/
-- Use the function
DECLARE
   x NUMBER := &x;  -- Base
   n NUMBER := &n;  -- Exponent
   result NUMBER;
BEGIN
   result := PowerNN(x, n);
   DBMS_OUTPUT.PUT_LINE(x || ' power ' || n || ' is ' || result);
END;
/
10) Online Medical Store ER Diagram:

                                    +-------------+
                                    |   Customer  |
                                    +-------------+
                                    | customer_id (PK)
                                    | name
                                    | email
                                    | address
                                    +-------------+
                                            |
                                            |
                                  +---------+---------+
                                  |                   |
                          +-------+-------+   +-------+-------+
                          |     Places    |   |     Product   |
                          |    Order      |   +---------------+
                          +---------------+   | product_id (PK)|
                          | order_id (PK) |   | name          |
                          | customer_id (FK)|  | price         |
                          | order_date    |   | description   |
                          | status        |   +---------------+
                          +---------------+
                                                |
                                                |
                                    +-----------+-----------+
                                    |                       |
                            +-------+-------+   +-----------+-------+
                            |   Contains    |   |    Sourced_from  |
                            +---------------+   +-------------------+
                            | order_id (FK) |   | product_id (FK)  |
                            | product_id (FK)|  | pharmacy_id (FK) |
                            | quantity      |   +-------------------+
                            +---------------+
9) Railway Reservation System ER Diagram:

                                    +-------------+
                                    |   Passenger |
                                    +-------------+
                                    | passenger_id (PK)
                                    | name
                                    | age
                                    | gender
                                    +-------------+
                                            |
                                            |
                                  +---------+---------+
                                  |                   |
                          +-------+-------+   +-------+-------+
                          |     Books     |   |    Train      |
                          |     Ticket    |   +---------------+
                          +---------------+   | train_id (PK) |
                          | ticket_id (PK)|   | name          |
                          | passenger_id (FK)| | source        |
                          | train_id (FK) |   | destination   |
                          | booking_date  |   | departure_time|
                          | status        |   | arrival_time  |
                          +---------------+   | fare          |
                                              +---------------+
8) Flipkart ER Diagram:

                                    +-------------+
                                    |   Customer  |
                                    +-------------+
                                    | customer_id (PK)
                                    | name
                                    | email
                                    | address
                                    +-------------+
                                            |
                                            |
                                  +---------+---------+
                                  |                   |
                          +-------+-------+   +-------+-------+
                          |   Places      |   |     Product   |
                          |   Order       |   +---------------+
                          +---------------+   | product_id (PK)|
                          | order_id (PK) |   | name          |
                          | customer_id (FK)|  | price         |
                          | order_date    |   | description   |
                          | status        |   +---------------+
                          +---------------+
                                                |
                                                |
                                    +-----------+-----------+
                                    |                       |
                            +-------+-------+   +-----------+-------+
                            |   Contains    |   |    Sold_by       |
                            +---------------+   +-------------------+
                            | order_id (FK) |   | product_id (FK)  |
                            | product_id (FK)|  | seller_id (FK)   |
                            | quantity      |   | quantity_sold    |
                            +---------------+   | price            |
                                                +-------------------+
7) Hotel Management System ER Diagram:

                                    +-------------+
                                    |   Guest     |
                                    +-------------+
                                    | guest_id (PK)|
                                    | name        |
                                    | email       |
                                    | address     |
                                    +-------------+
                                            |
                                            |
                                  +---------+---------+
                                  |                   |
                          +-------+-------+   +-------+-------+
                          |     Books     |   |     Room      |
                          |     Room      |   +---------------+
                          +---------------+   | room_id (PK)  |
                          | booking_id (PK)|   | type          |
                          | guest_id (FK)  |   | capacity      |
                          | room_id (FK)   |   | status        |
                          | check_in_date  |   +---------------+
                          | check_out_date |
                          +---------------+
6) Hospital Management System ER Diagram (Duplicate):

                                    +-------------+
                                    |   Patient   |
                                    +-------------+
                                    | patient_id (PK)|
                                    | name        |
                                    | dob         |
                                    | address     |
                                    +-------------+
                                            |
                                            |
                                  +---------+---------+
                                  |                   |
                          +-------+-------+   +-------+-------+
                          |    Admits     |   |    Doctor     |
                          |               |   +---------------+
                          +---------------+   | doctor_id (PK)|
                          | admit_id (PK) |   | name          |
                          | patient_id (FK)|  | specialization|
                          | doctor_id (FK)|   +---------------+
                          | admit_date    |
                          | discharge_date|
                          +---------------+
5) Hospital Management System ER Diagram:

                                    +-------------+
                                    |   Patient   |
                                    +-------------+
                                    | patient_id (PK)|
                                    | name        |
                                    | dob         |
                                    | address     |
                                    +-------------+
                                            |
                                            |
                                  +---------+---------+
                                  |                   |
                          +-------+-------+   +-------+-------+
                          |    Admits     |   |    Doctor     |
                          |               |   +---------------+
                          +---------------+   | doctor_id (PK)|
                          | admit_id (PK) |   | name          |
                          | patient_id (FK)|  | specialization|
                          | doctor_id (FK)|   +---------------+
                          | admit_date    |
                          | discharge_date|
                          +---------------+
4) Library Management System ER Diagram:
plaintext
Copy code
                                    +-------------+
                                    |    Member   |
                                    +-------------+
                                    | member_id (PK)|
                                    | name        |
                                    | email       |
                                    | address     |
                                    +-------------+
                                            |
                                            |
                                  +---------+---------+
                                  |                   |
                          +-------+-------+   +-------+-------+
                          |     Borrows   |   |    Book       |
                          |               |   +---------------+
                          +---------------+   | book_id (PK)  |
                          | borrow_id (PK)|   | title         |
                          | member_id (FK)|   | author        |
                          | book_id (FK)  |   | available     |
                          | borrow_date   |   +---------------+
                          | return_date   |
                          +---------------+
3) Online Auction System ER Diagram:

                                    +-------------+
                                    |    User     |
                                    +-------------+
                                    | user_id (PK)|
                                    | username    |
                                    | email       |
                                    | address     |
                                    +-------------+
                                            |
                                            |
                                  +---------+---------+
                                  |                   |
                          +-------+-------+   +-------+-------+
                          |    Places     |   |     Item      |
                          |   Bid         |   +---------------+
                          +---------------+   | item_id (PK)  |
                          | bid_id (PK)   |   | name          |
                          | user_id (FK)  |   | description   |
                          | item_id (FK)  |   | starting_price|
                          | amount        |   | current_price |
                          +---------------+   +---------------+
2) Online Banking System ER Diagram:

                                    +-------------+
                                    |   Customer  |
                                    +-------------+
                                    | customer_id (PK)
                                    | name
                                    | email
                                    | address
                                    +-------------+
                                            |
                                            |
                                  +---------+---------+
                                  |                   |
                          +-------+-------+   +-------+-------+
                          |   Owns Account |   |    Account    |
                          |               |   +---------------+
                          +---------------+   | account_id (PK)|
                          | account_id (PK)|   | balance       |
                          | customer_id (FK)|  | type          |
                          | balance        |   | status        |
                          +---------------+   +---------------+
                                                |
                                                |
                                    +-----------+-----------+
                                    |                       |
                            +-------+-------+   +-----------+-------+
                            |   Performs    |   |    Transaction    |
                            +---------------+   +-------------------+
                            | transaction_id(PK)| transaction_id (PK)|
                            | account_id (FK)|   | account_id (FK)   |
                            | date          |   | type              |
                            | amount        |   | amount            |
                            +---------------+   +-------------------+
                                    +-------------+
                                    |   Customer  |
                                    +-------------+
                                    | customer_id (PK)
                                    | name
                                    | email
                                    | address
                                    +-------------+
                                            |
                                            |
                                  +---------+---------+
                                  |                   |
                          +-------+-------+   +-------+-------+
                          |     Places    |   |     Book      |
                          |    Order      |   +---------------+
                          +---------------+   | book_id (PK)  |
                          | order_id (PK) |   | title         |
                          | customer_id (FK)|  | author        |
                          | order_date    |   | price         |
                          | status        |   | publication_date|
                          +---------------+   | genre         |
                                              +---------------+
                                                |
                                                |
                                    +-----------+-----------+
                                    |                       |
                            +-------+-------+   +-----------+-------+
                            |   Contains    |   |    Written_by    |
                            +---------------+   +------------------+
                            | order_id (FK) |   | author_id (PK)   |
                            | book_id (FK)  |   | name             |
                            | quantity      |   | country          |
                            +---------------+   +------------------+
1. PL/SQL Program to demonstrate Strings:
DECLARE
    str1 VARCHAR2(50) := 'Hello';
    str2 VARCHAR2(50) := 'World';
    concatenated_str VARCHAR2(100);
BEGIN
    -- Concatenation
    concatenated_str := str1 || ' ' || str2;
    DBMS_OUTPUT.PUT_LINE('Concatenated String: ' || concatenated_str);

    -- Length
    DBMS_OUTPUT.PUT_LINE('Length of str1: ' || LENGTH(str1));

    -- Substring
    DBMS_OUTPUT.PUT_LINE('Substring of concatenated_str: ' || SUBSTR(concatenated_str, 4, 5));

    -- Uppercase
    DBMS_OUTPUT.PUT_LINE('Uppercase of str1: ' || UPPER(str1));

    -- Lowercase
    DBMS_OUTPUT.PUT_LINE('Lowercase of str2: ' || LOWER(str2));
END;

2. DML Commands:
//INSERT: Adds new records to a table.
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);
//UPDATE: Modifies existing records in a table.
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
//DELETE: Removes existing records from a table.
DELETE FROM table_name
WHERE condition;
//SELECT: Retrieves data from one or more tables.
SELECT column1, column2, ...
FROM table_name
WHERE condition;

3. Solutions for the provided relations and queries:

-- i. Create the given relations and insert at least 5 records into each relation
CREATE TABLE Employees (
    EmployeeID NUMBER PRIMARY KEY,
    FirstName VARCHAR2(50),
    LastName VARCHAR2(50),
    ProjectID NUMBER,
    Salary NUMBER,
    CONSTRAINT fk_projects FOREIGN KEY (ProjectID) REFERENCES Projects(ProjectID)
);

CREATE TABLE Projects (
    ProjectID NUMBER PRIMARY KEY,
    ProjectName VARCHAR2(50),
    StartDate DATE,
    EndDate DATE,
    ManagerID NUMBER,
    CONSTRAINT fk_employees FOREIGN KEY (ManagerID) REFERENCES Employees(EmployeeID)
);

-- ii. Find projects managed by employees in a specific department. (using nested queries)
SELECT * 
FROM Projects 
WHERE ManagerID IN (
    SELECT EmployeeID 
    FROM Employees 
    WHERE DepartmentID = 'specific_department_id'
);

-- iii. Find projects where the manager's salary is higher than the overall average salary.
SELECT * 
FROM Projects 
WHERE ManagerID IN (
    SELECT EmployeeID 
    FROM Employees 
    WHERE Salary > (SELECT AVG(Salary) FROM Employees)
);

-- iv. List all employees their names concatenating both FirstName & LastName
SELECT EmployeeID, FirstName || ' ' || LastName AS FullName
FROM Employees;

-- v. List employee First names contains at least 5 characters.
SELECT * 
FROM Employees 
WHERE LENGTH(FirstName) >= 5;

-- vi. Reallocate to another project whose salary is greater than 20K.
UPDATE Employees 
SET ProjectID = 'new_project_id' 
WHERE Salary > 20000;
1. PL/SQL Program to find if a given number is even or odd:
DECLARE
    num NUMBER := 10; -- Change the number here
BEGIN
    IF MOD(num, 2) = 0 THEN
        DBMS_OUTPUT.PUT_LINE(num || ' is even');
    ELSE
        DBMS_OUTPUT.PUT_LINE(num || ' is odd');
    END IF;
END;

2. Examples of creating a table with NULL, NOT NULL, CHECK constraints:

-- Table with NULL constraint
CREATE TABLE example_null (
    id NUMBER PRIMARY KEY,
    name VARCHAR2(50) NULL
);

-- Table with NOT NULL constraint
CREATE TABLE example_not_null (
    id NUMBER PRIMARY KEY,
    name VARCHAR2(50) NOT NULL
);

-- Table with CHECK constraint
CREATE TABLE example_check (
    id NUMBER PRIMARY KEY,
    age NUMBER CHECK (age >= 18)
);


3. Solutions for the provided relations and queries:
-- Create Employees table
CREATE TABLE Employees (
    Employee_ID NUMBER PRIMARY KEY,
    Emp_Name VARCHAR2(50),
    Skill_ID NUMBER,
    Salary NUMBER,
    CONSTRAINT fk_skills FOREIGN KEY (Skill_ID) REFERENCES Skills(SkillID)
);
-- Create Skills table
CREATE TABLE Skills (
    SkillID NUMBER PRIMARY KEY,
    SkillName VARCHAR2(50),
    Description VARCHAR2(100)
);
-- Insert sample records into Employees table
INSERT INTO Employees (Employee_ID, Emp_Name, Skill_ID, Salary) VALUES (1, 'John', 1, 5000);
INSERT INTO Employees (Employee_ID, Emp_Name, Skill_ID, Salary) VALUES (2, 'Alice', 2, 6000);
INSERT INTO Employees (Employee_ID, Emp_Name, Skill_ID, Salary) VALUES (3, 'Bob', 1, 5500);
INSERT INTO Employees (Employee_ID, Emp_Name, Skill_ID, Salary) VALUES (4, 'Emma', 3, 7000);
INSERT INTO Employees (Employee_ID, Emp_Name, Skill_ID, Salary) VALUES (5, 'Mike', NULL, 4500);

-- Insert sample records into Skills table
INSERT INTO Skills (SkillID, SkillName, Description) VALUES (1, 'Java', 'Programming language');
INSERT INTO Skills (SkillID, SkillName, Description) VALUES (2, 'SQL', 'Database querying language');
INSERT INTO Skills (SkillID, SkillName, Description) VALUES (3, 'Python', 'High-level programming language');

-- ii. Find employees who have not acquired any skills
SELECT * FROM Employees WHERE Skill_ID IS NULL;

-- iii. Find employees with the highest salary
SELECT * FROM Employees WHERE Salary = (SELECT MAX(Salary) FROM Employees);

-- iv. Find the average salary of employees in each department
-- Assuming there's a department_id column in the Employees table
SELECT department_id, AVG(Salary) AS Avg_Salary FROM Employees GROUP BY department_id;

-- v. Update the salary of an employee
UPDATE Employees SET Salary = 6000 WHERE Employee_ID = 1;

-- vi. Retrieve skills that are possessed by at least two employees
SELECT SkillID, SkillName FROM Skills WHERE SkillID IN (
    SELECT Skill_ID FROM Employees GROUP BY Skill_ID HAVING COUNT(*) >= 2
);
**Set-1:**
```
               +------------------+
               |      Nurse       |
               +------------------+
               | nurse_id (PK)    |
               | nurse_name       |
               | registered       |
               | department_id (FK)|
               +------------------+
                        |
                        |
                        | works in
                        |
                        v
               +------------------+
               |    Department    |
               +------------------+
               | department_id (PK)|
               | department_name  |
               +------------------+
```

**Set-2:**
```
               +------------------+
               |     Student      |
               +------------------+
               | student_id (PK)  |
               | student_name     |
               | course_id (FK)   |
               +------------------+
                        |
                        |
                        | enrolled in
                        |
                        v
               +------------------+
               |      Course      |
               +------------------+
               | course_id (PK)   |
               | course_name      |
               +------------------+
```

**Set-3:**
```
               +------------------+
               |    Physician     |
               +------------------+
               | physician_id (PK)|
               | physician_name   |
               | department_id (FK)|
               +------------------+
                        |
                        |
                        | works in
                        |
                        v
               +------------------+
               |    Department    |
               +------------------+
               | department_id (PK)|
               | department_name  |
               +------------------+
```

**Set-4:**
```
               +------------------+
               |     Supplier     |
               +------------------+
               | supplier_id (PK) |
               | supplier_name    |
               +------------------+
                        |
                        |
                        | supplies
                        |
                        v
               +------------------+
               |      Item        |
               +------------------+
               | item_id (PK)     |
               | item_name        |
               | supplier_id (FK) |
               +------------------+
```

**Set-5:**
```
               +------------------+
               |     User         |
               +------------------+
               | user_id (PK)     |
               | username         |
               +------------------+
                        |
                        |
                        | makes order
                        |
                        v
               +------------------+
               |     Order        |
               +------------------+
               | order_id (PK)    |
               | user_id (FK)     |
               +------------------+
```

**Set-6:**
```
               +------------------+
               |     Supplier     |
               +------------------+
               | supplier_id (PK) |
               | supplier_name    |
               +------------------+
                        |
                        |
                        | supplies
                        |
                        v
               +------------------+
               |      Item        |
               +------------------+
               | item_id (PK)     |
               | item_name        |
               | supplier_id (FK) |
               +------------------+
```

**Set-7:**
```
               +------------------+
               |     Student      |
               +------------------+
               | student_id (PK)  |
               | student_name     |
               | course_id (FK)   |
               +------------------+
                        |
                        |
                        | enrolled in
                        |
                        v
               +------------------+
               |      Course      |
               +------------------+
               | course_id (PK)   |
               | course_name      |
               +------------------+
```

**Set-8:**
```
               +------------------+
               |     Supplier     |
               +------------------+
               | supplier_id (PK) |
               | supplier_name    |
               +------------------+
                        |
                        |
                        | supplies
                        |
                        v
               +------------------+
               |      Item        |
               +------------------+
               | item_id (PK)     |
               | item_name        |
               | supplier_id (FK) |
               +------------------+
```

**Set-9:**
```
               +------------------+
               |     Employee     |
               +------------------+
               | emp_id (PK)      |
               | emp_name         |
               | job              |
               | hiredate         |
               | sal              |
               | comm             |
               | dept_no (FK)     |
               +------------------+
                        |
                        |
                        | works in
                        |
                        v
               +------------------+
               |    Department    |
               +------------------+
               | dept_no (PK)     |
               | dept_name        |
               | location         |
               +------------------+
```

**Set-10:**
```
               +------------------+
               |     Employee     |
               +------------------+
               | emp_no (PK)      |
               | emp_name         |
               | job              |
               | hiredate         |
               | sal              |
               | comm             |
              


/////SET-10
                                        +--------------+
                                        |   Customer   |
                                        +--------------+
                                        | customer_id (PK)
                                        | name
                                        | email
                                        | address
                                        +--------------+
                                                |
                                                |
                                    +-----------+-----------+
                                    |                       |
                        +-----------+-----------+   +-------+-------+
                        |      Makes Purchase     |   |   Manages    |
                        |    +--------------+    |   |    Payment   |
                        +----|     Order    |<---+   +-------+-------+
                             +--------------+            |    
                             | order_id (PK)             |    
                             | customer_id (FK)          |    
                             | order_date                |
                             +--------------+            |
                                                 +--------+---------+
                                                 |                  |
                                       +---------+---------+   +----v----+
                                       |     Contains     |   | Payment |
                                       +-----------------+   +---------+
                                       | order_id (FK)  |   
                                       | product_id (FK)|
                                       | quantity        |
                                       +-----------------+
                                                      
                           +-------------+             +----------------+
                           |   Product   |             |    Pharmacy    |
                           +-------------+             +----------------+
                           | product_id (PK)|         | pharmacy_id (PK)|
                           | name          |         | name           |
                           | price         |         | location       |
                           | manufacturer_id (FK)|    +----------------+
                           +-------------+    
                                   |
                                   |
                           +-------+--------+
                           |  Manufactures  |
                           +----------------+
                           | manufacturer_id (PK)|
                           | name               |
                           | country            |
                           +-------------------+
A. List the details of the employees in ascending order of the Department numbers and descending order of Jobs:
SELECT *
FROM emp_details
ORDER BY dept_no ASC, job DESC;

B. Query for adding a new column called PF:
ALTER TABLE emp_details ADD PF NUMBER;

C. List the employees who joined before 1981:
SELECT *
FROM emp_details
WHERE hiredate < TO_DATE('1981-01-01', 'YYYY-MM-DD');
D. Display employees whose salary is between 10,000 and 20,000:
SELECT *
FROM emp_details
WHERE sal BETWEEN 10000 AND 20000;

E. Display employees whose name starts with 'S':
SELECT *
FROM emp_details
WHERE emp_name LIKE 'S%';

F. Display employees who were born between January 1st, 1970, and January 1st, 1990:
SELECT *
FROM emp_details
WHERE EXTRACT(YEAR FROM hiredate) BETWEEN 1970 AND 1990;
G. Syntax of DDL Commands:
//CREATE: Used to create a new database object like a table, view, or index.
CREATE TABLE table_name (column1 datatype, column2 datatype, ...);
//ALTER: Used to modify an existing database object like adding, modifying, or dropping columns.
ALTER TABLE table_name ADD column_name datatype;
//DROP: Used to delete an existing database object like a table, view, or index.
DROP TABLE table_name;
H. PL/SQL Program to find the maximum number among three numbers:
DECLARE
    num1 NUMBER := 10;
    num2 NUMBER := 20;
    num3 NUMBER := 30;
    max_num NUMBER;
BEGIN
    max_num := GREATEST(num1, num2, num3);
    DBMS_OUTPUT.PUT_LINE('Maximum number: ' || max_num);
END;

I. PL/SQL Program to print the salary changes when the salary is changed using a Trigger:
CREATE OR REPLACE TRIGGER salary_change_trigger
BEFORE UPDATE OF sal ON emp_details
FOR EACH ROW
BEGIN
    DBMS_OUTPUT.PUT_LINE('Old Salary: ' || :OLD.sal);
    DBMS_OUTPUT.PUT_LINE('New Salary: ' || :NEW.sal);
END;

J. Find the maximum average salary drawn for each job except for 'President':
SELECT job, MAX(AVG(sal)) AS max_avg_salary
FROM emp_details
WHERE job != 'President'
GROUP BY job;

Entities:

Employee (emp_no, emp_name, job, hiredate, mgr, sal, comm, dept_no)
Department (dept_no, dept_name, location)
Relationships:

Employee works in Department (many-to-one)
Employee (mgr) manages other Employees (one-to-many)

            +------------------+
            |     Employee     |
            +------------------+
            | emp_no (PK)      |
            | emp_name         |
            | job              |
            | hiredate         |
            | sal              |
            | comm             |
            | dept_no (FK)     |
            +------------------+
                    |
                    |
                    | works in
                    |
                    v
            +------------------+
            |   Department     |
            +------------------+
            | dept_no (PK)     |
            | dept_name        |
            | location         |
            +------------------+
1. Retrieve all the names and their respective salaries:
SELECT Emp_Name, Salary FROM Employee;

2. Retrieve the names of employees whose salary is greater than 5000:
SELECT Emp_Name FROM Employee WHERE Salary > 5000;
3. Display the names and locations of all departments:
SELECT Dname, Location FROM Department;

4. Display the names of employees who work in the sales department:
SELECT e.Emp_Name 
FROM Employee e 
JOIN Department d ON e.Dept_no = d.Dept_No 
WHERE d.Dname = 'Sales';

5. Display the total number of employees in each department:
SELECT d.Dname, COUNT(e.Emp_id) AS Total_Employees
FROM Department d
LEFT JOIN Employee e ON d.Dept_No = e.Dept_no
GROUP BY d.Dname;

6. Update the salary of employee with empid 3 to 8000:
UPDATE Employee SET Salary = 8000 WHERE Emp_id = 3;

7. Delete the employee with empid=4:
DELETE FROM Employee WHERE Emp_id = 4;

8. Display the highest salary in each department:
SELECT d.Dname, MAX(e.Salary) AS Highest_Salary
FROM Department d
LEFT JOIN Employee e ON d.Dept_No = e.Dept_no
GROUP BY d.Dname;

9. Create a view to list the employees in ascending order of their Salaries:
CREATE VIEW Employee_Salary_View AS
SELECT * FROM Employee ORDER BY Salary ASC;

10. Create a trigger before insert on emp table to make salary zero if less than zero:
CREATE OR REPLACE TRIGGER check_salary
BEFORE INSERT ON Employee
FOR EACH ROW
BEGIN
    IF :NEW.Salary < 0 THEN
        :NEW.Salary := 0;
    END IF;
END;

11. Aggregate Functions:
//SUM: Calculates the sum of values in a column.
SELECT SUM(Salary) FROM Employee;
//AVG: Calculates the average of values in a column.
SELECT AVG(Salary) FROM Employee;
//COUNT: Counts the number of rows in a result set or the number of non-null values in a column.
SELECT COUNT(*) FROM Employee;
//MAX: Returns the maximum value in a column.
SELECT MAX(Salary) FROM Employee;
//MIN: Returns the minimum value in a column.
SELECT MIN(Salary) FROM Employee;

12. E-R Diagram for Mobile Billing System:
Entities:

Customer (Customer_ID, Name, Address, Phone_Number)
Billing Details (Bill_ID, Customer_ID, Bill_Amount, Bill_Date)
Plan Details (Plan_ID, Plan_Name, Plan_Type, Monthly_Price)
Cities of Service (City_ID, City_Name, Service_Area)
Relationships:

Customer makes Billing Details (one-to-many)
Customer subscribes to Plan (many-to-one)
Plan is available in Cities of Service (many-to-many)
1) ER Diagram for Online Medical Store:
Entities: User, Product, Order, Prescription, Pharmacy, Payment, Review
Relationships:

User places Order (one-to-many)
Order contains Product (many-to-many)
Prescription is related to User (many-to-one)
Product is sold by Pharmacy (many-to-one)
Payment is related to Order (one-to-one)
User writes Review for Product (one-to-many)

2) Trigger to Update Project Budget When Employee Salary is Increased:

CREATE OR REPLACE TRIGGER update_project_budget
AFTER UPDATE OF salary ON Employees
FOR EACH ROW
BEGIN
    UPDATE Projects
    SET budget = budget + (:new.salary - :old.salary)
    WHERE manager_id = :new.employee_id;
END;


3) SQL Queries:
A)
SELECT Department, MAX(Budget) AS Highest_Budget
FROM Projects
GROUP BY Department;
B)
SELECT SUM(Budget) AS Total_Budget FROM Projects;
C)
CREATE VIEW HighSalaryEmployees AS
SELECT * FROM Employees WHERE Salary > 80000;
D)
SELECT * FROM Employees WHERE Salary BETWEEN 60000 AND 80000;
E)
DELETE FROM Employees WHERE Salary < 60000;
F)
SELECT * FROM Projects WHERE Budget > (SELECT AVG(Budget) FROM Projects);
G)
SELECT * FROM Projects WHERE ProjectName LIKE 'Web%' ORDER BY Budget;
H)
SELECT Department, SUM(Budget) AS Total_Budget
FROM Projects
GROUP BY Department
ORDER BY Total_Budget;
1) ER Diagram for Railway Reservation System:
Entities: Train, Passenger, Ticket, Route, Station, Reservation, Payment
Relationships:

Passenger books Ticket (one-to-many)
Ticket is for Train (many-to-one)
Ticket is for Passenger (many-to-one)
Train travels on Route (many-to-many)
Route includes Station (one-to-many)
Reservation is related to Ticket (one-to-one)
Payment is related to Ticket (one-to-one)

2) PL/SQL Program to Calculate Sum of Digits of any Number:

CREATE OR REPLACE PROCEDURE calculate_digit_sum(
    num IN NUMBER,
    sum OUT NUMBER
) AS
    total_sum NUMBER := 0;
BEGIN
    WHILE num != 0 LOOP
        total_sum := total_sum + MOD(num, 10);
        num := num / 10;
    END LOOP;
    sum := total_sum;
END;


3) SQL Queries:
A
SELECT * FROM Employees WHERE Department = 'IT';
B)
UPDATE Employees SET Salary = NEW_SALARY WHERE EmployeeID = 3;
C)
SELECT * FROM Employees WHERE Salary > (SELECT AVG(Salary) FROM Employees);
D)
SELECT * FROM Employees WHERE Department = 'IT' AND Salary > 70000;
E)
SELECT SUM(Budget) AS Total_Budget FROM Projects WHERE Department = 'Marketing';
F)
SELECT * FROM Employees WHERE Salary = (SELECT MAX(Salary) FROM Employees);
G)
SELECT E.EmployeeID, E.EmployeeName, P.ProjectName
FROM Employees E
JOIN Project_Assignment PA ON E.EmployeeID = PA.EmployeeID
JOIN Projects P ON PA.ProjectID = P.ProjectID;
H)
SELECT Department, COUNT(EmployeeID) AS Total_Employees
FROM Employees
GROUP BY Department;
1) ER Diagram for Flipkart:
Entities: User, Product, Order, Payment, Cart, Review
Relationships:

User places Order (one-to-many)
User adds Product to Cart (one-to-many)
Order contains Product (many-to-many)
Payment is related to Order (one-to-one)
User writes Review for Product (one-to-many)


2) Trigger to Update Instructor's Name in Courses Table:

CREATE OR REPLACE TRIGGER update_instructor_name
AFTER UPDATE OF instructor_name ON Students
FOR EACH ROW
BEGIN
    UPDATE Courses
    SET instructor_name = :new.instructor_name
    WHERE instructor_id = :new.student_id;
END;


3) SQL Queries:
A)
ALTER TABLE Students
ADD Email VARCHAR2(100);
B)
UPDATE Students
SET Email = 'example@email.com'
WHERE StudentID = 12345;
C)
SELECT CourseID, CourseName
FROM Courses
WHERE CourseID IN (
    SELECT CourseID
    FROM Enrollments
    WHERE StudentID IN (
        SELECT StudentID
        FROM Students
        WHERE GPA < 2.5
    )
);
D)
SELECT CourseID, CourseName
FROM Courses
WHERE CreditHours > (
    SELECT AVG(CreditHours)
    FROM Courses
);
E)
SELECT *
FROM Students
WHERE LastName LIKE '%son';
F)
SELECT BirthDate, COUNT(*)
FROM Students
GROUP BY BirthDate;
G)
SELECT BirthDate
FROM Students
GROUP BY BirthDate
HAVING COUNT(*) > 1;
H)
UPDATE Courses
SET Instructor = 'New Instructor'
WHERE CourseID = 'SpecificCourseID';
1.ER Diagram for Online Food Order System:
Entities: Customer, Restaurant, Order, Food Item, Delivery, Payment, Review
Relationships:

Customer places Order (one-to-many)
Order contains Food Item (many-to-many)
Order is delivered by Delivery (one-to-one)
Payment is related to Order (one-to-one)
Customer writes Review for Restaurant (one-to-many)


2.PL/SQL Procedure to Calculate Square of a Number:

CREATE OR REPLACE PROCEDURE calculate_square(
    num IN NUMBER,
    square OUT NUMBER
) AS
BEGIN
    square := num * num;
END;


3.SQL Queries:
A)
SELECT supplier_number, supplier_name 
FROM Suppliers 
WHERE supplier_name LIKE 'R%';
B)
SELECT supplier_name 
FROM Suppliers 
WHERE item_supplied = 'Processor' AND city = 'Delhi';
C)
SELECT DISTINCT S.supplier_name 
FROM Suppliers S 
JOIN Suppliers R ON S.item_supplied = R.item_supplied 
WHERE R.supplier_name = 'Ramesh';
D)
UPDATE Items 
SET item_price = item_price + 200 
WHERE item_name = 'Keyboard';
E)
SELECT supplier_number, supplier_name, item_price 
FROM Suppliers 
WHERE city = 'Delhi' 
ORDER BY item_price ASC;
F)
ALTER TABLE Suppliers 
ADD contact_no VARCHAR2(20);
G)
DELETE FROM Items 
WHERE item_price = (SELECT MIN(item_price) FROM Items);
H)
CREATE VIEW SupplierDetails AS
SELECT supplier_number, supplier_name 
FROM Suppliers;
1) ER Diagram for Online Food Order System:

Entities: Customer, Restaurant, Order, Food Item, Delivery, Payment, Review
Relationships:
Customer places Order (one-to-many)
Order contains Food Item (many-to-many)
Order is delivered by Delivery (one-to-one)
Payment is related to Order (one-to-one)
Customer writes Review for Restaurant (one-to-many)

2) PL/SQL Procedure to Calculate Square of a Number:

CREATE OR REPLACE PROCEDURE calculate_square(
    num IN NUMBER,
    square OUT NUMBER
) AS
BEGIN
    square := num * num;
END;
3) SQL Queries:
A) SELECT supplier_number, supplier_name FROM Suppliers WHERE supplier_name LIKE 'R%';
B)
SELECT supplier_name 
FROM Suppliers 
WHERE item_supplied = 'Processor' AND city = 'Delhi';
C)
SELECT DISTINCT S.supplier_name 
FROM Suppliers S 
JOIN Suppliers R ON S.item_supplied = R.item_supplied 
WHERE R.supplier_name = 'Ramesh';
D) UPDATE Items SET item_price = item_price + 200 WHERE item_name = 'Keyboard';
E)
SELECT supplier_number, supplier_name, item_price 
FROM Suppliers 
WHERE city = 'Delhi' 
ORDER BY item_price ASC;
F) ALTER TABLE Suppliers ADD contact_no VARCHAR2(20);
G)
DELETE FROM Items 
WHERE item_price = (SELECT MIN(item_price) FROM Items);
H)
CREATE VIEW SupplierDetails AS
SELECT supplier_number, supplier_name 
FROM Suppliers;
1) ER Diagram for Hospital Management System:

Entities: Patient, Doctor, Nurse, Department, Appointment, Prescription, Procedure
Relationships:
Doctor treats Patient (many-to-many)
Nurse cares for Patient (many-to-many)
Department employs Doctor/Nurse (one-to-many)
Appointment scheduled between Doctor and Patient (one-to-many)


2) PL/SQL Function Program to Use IN, OUT:

//CREATE OR REPLACE FUNCTION 
CREATE OR REPLACE FUNCTION calculate_area_length_width(
    length_val IN NUMBER,
    width_val IN NUMBER,
    area_val OUT NUMBER
) RETURN NUMBER
IS
BEGIN
    area_val := length_val * width_val;
    RETURN area_val;
END;
/

3) SQL Queries:
A)
DESCRIBE nurse;
DESCRIBE physician;
B) SELECT name FROM physician WHERE position = 'Senior Attending';
C) SELECT name FROM physician WHERE department_id IS NULL;
D) SELECT name FROM physician WHERE position LIKE 'Surgical%';
E)
SELECT P.name 
FROM physician P 
JOIN nurse N ON P.position = N.position 
WHERE N.name = 'Carla Espinosa';
F) ALTER TABLE physician MODIFY ssn VARCHAR2(20);
G) DELETE FROM department WHERE departmentid = 1;
H)
CREATE VIEW AttendingPhysicians AS
SELECT name, ssn 
FROM physician 
WHERE position = 'Attending Physician';
1) ER Diagram for Library Management System:

Entities: Book, Author, Publisher, Member, Loan, Reservation, Genre
Relationships:
Member borrows Book (many-to-many)
Book is written by Author (many-to-many)
Book is published by Publisher (many-to-one)
Reservation is placed by Member (one-to-many)

2) PL/SQL Function to Calculate Area of Rectangle:
CREATE OR REPLACE FUNCTION calculate_rectangle_area(
    length IN NUMBER,
    width IN NUMBER
) RETURN NUMBER IS
    area NUMBER;
BEGIN
    area := length * width;
    RETURN area;
END;

3) SQL Queries:
A) SELECT * FROM Employees;
B) SELECT salary FROM Employees;
C) SELECT DISTINCT designation FROM Employees;
D) SELECT emp_name, salary * 1.15 AS increased_salary FROM Employees;
E) SELECT emp_id, salary, dept_id FROM Employees;
F) SELECT * FROM Employees WHERE YEAR(join_date) < 1991;
G) SELECT AVG(salary) AS average_salary FROM Employees WHERE designation = 'ANALYST';
H)CREATE VIEW EmployeesWithThirdLetterA AS
  SELECT * FROM Employees 
  WHERE SUBSTRING(name, 3, 1) = 'A' AND salary BETWEEN 2600 AND 3200;
1) ER Diagram for Online Auction System:

Entities: User, Item, Bid, Auction, Payment, Category
Relationships:
User places Bid (one-to-many)
Item is listed in Auction (many-to-one)
User makes Payment (one-to-one)
Item belongs to Category (many-to-many)

2) PL/SQL Program to Find Area of Circle:

CREATE OR REPLACE PROCEDURE calculate_circle_area(
    radius IN NUMBER,
    area OUT NUMBER
) AS
BEGIN
    area := 3.14 * radius * radius;
END;


3) SQL Queries:
a) UPDATE Physicians SET position = 'Senior Staff Internist' WHERE name = 'John Dorian';

b) CREATE VIEW NonInternPhysicians AS SELECT name, position FROM Physicians WHERE position <> 'Intern';

c) SELECT * FROM Physicians WHERE position = 'Attending Physician';

d) SELECT P.name AS physician_name, D.name AS department_name FROM Physicians P JOIN Departments D ON P.department_id = D.id;

e) SELECT name FROM Physicians WHERE position LIKE '%Physician%';

f) SELECT N.name FROM Nurses N JOIN Departments D ON N.department_id = D.id WHERE N.registered = 'Y' AND D.name = 'Surgery';

g) SELECT D.name AS department_name, COUNT(*) AS total_physicians FROM Physicians P JOIN Departments D ON P.department_id = D.id GROUP BY D.name;
                                           
h) DELETE FROM Nurses WHERE registered = 'N';
SET-2

ER Diagram for Online Banking:

Entities: Customer, Account, Transaction, Bank, Branch, Loan
Relationships:
Customer owns Account (one-to-many)
Account has Transaction (one-to-many)
Bank has Branches (one-to-many)
Customer takes Loan (one-to-many)

2.PL/SQL Procedure with OUT Parameter to Calculate Square and Cube:
CREATE OR REPLACE PROCEDURE calculate_square_cube(
    num IN NUMBER,
    square OUT NUMBER,
    cube OUT NUMBER
) AS
BEGIN
    square := num * num;
    cube := num * num * num;
END;

3.SQL Queries:
A. SELECT * FROM Students WHERE state NOT IN ('Telangana', 'AndhraPradesh');

B. CREATE VIEW TelanganaStudents AS SELECT Sid, Sname FROM Students WHERE state = 'Telangana';

C. SELECT * FROM Students WHERE gender = 'female' AND course = 'Compcourse' AND category = 'OBC';

D. SELECT Sid, Sname, (marks_obtained / total_marks) * 100 AS percentage FROM Results;

E. SELECT * FROM Students ORDER BY Sname, course ASC;

F. DELETE FROM Students WHERE course = 'Compcourse' AND YEAROFBIRTH > 2002;

G. ALTER TABLE Students MODIFY (state VARCHAR2(40));

H. SELECT Sname FROM Students WHERE LENGTH(Sname) = 5;
SET-1

1.ER Diagram for Online Book Store:

	Entities: User, Book, Author, Publisher, Order, Payment, Review
	Relationships:
	User buys Book (one-to-many)
	Book is written by Author (many-to-many)
	Book is published by Publisher (many-to-one)
	Order contains Book (one-to-many)
	Payment is related to Order (one-to-one)
	User writes Review for Book (one-to-many)
2.PL/SQL Function to Calculate Factorial:


CREATE OR REPLACE FUNCTION factorial(n IN NUMBER) RETURN NUMBER IS
    result NUMBER := 1;
BEGIN
    FOR i IN 1..n LOOP
        result := result * i;
    END LOOP;
    RETURN result;
END;
3.SQL Queries:
A. SELECT * FROM Nurses WHERE registered = 'Y';

B. ALTER TABLE Nurses ADD phone VARCHAR2(20);

C. UPDATE Nurses SET registered = 'N' WHERE name = 'Laverne Roberts';

D. CREATE VIEW NursePositions AS SELECT name, position FROM Nurses;

E. SELECT name, position FROM Nurses UNION ALL SELECT name, position FROM Physicians;

F. SELECT D.name AS department_name, E.name AS department_head FROM Departments D JOIN Employees E ON D.head_id = E.id;

G. SELECT N.name AS nurse_name, D.name AS department_name FROM Nurses N JOIN Departments D ON N.department_id = D.id;

H. DELETE FROM Departments WHERE id = 2;
class ArrayStack<T> {
    private T[] stackArray;
    private int top;
    private int maxSize;

    @SuppressWarnings("unchecked")
    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        this.stackArray = (T[]) new Object[maxSize];
        this.top = -1;
    }

    public void push(T item) {
        if (isFull()) {
            System.out.println("Stack overflow");
            return;
        }
        stackArray[++top] = item;
    }

    public T pop() {
        if (isEmpty()) {
            System.out.println("Stack underflow");
            return null;
        }
        return stackArray[top--];
    }

    public T peek() {
        if (isEmpty()) {
            System.out.println("Stack is empty");
            return null;
        }
        return stackArray[top];
    }

    public boolean isEmpty() {
        return top == -1;
    }

    public boolean isFull() {
        return top == maxSize - 1;
    }
}

public class GenericStackDemo {
    public static void main(String[] args) {
        // Using ArrayStack
        ArrayStack<Integer> integerStack = new ArrayStack<>(5);
        integerStack.push(10);
        integerStack.push(20);
        System.out.println("Popped integer: " + integerStack.pop());
        System.out.println("Peek integer: " + integerStack.peek());

        ArrayStack<Double> doubleStack = new ArrayStack<>(5);
        doubleStack.push(3.14);
        doubleStack.push(6.28);
        System.out.println("Popped double: " + doubleStack.pop());
        System.out.println("Peek double: " + doubleStack.peek());

        ArrayStack<String> stringStack = new ArrayStack<>(5);
        stringStack.push("Hello");
        stringStack.push("World");
        System.out.println("Popped string: " + stringStack.pop());
        System.out.println("Peek string: " + stringStack.peek());
    }
}
 import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

class Product {
    private int id;
    private String name;
    private double price;
    private String type;
    private double rating;

    public Product(int id, String name, double price, String type, double rating) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.type = type;
        this.rating = rating;
    }

    public double getRating() {
        return rating;
    }

    public double getPrice() {
        return price;
    }

    public String getType() {
        return type;
    }

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", type='" + type + '\'' +
                ", rating=" + rating +
                '}';
    }
}

public class ProductStreamExample {
    public static void main(String[] args) {
        List<Product> products = Arrays.asList(
                new Product(1, "Laptop", 1500.0, "Electronics", 4.5),
                new Product(2, "Smartphone", 800.0, "Electronics", 4.2),
                new Product(3, "Watch", 300.0, "Fashion", 3.8),
                new Product(4, "Headphones", 100.0, "Electronics", 4.8),
                new Product(5, "Shoes", 50.0, "Fashion", 3.5),
                new Product(6, "Camera", 2000.0, "Electronics", 4.7)
        );

        // i) Find all the products having rating between 4 and 5
        List<Product> productsRatingBetween4And5 = products.stream()
                .filter(p -> p.getRating() >= 4 && p.getRating() <= 5)
                .collect(Collectors.toList());
        System.out.println("Products with rating between 4 and 5: " + productsRatingBetween4And5);
		System.out.println();
        
        // ii) Find first n products having price > 10000
        int n = 2;
        List<Product> firstNProductsPriceGreaterThan1000 = products.stream()
                .filter(p -> p.getPrice() > 1000)
                .limit(n)
                .collect(Collectors.toList());
        System.out.println("First " + n + " products with price > 1000: " + firstNProductsPriceGreaterThan1000);
		System.out.println();
        
        // iii) Find the number of products under each type (map containing type and count)
        Map<String, Long> productCountByType = products.stream()
		.collect(Collectors.groupingBy(Product::getType, Collectors.counting()));
        System.out.println("Number of products under each type: " + productCountByType);
		System.out.println();
        
        // iv) Find average rating of products with type = "Electronics"
        double averageRatingElectronics = products.stream()
                .filter(p -> p.getType().equals("Electronics"))
                .mapToDouble(Product::getRating)
                .average()
                .orElse(0.0);
        System.out.println("Average rating of products with type 'Electronics': " + averageRatingElectronics);
    }
}
#include<bits/stdc++.h>
using namespace std;
const int N = 1e3+5;
vector<int> graph[N];
bool visited[N];
void dfs(int vertex)
{
  visited[vertex]=true;
  for(int child:graph[vertex])
    {
      
      if(visited[child])
        continue;
      dfs(child);
    }
}
int main()
{
    int v,e,j,k;
    cin>>v>>e;
    for(int i=0;i<v;++i)
    {
        cin>>j>>k;
        graph[k].push_back(j);
        graph[j].push_back(k);
        
    }
}
class AVLNode<T extends Comparable<T>> {
    T data;
    AVLNode<T> left, right;
    int height;

    public AVLNode(T data) {
        this.data = data;
        this.height = 1; // New node initially has height 1
    }
}

public class AVLTree<T extends Comparable<T>> {
    private AVLNode<T> root;

    public AVLTree() {
        this.root = null;
    }

    // Get height of node
    private int height(AVLNode<T> node) {
        return node == null ? 0 : node.height;
    }

    // Right rotation
    private AVLNode<T> rotateRight(AVLNode<T> y) {
        AVLNode<T> x = y.left;
        AVLNode<T> T2 = x.right;

        x.right = y;
        y.left = T2;

        y.height = Math.max(height(y.left), height(y.right)) + 1;
        x.height = Math.max(height(x.left), height(x.right)) + 1;

        return x;
    }

    // Left rotation
    private AVLNode<T> rotateLeft(AVLNode<T> x) {
        AVLNode<T> y = x.right;
        AVLNode<T> T2 = y.left;

        y.left = x;
        x.right = T2;

        x.height = Math.max(height(x.left), height(x.right)) + 1;
        y.height = Math.max(height(y.left), height(y.right)) + 1;

        return y;
    }

    // Balance factor of a node
    private int getBalance(AVLNode<T> node) {
        return node == null ? 0 : height(node.left) - height(node.right);
    }

    // Insert operation
    public void insert(T data) {
        root = insertRec(root, data);
    }

    private AVLNode<T> insertRec(AVLNode<T> node, T data) {
        if (node == null) {
            return new AVLNode<>(data);
        }

        if (data.compareTo(node.data) < 0) {
            node.left = insertRec(node.left, data);
        } else if (data.compareTo(node.data) > 0) {
            node.right = insertRec(node.right, data);
        } else {
            return node;
        }

        node.height = Math.max(height(node.left), height(node.right)) + 1;

        int balance = getBalance(node);

        if (balance > 1 && data.compareTo(node.left.data) < 0) {
            return rotateRight(node);
        }

        if (balance < -1 && data.compareTo(node.right.data) > 0) {
            return rotateLeft(node);
        }

        if (balance > 1 && data.compareTo(node.left.data) > 0) {
            node.left = rotateLeft(node.left);
            return rotateRight(node);
        }

        if (balance < -1 && data.compareTo(node.right.data) < 0) {
            node.right = rotateRight(node.right);
            return rotateLeft(node);
        }

        return node;
    }

    // Search operation
    public boolean search(T data) {
        return searchRec(root, data) != null;
    }

    private AVLNode<T> searchRec(AVLNode<T> node, T data) {
        if (node == null || node.data.equals(data)) {
            return node;
        }

        if (data.compareTo(node.data) < 0) {
            return searchRec(node.left, data);
        } else {
            return searchRec(node.right, data);
        }
    }

    // In-order traversal
    public void inOrder() {
        inOrderRec(root);
    }

    private void inOrderRec(AVLNode<T> node) {
        if (node != null) {
            inOrderRec(node.left);
            System.out.print(node.data + " ");
            inOrderRec(node.right);
        }
    }

    // Delete operation
    public void delete(T data) {
        root = deleteRec(root, data);
    }

    private AVLNode<T> deleteRec(AVLNode<T> root, T data) {
        if (root == null) {
            return root;
        }

        if (data.compareTo(root.data) < 0) {
            root.left = deleteRec(root.left, data);
        } else if (data.compareTo(root.data) > 0) {
            root.right = deleteRec(root.right, data);
        } else {
            if ((root.left == null) || (root.right == null)) {
                AVLNode<T> temp = root.left != null ? root.left : root.right;
                if (temp == null) {
                    return null;
                } else {
                    return temp;
                }
            } else {
                AVLNode<T> temp = minValueNode(root.right);
                root.data = temp.data;
                root.right = deleteRec(root.right, temp.data);
            }
        }

        root.height = Math.max(height(root.left), height(root.right)) + 1;

        int balance = getBalance(root);

        if (balance > 1 && getBalance(root.left) >= 0) {
            return rotateRight(root);
        }

        if (balance > 1 && getBalance(root.left) < 0) {
            root.left = rotateLeft(root.left);
            return rotateRight(root);
        }

        if (balance < -1 && getBalance(root.right) <= 0) {
            return rotateLeft(root);
        }

        if (balance < -1 && getBalance(root.right) > 0) {
            root.right = rotateRight(root.right);
            return rotateLeft(root);
        }

        return root;
    }

    private AVLNode<T> minValueNode(AVLNode<T> node) {
        AVLNode<T> current = node;
        while (current.left != null) {
            current = current.left;
        }
        return current;
    }

    public static void main(String[] args) {
        AVLTree<Integer> avlTree = new AVLTree<>();
        avlTree.insert(10);
        avlTree.insert(20);
        avlTree.insert(5);
        avlTree.insert(6);
        avlTree.insert(15);
        avlTree.insert(25);

        System.out.println("In-order traversal:");
        avlTree.inOrder();
        System.out.println();

        System.out.println("Search 15: " + avlTree.search(15));
        System.out.println("Search 100: " + avlTree.search(100));

        avlTree.delete(20);

        System.out.println("In-order traversal after deleting 20:");
        avlTree.inOrder();
        System.out.println();
    }
}
class TreeNode<T extends Comparable<T>> {
    T data;
    TreeNode<T> left, right;

    public TreeNode(T data) {
        this.data = data;
        this.left = this.right = null;
    }
}

public class BinarySearchTree<T extends Comparable<T>> {
    private TreeNode<T> root;

    public BinarySearchTree() {
        this.root = null;
    }

    // Insert operation
    public void insert(T data) {
        root = insertRec(root, data);
    }

    private TreeNode<T> insertRec(TreeNode<T> root, T data) {
        if (root == null) {
            root = new TreeNode<>(data);
            return root;
        }

        if (data.compareTo(root.data) < 0) {
            root.left = insertRec(root.left, data);
        } else if (data.compareTo(root.data) > 0) {
            root.right = insertRec(root.right, data);
        }

        return root;
    }

    // Search operation
    public boolean search(T data) {
        return searchRec(root, data) != null;
    }

    private TreeNode<T> searchRec(TreeNode<T> root, T data) {
        if (root == null || root.data.equals(data)) {
            return root;
        }

        if (data.compareTo(root.data) < 0) {
            return searchRec(root.left, data);
        } else {
            return searchRec(root.right, data);
        }
    }

    // In-order traversal (sorted order)
    public void inOrder() {
        inOrderRec(root);
    }

    private void inOrderRec(TreeNode<T> root) {
        if (root != null) {
            inOrderRec(root.left);
            System.out.print(root.data + " ");
            inOrderRec(root.right);
        }
    }

    // Delete operation
    public void delete(T data) {
        root = deleteRec(root, data);
    }

    private TreeNode<T> deleteRec(TreeNode<T> root, T data) {
        if (root == null) {
            return null;
        }

        if (data.compareTo(root.data) < 0) {
            root.left = deleteRec(root.left, data);
        } else if (data.compareTo(root.data) > 0) {
            root.right = deleteRec(root.right, data);
        } else {
            // Node to be deleted found

            // Case 1: Node has no children (leaf node)
            if (root.left == null && root.right == null) {
                return null;
            }

            // Case 2: Node has only one child
            if (root.left == null) {
                return root.right;
            }
            if (root.right == null) {
                return root.left;
            }

            // Case 3: Node has two children
            T minValue = findMinValue(root.right);
            root.data = minValue;
            root.right = deleteRec(root.right, minValue);
        }

        return root;
    }

    private T findMinValue(TreeNode<T> root) {
        T minValue = root.data;
        while (root.left != null) {
            minValue = root.left.data;
            root = root.left;
        }
        return minValue;
    }

    public static void main(String[] args) {
        BinarySearchTree<Integer> bst = new BinarySearchTree<>();

        bst.insert(50);
        bst.insert(30);
        bst.insert(70);
        bst.insert(20);
        bst.insert(40);
        bst.insert(60);
        bst.insert(80);

        System.out.println("In-order traversal:");
        bst.inOrder();
        System.out.println();

        System.out.println("Search 60: " + bst.search(60));
        System.out.println("Search 100: " + bst.search(100));

        bst.delete(70);

        System.out.println("In-order traversal after deleting 70:");
        bst.inOrder();
        System.out.println();
    }
}
public class LinearProbingHashTable {
    private String[] keys;
    private String[] values;
    private int size;
    private int capacity;

    public LinearProbingHashTable(int capacity) {
        this.capacity = capacity;
        this.keys = new String[capacity];
        this.values = new String[capacity];
        this.size = 0;
    }

    private int hash(String key) {
        return key.length() % capacity;
    }
    
    public void put(String key, String value) {
        if (key == null || value == null) {
            throw new IllegalArgumentException("Key or value cannot be null.");
        }
        
        int index = hash(key);
        while (keys[index] != null) {
            if (keys[index].equals(key)) {
				values[index] = value;
                return;
            }
            index = (index + 1) % capacity;
        }
        keys[index] = key;
        values[index] = value;
        size++;
    }

    public String get(String key) {
        int index = hash(key);
        while (keys[index] != null) {
            if (keys[index].equals(key)) {
                return values[index];
            }
             index = (index + 1) % capacity;
        }
        return null; 
    }

    public void display() {
        for (int i = 0; i < capacity; i++) {
            if (keys[i] != null) {
                System.out.println("Key: " + keys[i] + ", Value: " + values[i]);
            }
        }
    }

    public static void main(String[] args) {
        LinearProbingHashTable hashTable = new LinearProbingHashTable(10);

        hashTable.put("John", "Doe");
        hashTable.put("Alice", "Smith");
        hashTable.put("Bob", "Johnson");
        hashTable.put("Charlie", "Brown");
 
        hashTable.display();

        System.out.println("Value associated with 'John': " + hashTable.get("John"));
        System.out.println("Value associated with 'Alice': " + hashTable.get("Alice"));
        System.out.println("Value associated with 'Bob': " + hashTable.get("Bob"));
        System.out.println("Value associated with 'Charlie': " + hashTable.get("Charlie"));
        System.out.println("Value associated with 'Dave': " + hashTable.get("Dave")); // Not found
    }
}
import java.util.LinkedList;

class KeyValuePair<K, V> {
    private K key;
    private V value;

    public KeyValuePair(K key, V value) {
        this.key = key;
        this.value = value;
    }

    public K getKey() {
        return key;
    }

    public V getValue() {
        return value;
    }
}

class SeparateChaining<K, V> {
    private LinkedList<KeyValuePair<K, V>>[] table;
    private int capacity;
	
    @SuppressWarnings("unchecked")
    public SeparateChaining(int capacity) {
        this.capacity = capacity;
        this.table = new LinkedList[capacity];
        for (int i = 0; i < capacity; i++) {
            table[i] = new LinkedList<>();
        }
    }

    private int hash(K key) {
        return Math.abs(key.hashCode() % capacity);
    }

    public void put(K key, V value) {
        int index = hash(key);
        LinkedList<KeyValuePair<K, V>> list = table[index];
        for (KeyValuePair<K, V> pair : list) {
            if (pair.getKey().equals(key)) {
                pair = new KeyValuePair<>(key, value);
                return;
            }
        }
        list.add(new KeyValuePair<>(key, value));
    }

    public V get(K key) {
        int index = hash(key);
        LinkedList<KeyValuePair<K, V>> list = table[index];
        for (KeyValuePair<K, V> pair : list) {
            if (pair.getKey().equals(key)) {
                return pair.getValue();
            }
        }
        return null;
    }

    public void remove(K key) {
        int index = hash(key);
        LinkedList<KeyValuePair<K, V>> list = table[index];
        for (KeyValuePair<K, V> pair : list) {
            if (pair.getKey().equals(key)) {
                list.remove(pair);
                return;
            }
        }
    }

    public void display() {
        for (int i = 0; i < capacity; i++) {
            System.out.print("Bucket " + i + ": ");
            for (KeyValuePair<K, V> pair : table[i]) {
                System.out.print("[" + pair.getKey() + ": " + pair.getValue() + "] ");
            }
            System.out.println();
        }
    }
}

public class SeparateChainingExample {
    public static void main(String[] args) {
        SeparateChaining<String, Integer> map = new SeparateChaining<>(5);

        map.put("John", 25);
        map.put("Alice", 30);
        map.put("Bob", 35);
        map.put("Doe", 40);  // Adding more elements to see separate chaining in action
        map.put("Eve", 45);

        System.out.println("Initial Map:");
        map.display();

        System.out.println("\nAlice's age: " + map.get("Alice"));
        System.out.println("Bob's age: " + map.get("Bob"));

        map.remove("Alice");

        System.out.println("\nMap after removing Alice:");
        map.display();

        System.out.println("Alice's age after removal: " + map.get("Alice"));
    }
}
class Node<T extends Comparable<T>> {
    T data;
    Node<T> next;

    public Node(T data) {
        this.data = data;
        this.next = null;
    }
}

public class SortedChain<T extends Comparable<T>> {
    private Node<T> head;

    public void insert(T data) {
        Node<T> newNode = new Node<>(data);
        
        if (head == null || head.data.compareTo(data) >= 0) {
            newNode.next = head;
            head = newNode;
        } else {
            Node<T> current = head;
            while (current.next != null && current.next.data.compareTo(data) < 0) {
                current = current.next;
            }
            newNode.next = current.next;
            current.next = newNode;
        }
    }

    public void display() {
        Node<T> current = head;
        while (current != null) {
            System.out.print(current.data + " ");
            current = current.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        SortedChain<Integer> sortedChain = new SortedChain<>();
        sortedChain.insert(5);
        sortedChain.insert(3);
        sortedChain.insert(7);
        sortedChain.insert(1);
        sortedChain.insert(9);

        System.out.println("Sorted Chain:");
        sortedChain.display();
    }
}
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

class Product {
    private int id;
    private String name;
    private double price;
    private String type;
    private double rating;

    public Product(int id, String name, double price, String type, double rating) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.type = type;
        this.rating = rating;
    }

    public double getRating() {
        return rating;
    }

    public double getPrice() {
        return price;
    }

    public String getType() {
        return type;
    }

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", type='" + type + '\'' +
                ", rating=" + rating +
                '}';
    }
}

public class ProductStreamExample {
    public static void main(String[] args) {
        List<Product> products = Arrays.asList(
                new Product(1, "Laptop", 1500.0, "Electronics", 4.5),
                new Product(2, "Smartphone", 800.0, "Electronics", 4.2),
                new Product(3, "Watch", 300.0, "Fashion", 3.8),
                new Product(4, "Headphones", 100.0, "Electronics", 4.8),
                new Product(5, "Shoes", 50.0, "Fashion", 3.5),
                new Product(6, "Camera", 2000.0, "Electronics", 4.7)
        );

        // i) Find all the products having rating between 4 and 5
        List<Product> productsRatingBetween4And5 = products.stream()
                .filter(p -> p.getRating() >= 4 && p.getRating() <= 5)
                .collect(Collectors.toList());
        System.out.println("Products with rating between 4 and 5: " + productsRatingBetween4And5);
		System.out.println();
        
        // ii) Find first n products having price > 10000
        int n = 2;
        List<Product> firstNProductsPriceGreaterThan1000 = products.stream()
                .filter(p -> p.getPrice() > 1000)
                .limit(n)
                .collect(Collectors.toList());
        System.out.println("First " + n + " products with price > 1000: " + firstNProductsPriceGreaterThan1000);
		System.out.println();
        
        // iii) Find the number of products under each type (map containing type and count)
        Map<String, Long> productCountByType = products.stream()
		.collect(Collectors.groupingBy(Product::getType, Collectors.counting()));
        System.out.println("Number of products under each type: " + productCountByType);
		System.out.println();
        
        // iv) Find average rating of products with type = "Electronics"
        double averageRatingElectronics = products.stream()
                .filter(p -> p.getType().equals("Electronics"))
                .mapToDouble(Product::getRating)
                .average()
                .orElse(0.0);
        System.out.println("Average rating of products with type 'Electronics': " + averageRatingElectronics);
    }
}
import java.util.Map;
import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        // Creating a TreeMap to store names and ages
        TreeMap<String, Integer> ageMap = new TreeMap<>();

        // Adding key-value pairs to the TreeMap
        ageMap.put("John", 30);
        ageMap.put("Alice", 25);
        ageMap.put("Bob", 35);
        ageMap.put("Eve", 28);

        // Accessing values using get() method
        System.out.println("Age of John: " + ageMap.get("John"));
        System.out.println("Age of Alice: " + ageMap.get("Alice"));

        // Updating a value using put() method
        ageMap.put("John", 32);
        System.out.println("Updated age of John: " + ageMap.get("John"));

        // Checking if a key exists
        String name = "Bob";
        if (ageMap.containsKey(name)) {
            System.out.println(name + " exists in the map.");
        } else {
            System.out.println(name + " does not exist in the map.");
        }

        // Removing an entry using remove() method
        ageMap.remove("Eve");
        System.out.println("Map after removing Eve: " + ageMap);

        // Iterating over map entries using for-each loop
        System.out.println("Iterating over map entries:");
        for (Map.Entry<String, Integer> entry : ageMap.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }

        // Checking size and emptiness
        System.out.println("Size of map: " + ageMap.size());
        System.out.println("Is map empty? " + ageMap.isEmpty());

        // Checking if map contains a key and value
        System.out.println("Contains key 'Bob': " + ageMap.containsKey("Bob"));
        System.out.println("Contains value 35: " + ageMap.containsValue(35));

        // Clear the map
        ageMap.clear();
        System.out.println("Map after clearing: " + ageMap);
    }
}
import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        // Creating a LinkedHashMap to store names and ages
        LinkedHashMap<String, Integer> ageMap = new LinkedHashMap<>();

        // Adding key-value pairs to the LinkedHashMap
        ageMap.put("John", 30);
        ageMap.put("Alice", 25);
        ageMap.put("Bob", 35);
        ageMap.put("Eve", 28);

        // Accessing values using get() method
        System.out.println("Age of John: " + ageMap.get("John"));
        System.out.println("Age of Alice: " + ageMap.get("Alice"));

        // Updating a value using put() method
        ageMap.put("John", 32);
        System.out.println("Updated age of John: " + ageMap.get("John"));

        // Checking if a key exists
        String name = "Bob";
        if (ageMap.containsKey(name)) {
            System.out.println(name + " exists in the map.");
        } else {
            System.out.println(name + " does not exist in the map.");
        }

        // Removing an entry using remove() method
        ageMap.remove("Eve");
        System.out.println("Map after removing Eve: " + ageMap);

        // Iterating over map entries
        System.out.println("Iterating over map entries:");
        for (Map.Entry<String, Integer> entry : ageMap.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }

        // Checking size and emptiness
        System.out.println("Size of map: " + ageMap.size());
        System.out.println("Is map empty? " + ageMap.isEmpty());

        // Checking if map contains a key and value
        System.out.println("Contains key 'Bob': " + ageMap.containsKey("Bob"));
        System.out.println("Contains value 35: " + ageMap.containsValue(35));

        // Clear the map
        ageMap.clear();
        System.out.println("Map after clearing: " + ageMap);
    }
}
select 
json_event->'project',
json_event->'pipeline_params'->'artifacts_iac' as iac
from cicd_event
where event_type = 'ci_start'
and jsonb_array_length(jsonb_path_query_array(
	json_event->'pipeline_params'->'artifacts_iac',
	'$[*] ? (@.classifier == "terraform")'
)) >=2
import java.util.HashMap;
import java.util.Map;

public class HashMapMethodsExample {
    public static void main(String[] args) {
        // Creating a HashMap to store names and ages
        HashMap<String, Integer> ageMap = new HashMap<>();

        // Adding key-value pairs to the HashMap
        ageMap.put("John", 30);
        ageMap.put("Alice", 25);
        ageMap.put("Bob", 35);

        // Accessing values using get() method
        System.out.println("Age of John: " + ageMap.get("John"));
        System.out.println("Age of Alice: " + ageMap.get("Alice"));

        // Updating a value using put() method
        ageMap.put("John", 32);
        System.out.println("Updated age of John: " + ageMap.get("John"));

        // Checking if a key exists
        String name = "Bob";
        if (ageMap.containsKey(name)) {
            System.out.println(name + " exists in the map.");
        } else {
            System.out.println(name + " does not exist in the map.");
        }

        // Removing an entry using remove() method
        ageMap.remove("Alice");
        System.out.println("Map after removing Alice: " + ageMap);

        // Iterating over map entries
        System.out.println("Iterating over map entries:");
        for (Map.Entry<String, Integer> entry : ageMap.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }

        // Checking size and emptiness
        System.out.println("Size of map: " + ageMap.size());
        System.out.println("Is map empty? " + ageMap.isEmpty());

        // Checking if map contains a key and value
        System.out.println("Contains key 'Bob': " + ageMap.containsKey("Bob"));
        System.out.println("Contains value 35: " + ageMap.containsValue(35));

        // Clear the map
        ageMap.clear();
        System.out.println("Map after clearing: " + ageMap);
    }
}
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class Person {
    private String name;
    private int age;
    private double income;

    public Person(String name, int age, double income) {
        this.name = name;
        this.age = age;
        this.income = income;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public double getIncome() {
        return income;
    }
}

public class PersonExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        List<Person> setA = new ArrayList<>();

        // Read the number of persons
        System.out.print("Enter the number of persons: ");
        int n = scanner.nextInt();
        scanner.nextLine(); // consume newline character

        // Read details for each person
        for (int i = 0; i < n; i++) {
            System.out.println("Enter details for person " + (i + 1) + ":");
            System.out.print("Name: ");
            String name = scanner.nextLine();
            System.out.print("Age: ");
            int age = scanner.nextInt();
            System.out.print("Income: ");
            double income = scanner.nextDouble();
            scanner.nextLine(); // consume newline character

            // Create a new Person object and add it to the list
            Person person = new Person(name, age, income);
            setA.add(person);
        }

        // Initialize sets B, C, and B and C
        List<Person> setB = new ArrayList<>();
        List<Person> setC = new ArrayList<>();
        List<Person> setBC = new ArrayList<>();

        // Compute the sets
        for (Person person : setA) {
            if (person.getAge() > 60) {
                setB.add(person);
            }
            if (person.getIncome() < 10000) {
                setC.add(person);
            }
            if (person.getAge() > 60 && person.getIncome() < 10000) {
                setBC.add(person);
            }
        }

        // Print the results
        System.out.println("\nSet A:");
        for (Person person : setA) {
            System.out.println("Name: " + person.getName() + ", Age: " + person.getAge() + ", Income: " + person.getIncome());
        }

        System.out.println("\nSet B (age > 60):");
        for (Person person : setB) {
            System.out.println("Name: " + person.getName() + ", Age: " + person.getAge() + ", Income: " + person.getIncome());
        }

        System.out.println("\nSet C (income < 10000):");
        for (Person person : setC) {
            System.out.println("Name: " + person.getName() + ", Age: " + person.getAge() + ", Income: " + person.getIncome());
        }

        System.out.println("\nSet B and C (age > 60 and income < 10000):");
        for (Person person : setBC) {
            System.out.println("Name: " + person.getName() + ", Age: " + person.getAge() + ", Income: " + person.getIncome());
        }
    }
}
import java.util.TreeSet;
import java.util.Iterator;

public class TreeSetExample {
    public static void main(String[] args) {
        // Create a TreeSet
        TreeSet<String> fruits = new TreeSet<>();

        // Add elements to the TreeSet
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        fruits.add("Date");
        fruits.add("Elderberry");
        fruits.add("Fig");
        fruits.add("Grape");

        // Display the TreeSet
        System.out.println("Fruits in the TreeSet: " + fruits);

        // Attempt to add a duplicate element
        boolean isAdded = fruits.add("Apple");
        System.out.println("Attempt to add 'Apple' again: " + isAdded); // Should print false

        // Check the size of the TreeSet
        System.out.println("Size of the TreeSet: " + fruits.size());

        // Check if an element exists
        boolean containsCherry = fruits.contains("Cherry");
        System.out.println("Does the set contain 'Cherry'? " + containsCherry);

        // Remove an element
        fruits.remove("Banana");
        System.out.println("Fruits after removing 'Banana': " + fruits);

        // Iterate through the TreeSet using an Iterator
        System.out.println("Iterating through the TreeSet using an Iterator:");
        Iterator<String> iterator = fruits.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

        // Iterate through the TreeSet using a for-each loop
        System.out.println("Iterating through the TreeSet using a for-each loop:");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }

        // Convert the TreeSet to an array
        Object[] fruitsArray = fruits.toArray();
        System.out.println("Fruits as an array:");
        for (Object fruit : fruitsArray) {
            System.out.println(fruit);
        }

        // Check if the TreeSet is empty
        System.out.println("Is the TreeSet empty? " + fruits.isEmpty());

        // Clone the TreeSet
        TreeSet<String> clonedFruits = (TreeSet<String>) fruits.clone();
        System.out.println("Cloned TreeSet: " + clonedFruits);

        // Clear the TreeSet
        fruits.clear();
        System.out.println("Is the TreeSet empty after clearing? " + fruits.isEmpty());

        // Add all elements from another collection
        TreeSet<String> moreFruits = new TreeSet<>();
        moreFruits.add("Kiwi");
        moreFruits.add("Lemon");
        moreFruits.add("Mango");
        fruits.addAll(moreFruits);
        System.out.println("Fruits after adding more fruits: " + fruits);

        // Retain only certain elements
        TreeSet<String> retainFruits = new TreeSet<>();
        retainFruits.add("Kiwi");
        retainFruits.add("Mango");
        fruits.retainAll(retainFruits);
        System.out.println("Fruits after retaining certain fruits: " + fruits);

        // Remove all elements from another collection
        fruits.removeAll(retainFruits);
        System.out.println("Fruits after removing retained fruits: " + fruits);

        // Accessing the first and last elements
        System.out.println("First fruit in the TreeSet: " + moreFruits.first());
        System.out.println("Last fruit in the TreeSet: " + moreFruits.last());

        // Subset of the TreeSet
        TreeSet<String> subSet = (TreeSet<String>) moreFruits.subSet("Kiwi", "Mango");
        System.out.println("Subset from 'Kiwi' to 'Mango': " + subSet);
    }
}
import java.util.LinkedHashSet;
import java.util.Iterator;

public class LinkedHashSetExample {
    public static void main(String[] args) {
        // Create a LinkedHashSet
        LinkedHashSet<String> fruits = new LinkedHashSet<>();

        // Add elements to the LinkedHashSet
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        fruits.add("Date");
        fruits.add("Elderberry");
        fruits.add("Fig");
        fruits.add("Grape");

        // Display the LinkedHashSet
        System.out.println("Fruits in the LinkedHashSet: " + fruits);

        // Attempt to add a duplicate element
        boolean isAdded = fruits.add("Apple");
        System.out.println("Attempt to add 'Apple' again: " + isAdded); // Should print false

        // Check the size of the LinkedHashSet
        System.out.println("Size of the LinkedHashSet: " + fruits.size());

        // Check if an element exists
        boolean containsCherry = fruits.contains("Cherry");
        System.out.println("Does the set contain 'Cherry'? " + containsCherry);

        // Remove an element
        fruits.remove("Banana");
        System.out.println("Fruits after removing 'Banana': " + fruits);

        // Iterate through the LinkedHashSet using an Iterator
        System.out.println("Iterating through the LinkedHashSet using an Iterator:");
        Iterator<String> iterator = fruits.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

        // Iterate through the LinkedHashSet using a for-each loop
        System.out.println("Iterating through the LinkedHashSet using a for-each loop:");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }

        // Convert the LinkedHashSet to an array
        Object[] fruitsArray = fruits.toArray();
        System.out.println("Fruits as an array:");
        for (Object fruit : fruitsArray) {
            System.out.println(fruit);
        }

        // Check if the LinkedHashSet is empty
        System.out.println("Is the LinkedHashSet empty? " + fruits.isEmpty());

        // Clone the LinkedHashSet
        LinkedHashSet<String> clonedFruits = (LinkedHashSet<String>) fruits.clone();
        System.out.println("Cloned LinkedHashSet: " + clonedFruits);

        // Clear the LinkedHashSet
        fruits.clear();
        System.out.println("Is the LinkedHashSet empty after clearing? " + fruits.isEmpty());

        // Add all elements from another collection
        LinkedHashSet<String> moreFruits = new LinkedHashSet<>();
        moreFruits.add("Kiwi");
        moreFruits.add("Lemon");
        moreFruits.add("Mango");
        fruits.addAll(moreFruits);
        System.out.println("Fruits after adding more fruits: " + fruits);

        // Retain only certain elements
        LinkedHashSet<String> retainFruits = new LinkedHashSet<>();
        retainFruits.add("Kiwi");
        retainFruits.add("Mango");
        fruits.retainAll(retainFruits);
        System.out.println("Fruits after retaining certain fruits: " + fruits);

        // Remove all elements from another collection
        fruits.removeAll(retainFruits);
        System.out.println("Fruits after removing retained fruits: " + fruits);
    }
}
public class BoundedArithematic<T extends Number> {
    public double add(T a, T b) {
        return a.doubleValue() + b.doubleValue();
    }
    public double subtract(T a, T b) {
        return a.doubleValue() - b.doubleValue();
    }
    public double multiply(T a, T b) {
        return a.doubleValue() * b.doubleValue();
    }	
   public double divide(T a, T b) {
        if (b.doubleValue() == 0) {
            throw new ArithmeticException("Division by zero is not allowed.");
        }
        return a.doubleValue() / b.doubleValue();
    }
    public static void main(String[] args) {
        BoundedArithematic<Number> calculator = new BoundedArithematic<>();
        Integer a = 10;
        Integer b = 5;
        System.out.println("Addition: " + calculator.add(a, b));
        System.out.println("Subtraction: " + calculator.subtract(a, b));
        System.out.println("Multiplication: " + calculator.multiply(a, b));
        System.out.println("Division: " + calculator.divide(a, b));
    }
}
==
//Wildcard Arguments
public class MagicBox<T> {
    private T item;

    public void addItem(T item) {
        this.item = item;
        System.out.println("Added item to the magic box: " + item);
    }

    public T getItem() {
                return item;
    }

    public void processBox(MagicBox<? super Integer> box) {
        System.out.println("Items in the box are processed["+box.getItem()+"]"); 
    }

    public static void main(String[] args) {
        
        MagicBox<Integer> integerBox = new MagicBox<>();
        integerBox.addItem(43);
        		
		MagicBox<String> stringBox = new MagicBox<>();
        stringBox.addItem("Sofiya");
        	
		
        MagicBox<Boolean> booleanBox = new MagicBox<>();
        booleanBox.addItem(false);
        
		MagicBox<Object> dobubleBox = new MagicBox<>();
        dobubleBox.addItem(43.43);
		
		integerBox.processBox(integerBox);
		dobubleBox.processBox(dobubleBox);
		
		
		
        
    }
}
star

Sat Jun 08 2024 02:00:56 GMT+0000 (Coordinated Universal Time)

@signup

star

Sat Jun 08 2024 00:45:15 GMT+0000 (Coordinated Universal Time)

@ayushg103 #c++

star

Sat Jun 08 2024 00:37:29 GMT+0000 (Coordinated Universal Time)

@gabriellesoares

star

Fri Jun 07 2024 22:54:08 GMT+0000 (Coordinated Universal Time)

@ayushg103 #c++

star

Fri Jun 07 2024 21:53:11 GMT+0000 (Coordinated Universal Time)

@ayushg103 #c++

star

Fri Jun 07 2024 20:10:48 GMT+0000 (Coordinated Universal Time) https://python.land/virtual-environments/virtualenv

@vladk

star

Fri Jun 07 2024 19:38:55 GMT+0000 (Coordinated Universal Time)

@signup

star

Fri Jun 07 2024 19:26:47 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 19:26:21 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 19:26:01 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 19:25:37 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 19:25:13 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 19:24:44 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 19:24:19 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 19:23:48 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 19:23:26 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 19:15:27 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:58:26 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:56:03 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:51:52 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:45:27 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:42:13 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:37:36 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:35:46 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:32:44 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:31:23 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:29:13 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:27:23 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:25:33 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:24:02 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:22:15 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:20:23 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:02:10 GMT+0000 (Coordinated Universal Time) https://gramentheme.com/html/odor/index.html?storefront

@jagdish575 #html #css #javascript

star

Fri Jun 07 2024 15:10:04 GMT+0000 (Coordinated Universal Time)

@prabhas

star

Fri Jun 07 2024 14:43:19 GMT+0000 (Coordinated Universal Time)

@exam

star

Fri Jun 07 2024 14:18:48 GMT+0000 (Coordinated Universal Time)

@ayushg103 #c++

star

Fri Jun 07 2024 14:04:18 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 14:03:07 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 14:02:25 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 14:01:40 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 14:00:56 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 13:59:29 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 13:58:39 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 13:58:10 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 13:57:08 GMT+0000 (Coordinated Universal Time)

@lokan32 #postgres #postgresql #json

star

Fri Jun 07 2024 13:56:50 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 13:54:41 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 13:20:36 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 13:19:38 GMT+0000 (Coordinated Universal Time)

@dbms

star

Fri Jun 07 2024 13:19:29 GMT+0000 (Coordinated Universal Time)

@exam

Save snippets that work with our extensions

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