Snippets Collections
package test;
 
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
@WebServlet("/updateUser")
public class jsplog extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Get user input from the form
        String id = request.getParameter("id");
        String name = request.getParameter("name");
 
        // Database connection parameters
        String jdbcUrl = "jdbc:mysql://localhost:3306/nehal";
        String dbUser = "root";
        String dbPassword = "nehal@123";
 
        Connection conn = null;
        PreparedStatement pstmt = null;
 
        try {
            // Load the JDBC driver
            Class.forName("com.mysql.cj.jdbc.Driver");
 
            // Establish a connection to the database
            conn = DriverManager.getConnection(jdbcUrl, dbUser, dbPassword);
 
            // Prepare SQL update query
            String sql = "UPDATE emp SET name = ? WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, name); // Set new name
            pstmt.setInt(2, Integer.parseInt(id)); // Set user ID
 
            // Execute update
            int rowsUpdated = pstmt.executeUpdate();
 
            // Respond to the client
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            if (rowsUpdated > 0) {
                out.println("<h1>Record updated successfully for user ID: " + id + "</h1>");
            } else {
                out.println("<h1>No user found with ID: " + id + "</h1>");
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (pstmt != null) pstmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
//html
<!DOCTYPE html>
<html>
<head>
    <title>Update User</title>
</head>
<body>
    <h2>Update User Information</h2>
    <form action="updateUser" method="post">
        <label for="id">User ID:</label>
        <input type="text" id="id" name="id" required><br><br>
 
        <label for="name">New Name:</label>
        <input type="text" id="name" name="name" required><br><br>
 
        <input type="submit" value="Update">
    </form>
</body>
</html>
<%@ page import="java.sql.*" %>
<html>
<body>
<%
    String url = "jdbc:oracle:thin:@//localhost:1521/XE";
    String user = "system";
    String password = "abhi";
    Connection conn = null;
    try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
        conn = DriverManager.getConnection(url, user, password);
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM employee");
        while (rs.next()) {
%>
            <p>User: <%= rs.getString("ename") %></p>
<%
        }
    } catch (Exception e) {
        out.println("Error: " + e.getMessage());
    } finally {
        if (conn != null) conn.close();
    }
%>
</body>
</html>
<%@ page language="java" %>
<html>
<head>
    <title>Login</title>
</head>
<body>
    <h2>User Login</h2>
    <form action="validateLogin.jsp" method="post">
        <label>Username:</label>
        <input type="text" name="username" required><br>
        <label>Password:</label>
        <input type="password" name="password" required><br>
        <input type="submit" value="Login">
    </form>
</body>
</html>



<%@ page import="java.sql.*" %>
<html>
<body>
<%
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    boolean isValid = false;

    String url = "jdbc:oracle:thin:@//localhost:1521/XE";
    String duser = "system";
    String dpassword = "abhi";
    Connection conn = null;
    try {
    	Class.forName("oracle.jdbc.driver.OracleDriver");
        conn = DriverManager.getConnection(url, duser, dpassword);
        PreparedStatement ps = conn.prepareStatement("SELECT * FROM users1 WHERE username=? AND password=?");
        ps.setString(1, username);
        ps.setString(2, password);
        ResultSet rs = ps.executeQuery();
        isValid = rs.next();
    } catch (Exception e) {
        out.println("Error: " + e.getMessage());
    } finally {
        if (conn != null) conn.close();
    }
    if (isValid) {
        out.println("Login Successful");
        out.println("<h1> hi "+ username+"! </h1>");
    } else {
        out.println("Invalid Credentials");
    }
%>
</body>
</html>
<%@ page import="java.sql.*" %>
<html>
<body>
<%
    String url = "jdbc:oracle:thin:@//localhost:1521/XE";
    String user = "system";
    String password = "abhi";
    Connection conn = null;
    try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
        conn = DriverManager.getConnection(url, user, password);
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM employee");
        while (rs.next()) {
%>
            <p>User: <%= rs.getString("ename") %></p>
<%
        }
    } catch (Exception e) {
        out.println("Error: " + e.getMessage());
    } finally {
        if (conn != null) conn.close();
    }
%>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.Date" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
   <p>Current Date and Time: <%= new Date() %></p>
</body>
</html>
<html>
<body>
    <form action="request.jsp" method="post">
        Name: <input type="text" name="name"><br>
        Age: <input type="number" name="age"><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

<html>
<body>
    <p>Name: <%= request.getParameter("name") %></p>
    <p>Age: <%= request.getParameter("age") %></p>
</body>
</html>
// File: ScrollableAndUpdatableResultSetExample.java
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class UpdateScrollResultset {
    public static void main(String[] args) throws ClassNotFoundException {
       
        //Class.forName("oracle.jdbc.driver.OracleDriver");
       //String jdbcURL = "jdbc:oracle:thin:@localhost:1521/XE";
        String jdbcURL = "jdbc:mysql://localhost:3306/jdbcdb"; 
        String username = ""; 
        String password = ""; 

    
        String query = "SELECT emp_id, empname, dob,salary,dept_id FROM employee";

        try (Connection connection = DriverManager.getConnection(jdbcURL, username, password)) {

            
            Statement statement = connection.createStatement(
                ResultSet.TYPE_SCROLL_SENSITIVE,      
                ResultSet.CONCUR_UPDATABLE      
            );

            
            ResultSet resultSet = statement.executeQuery(query);

            
            if (resultSet.last()) {
                System.out.println("Last Employee:");
                printEmployee(resultSet);
            }

            
            if (resultSet.first()) {
                System.out.println("First Employee:");
                printEmployee(resultSet);
            }

            
            if (resultSet.absolute(3)) {
                System.out.println("Third Employee:");
                printEmployee(resultSet);
            }

   
            resultSet.absolute(2); /
            double oldSalary = resultSet.getDouble("salary");
            double newSalary = oldSalary * 1.05; 
            resultSet.updateDouble("salary", newSalary);
            

            resultSet.updateRow();

            System.out.println("Updated Employee (2nd row) Salary: ");
            printEmployee(resultSet);

          
            resultSet.moveToInsertRow(); 
            resultSet.updateInt("emp_id",9);
            resultSet.updateString("empname", "Karthik");
            resultSet.updateDate("dob", Date.valueOf("1990-01-01"));
            resultSet.updateDouble("salary", 500000);
            resultSet.updateInt("dept_id", 15);
            resultSet.insertRow(); // Insert the row in the database
            System.out.println("Inserted a new employee.");
    
            // Delete the newly inserted row
            if (resultSet.last()) {
                resultSet.deleteRow(); // Delete the last row (which was just inserted)
                System.out.println("Deleted the newly inserted employee.");
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // Utility method to print employee details
    private static void printEmployee(ResultSet resultSet) throws SQLException {
        int empId = resultSet.getInt("emp_id");
        String empName = resultSet.getString("empname");
        Date dob = resultSet.getDate("dob");
        double salary = resultSet.getDouble("salary");
        int deptId = resultSet.getInt("dept_id");

        System.out.println("Employee ID: " + empId);
        System.out.println("Employee Name: " + empName);
       // System.out.println("Date of Birth: " + dob);
        System.out.println("Salary: " + salary);
        System.out.println("Department ID: " + deptId);
        System.out.println("------------------------");
    }
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class JdbcMultipleConn{
    public static void main(String[] args) {
        Connection conn1 = null;
        Connection conn2 = null;
        Connection conn3 = null;

        try{
            //Connection no #1
            String url1 = "jdbc:mysql://localhost:3306/jdbcdb"; 
            String user = "root";
            String password = "ramesh";
            conn1 = DriverManager.getConnection(url1, user, password);
            if (conn1 != null) {           
                System.out.println("Connected to the database jdbcdb");
                    }
                String url2 = "jdbc:mysql://localhost:3306/jdbcdb?user=root&password=ramesh";
            conn2 = DriverManager.getConnection(url2);
            if (conn2 != null) {
            System.out.println("Connected to the database jdbcdb");
        }

            String url3 = "jdbc:mysql://localhost:3306/jdbcdb";
            Properties info = new Properties();
            info.put("user", "root");
            info.put("password", "ramesh");
            conn3 = DriverManager.getConnection(url3, info);
                if (conn3 != null) {
                System.out.println("Connected to the database jdbcdb");
        }
        
        }

        catch (SQLException ex) {
            System.out.println("An error occurred. Maybe user/password is invalid");
            ex.printStackTrace();
                }
        }
    }                
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%
    // Initialize variables to hold form data
    String name = request.getParameter("name");
    String age = request.getParameter("age");
    boolean formSubmitted = (name != null && age != null); // Check if form is submitted
%>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Parameter Input Form</title>
</head>
<body>
    <h2>Enter Your Details</h2>

    <!-- Display the form if no data has been submitted -->
    <% if (!formSubmitted) { %>
        <form action="requestjsp.jsp" method="post">
            Name: <input type="text" name="name" required><br><br>
            Age: <input type="text" name="age" required><br><br>
            <input type="submit" value="Submit">
        </form>
    <% } else { %>
        <!-- Display submitted data if form is submitted -->
        <h2>Your Details:</h2>
        <p>Name: <%= name %></p>
        <p>Age: <%= age %></p>
    <% } %>
</body>
</html>
Add.java
@WebServlet( urlPatterns={"/add"})
public class Add extends HttpServlet {
    public void service(HttpServletRequest req, HttpServletResponse res) throws IOException {
    	
    	int i=Integer.parseInt(req.getParameter("num1"));
    	int j=Integer.parseInt(req.getParameter("num2"));
    	
    	int k=i+j;
    	PrintWriter out=res.getWriter();
    	out.println(k);
    			
    }

}

index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Add numbers</title>
</head>
<body>
	
	<form action="add" method="get">
		enter num1:<input type="text" name="num1"><br>
		Enter num2:<input type="text" name="num2">
		
		<br>
		<input type="submit" value="Add">
	</form>
</body>
</html>
books.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE bookstore SYSTEM "bookstore.dtd">
<bookstore>
    <book>
        <title>Introduction to XML</title>
        <author>John Doe</author>
        <isbn>978-0-123456-47-2</isbn>
        <publisher>Example Press</publisher>
        <edition>3rd</edition>
        <price>39.99</price>
    </book>
    <book>
        <title>Advanced XML Concepts</title>
        <author>Jane Smith</author>
        <isbn>978-0-765432-10-5</isbn>
        <publisher>Tech Books Publishing</publisher>
        <edition>1st</edition>
        <price>45.00</price>
    </book>
</bookstore>

bookstore.dtd
<!ELEMENT bookstore (book+)>
<!ELEMENT book (title, author, isbn, publisher, edition, price)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT isbn (#PCDATA)>
<!ELEMENT publisher (#PCDATA)>
<!ELEMENT edition (#PCDATA)>
<!ELEMENT price (#PCDATA)>
import java.sql.*;

public class ScrollableResultSetExample {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/your_database";
        String username = "root"; 
        String password = "your_password";

        try {
            Connection connection = DriverManager.getConnection(url, username, password);

            String query = "SELECT * FROM your_table";
            Statement statement = connection.createStatement(
                    ResultSet.TYPE_SCROLL_INSENSITIVE, 
                    ResultSet.CONCUR_READ_ONLY);
            
            ResultSet resultSet = statement.executeQuery(query);
            
            if (resultSet.last()) {
                System.out.println(resultSet.getString("column_name"));
            }

            if (resultSet.first()) {
                System.out.println(resultSet.getString("column_name"));
            }

            resultSet.close();
            statement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
import java.sql.*;

public class DMLExamples {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/your_database";
        String username = "root";
        String password = "your_password";

        try (Connection connection = DriverManager.getConnection(url, username, password)) {
            System.out.println("Connected to the database.");

          
            String insertSQL = "INSERT INTO your_table (column1, column2) VALUES (?, ?)";
            try (PreparedStatement insertStmt = connection.prepareStatement(insertSQL)) {
                insertStmt.setString(1, "Alice");
                insertStmt.setInt(2, 30);
                int rowsInserted = insertStmt.executeUpdate();
                System.out.println(rowsInserted + " row(s) inserted.");
            }

            
            String updateSQL = "UPDATE your_table SET column2 = ? WHERE column1 = ?";
            try (PreparedStatement updateStmt = connection.prepareStatement(updateSQL)) {
                updateStmt.setInt(1, 35); // New value for column2
                updateStmt.setString(2, "Alice"); // Condition
                int rowsUpdated = updateStmt.executeUpdate();
                System.out.println(rowsUpdated + " row(s) updated.");
            }

          
            String selectSQL = "SELECT * FROM your_table";
            try (PreparedStatement selectStmt = connection.prepareStatement(selectSQL)) {
                ResultSet resultSet = selectStmt.executeQuery();
                System.out.println("Data in the table:");
                while (resultSet.next()) {
                    int id = resultSet.getInt("id");
                    String column1 = resultSet.getString("column1");
                    int column2 = resultSet.getInt("column2");
                    System.out.printf("ID: %d, Column1: %s, Column2: %d%n", id, column1, column2);
                }
            }

          
            String deleteSQL = "DELETE FROM your_table WHERE column1 = ?";
            try (PreparedStatement deleteStmt = connection.prepareStatement(deleteSQL)) {
                deleteStmt.setString(1, "Alice");
                int rowsDeleted = deleteStmt.executeUpdate();
                System.out.println(rowsDeleted + " row(s) deleted.");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
import java.sql.*;

public class DatabaseConnectionExample {
    public static void main(String[] args) {
      
        String url = "jdbc:mysql://localhost:3306/your_database";
        String username = "root"; 
        String password = "your_password";

        try {
           
            Connection connection = DriverManager.getConnection(url, username, password);
            System.out.println("Connection established!");

            
            Statement statement = connection.createStatement();
            
            
            String query = "SELECT * FROM your_table";
            ResultSet resultSet = statement.executeQuery(query);
            
           
            while (resultSet.next()) {
                System.out.println(resultSet.getString("column_name"));
            }

           
            resultSet.close();
            statement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
import com.atlassian.jira.component.ComponentAccessor

def allProjects = ComponentAccessor.projectManager

def projects = allProjects.projects

projects.each{ project ->
    log.warn(project.key)
}
// Call the Jira REST API to retrieve all projects
def response = get('/rest/api/3/project')
    .header('Content-Type', 'application/json')
    .asObject(List)

// Check for a successful response
if (response.status != 200) {
    return "Error fetching projects: ${response.status} - ${response.statusText}"
}

// Cast the response body to a List of Maps for static type checking
List<Map> projects = response.body as List<Map>

// Extract project data and map to a simplified structure
return projects.collect { project ->
    [
        id   : project['id'],
        key  : project['key'],
        name : project['name']
    ]
}
const add = (a, b) => a + b;
console.log("Addition:", add(5, 3)); 


const greet = () => "Hello, World!";
console.log("Greeting:", greet()); 


const square = x => x * x;
console.log("Square of 4:", square(4)); 


const isEven = num => num % 2 === 0;
console.log("Is 10 even?:", isEven(10)); 


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


const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log("Even Numbers:", evenNumbers); 

<%@ page import="java.sql.*" %>
<html>
<body>
<%
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    boolean isValid = false;

    String url = "jdbc:oracle:thin:@//localhost:1521/XE";
    String duser = "system";
    String dpassword = "abhi";
    Connection conn = null;
    try {
    	Class.forName("oracle.jdbc.driver.OracleDriver");
        conn = DriverManager.getConnection(url, duser, dpassword);
        PreparedStatement ps = conn.prepareStatement("SELECT * FROM users1 WHERE username=? AND password=?");
        ps.setString(1, username);
        ps.setString(2, password);
        ResultSet rs = ps.executeQuery();
        isValid = rs.next();
    } catch (Exception e) {
        out.println("Error: " + e.getMessage());
    } finally {
        if (conn != null) conn.close();
    }
    if (isValid) {
        out.println("Login Successful");
        out.println("<h1> hi "+ username+"! </h1>");
    } else {
        out.println("Invalid Credentials");
    }
%>
</body>
</html>


<%@ page language="java" %>
<html>
<head>
    <title>Login</title>
</head>
<body>
    <h2>User Login</h2>
    <form action="validateLogin.jsp" method="post">
        <label>Username:</label>
        <input type="text" name="username" required><br>
        <label>Password:</label>
        <input type="password" name="password" required><br>
        <input type="submit" value="Login">
    </form>
</body>
</html>
<%@ page import="java.sql.*" %>
<html>
<body>
<%
    String url = "jdbc:oracle:thin:@//localhost:1521/XE";
    String user = "system";
    String password = "abhi";
    Connection conn = null;
    try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
        conn = DriverManager.getConnection(url, user, password);
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM employee");
        while (rs.next()) {
%>
            <p>User: <%= rs.getString("ename") %></p>
<%
        }
    } catch (Exception e) {
        out.println("Error: " + e.getMessage());
    } finally {
        if (conn != null) conn.close();
    }
%>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.Date" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
   <p>Current Date and Time: <%= new Date() %></p>
</body>
</html>
<html>
<body>
    <form action="request.jsp" method="post">
        Name: <input type="text" name="name"><br>
        Age: <input type="number" name="age"><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>


<html>
<body>
    <p>Name: <%= request.getParameter("name") %></p>
    <p>Age: <%= request.getParameter("age") %></p>
</body>
</html>
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JdbcTransactionExample {

    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pstmt1 = null;
        PreparedStatement pstmt2 = null;

        try {
            // Step 1: Establish database connection
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bank", "root", "ramesh");

          
            conn.setAutoCommit(false);

         
            String sql1 = "UPDATE bank_account SET balance = balance - ? WHERE account_id = ?";
            pstmt1 = conn.prepareStatement(sql1);
            pstmt1.setDouble(1, 1000); 
            pstmt1.setInt(2, 1);

            String sql2 = "UPDATE bank_account SET balance = balance + ? WHERE account_id = ?";
            pstmt2 = conn.prepareStatement(sql2);
            pstmt2.setDouble(1, 1000); 
            pstmt2.setInt(2, 2);

         
            pstmt1.executeUpdate();
            pstmt2.executeUpdate();

       
            conn.commit();
            System.out.println("Transaction committed successfully");

        } catch (SQLException e) {
          
            if (conn != null) {
                try {
                    conn.rollback();
                    System.out.println("Transaction rolled back due to error");
                } catch (SQLException rollbackEx) {
                    rollbackEx.printStackTrace();
                }
            }
            e.printStackTrace();
        } finally {
            
            try {
                if (pstmt1 != null) pstmt1.close();
                if (pstmt2 != null) pstmt2.close();
                if (conn != null) conn.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }
}
// File: ResultSetMetaDataExample.java
import java.sql.*;

public class ResultSetMetaDataExample {
    public static void main(String[] args) throws ClassNotFoundException {
   
        String jdbcURL = "jdbc:mysql://localhost:3306/jdbcdb"; 
         //String DB_URL = "jdbc:oracle:thin:@localhost:1521:XE";
   
        String username = "";
        String password = "";

       
        String query = "SELECT * FROM employee"; 
//Class.forName("oracle.jdbc.driver.OracleDriver");

        try (Connection connection = DriverManager.getConnection(jdbcURL, username, password);
             Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery(query)) {

           
            ResultSetMetaData metaData = resultSet.getMetaData();

           
            int columnCount = metaData.getColumnCount();

           
            System.out.println("Table and Column names:");
            for (int i = 1; i <= columnCount; i++) {
                String tableName = metaData.getTableName(i);
                String columnName = metaData.getColumnName(i);
                System.out.print(columnName + " (" + tableName + ") | ");
            }
            System.out.println();

            System.out.println("\nRow data:");
            while (resultSet.next()) {
                for (int i = 1; i <= columnCount; i++) {
                    Object columnValue = resultSet.getObject(i);
                    System.out.print(columnValue + " | ");
                }
                System.out.println(); 
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
//form.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <title>Input Form</title>
</head>
<body>
    <h2>Enter Your Details</h2>
    <form action="process.jsp" method="post">
        <label for="name">Name:</label><br>
        <input type="text" id="name" name="name" required><br><br>

        <label for="email">Email:</label><br>
        <input type="email" id="email" name="email" required><br><br>

        <input type="submit" value="Submit">
    </form>
</body>
</html>


//process.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <title>Form Submission Result</title>
</head>
<body>
    <h2>Submitted Details</h2>
    <%
        // Access request parameters using request.getParameter()
        String name = request.getParameter("name");
        String email = request.getParameter("email");

        // Check if parameters are not null (useful for handling cases when accessed directly)
        if (name != null && email != null) {
    %>
        <p><strong>Name:</strong> <%= name %></p>
        <p><strong>Email:</strong> <%= email %></p>
    <%
        } else {
    %>
        <p style="color:red;">No data received!</p>
    <%
        }
    %>
    <br>
    <a href="form.jsp">Go Back</a>
</body>
</html>
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class JdbcMultipleConn{
    public static void main(String[] args) {
        Connection conn1 = null;
        Connection conn2 = null;
        Connection conn3 = null;

        try{
            //Connection no #1
            String url1 = "jdbc:mysql://localhost:3306/jdbcdb"; 
            String user = "root";
            String password = "ramesh";
            conn1 = DriverManager.getConnection(url1, user, password);
            if (conn1 != null) {           
                System.out.println("Connected to the database jdbcdb");
                    }
                String url2 = "jdbc:mysql://localhost:3306/jdbcdb?user=root&password=ramesh";
            conn2 = DriverManager.getConnection(url2);
            if (conn2 != null) {
            System.out.println("Connected to the database jdbcdb");
        }

            String url3 = "jdbc:mysql://localhost:3306/jdbcdb";
            Properties info = new Properties();
            info.put("user", "root");
            info.put("password", "ramesh");
            conn3 = DriverManager.getConnection(url3, info);
                if (conn3 != null) {
                System.out.println("Connected to the database jdbcdb");
        }
        
        }

        catch (SQLException ex) {
            System.out.println("An error occurred. Maybe user/password is invalid");
            ex.printStackTrace();
                }
        }
    }                
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.*;
import jakarta.servlet.annotation.*;

@WebServlet("/hitcounter")
public class HitCounterServlet extends HttpServlet {
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Set the content type to HTML
        response.setContentType("text/html");

        // Get the writer to send the response
        PrintWriter out = response.getWriter();

        // Get the cookies from the request
        Cookie[] cookies = request.getCookies();
        int hitCount = 0;

        // Check if there's a cookie for 'hitCount'
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("hitCount".equals(cookie.getName())) {
                    hitCount = Integer.parseInt(cookie.getValue());
                    break;
                }
            }
        }

        // Increment the hit count
        hitCount++;

        // Create or update the 'hitCount' cookie
        Cookie hitCountCookie = new Cookie("hitCount", String.valueOf(hitCount));
        hitCountCookie.setMaxAge(60 * 60 * 24 * 7); // 1 week expiry time
        response.addCookie(hitCountCookie);

        // Generate the HTML response
        out.println("<html>");
        out.println("<head><title>Hit Counter</title></head>");
        out.println("<body>");
        out.println("<h1>Page hit count: " + hitCount + "</h1>");
        out.println("</body>");
        out.println("</html>");
    }
}
<%@ page import="java.sql.*" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <title>JSP Oracle Database Connectivity</title>
    <style>
        table { width: 60%; margin: 20px auto; border-collapse: collapse; }
        table, th, td { border: 1px solid black; text-align: center; padding: 8px; }
        th { background-color: #f2f2f2; }
        h2 { text-align: center; }
    </style>
</head>
<body>
    <h2>User Details from Oracle Database</h2>
    <%
        // Oracle database connection details
        String url = "jdbc:oracle:thin:@localhost:1521:xe";
        String username = "system"; // Replace with your Oracle username
        String password = "1234"; // Replace with your Oracle password

        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            // Load the Oracle JDBC driver
            //Class.forName("oracle.jdbc.driver.OracleDriver");
            
            // Establish the database connection
            conn = DriverManager.getConnection(url, username, password);
            
            // Create a statement object to execute queries
            stmt = conn.createStatement();
            
            // Execute a query to fetch data from the 'users' table
            String query = "SELECT * FROM users";
            rs = stmt.executeQuery(query);
    %>
    <table>
        <tr>
            <th>User ID</th>
            <th>Name</th>
            <th>Email</th>
        </tr>
        <%
            // Iterate through the result set and display data in the table
            while (rs.next()) {
        %>
        <tr>
            <td><%= rs.getInt("user_id") %></td>
            <td><%= rs.getString("name") %></td>
            <td><%= rs.getString("email") %></td>
        </tr>
        <%
            }
        %>
    </table>
    <%
        } catch (Exception e) {
            out.println("<p style='color:red; text-align:center;'>Error: " + e.getMessage() + "</p>");
        } finally {
            // Close all resources to avoid memory leaks
            if (rs != null) try { rs.close(); } catch (SQLException ignored) {}
            if (stmt != null) try { stmt.close(); } catch (SQLException ignored) {}
            if (conn != null) try { conn.close(); } catch (SQLException ignored) {}
        }
    %>
</body>
</html>
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;


public class JdbcConnectionExample {
	
	
	  public static void main(String[] args)throws ClassNotFoundException {
	    Connection con = null;
        Statement st=null;
	    String url = "jdbc:mysql://localhost:3306/books";
	    String username = "root";
	    String password = "ramesh";

	    try {
	      Class.forName("com.mysql.cj.jdbc.Driver");
	      con = DriverManager.getConnection(url, username, password);

	      System.out.println("Connected!");
            st= con.createStatement();
			System.out.println("Inserting Records into the table");
			int rowupdate=st.executeUpdate("insert into book values(33,'Machine Learning through JavaScript','Anderson','Taylor series',2500)");
		    ResultSet rs1=st.executeQuery("Select * from book");	          
                    //Get the values of the record using while loop from result set
                    while(rs1.next())
                    {
                        int id = rs1.getInt(1);
                        String title = rs1.getString(2);
                        String author = rs1.getString(3);
                        String publisher = rs1.getString(4);
                        int price = rs1.getInt(5);
                        //String totalMarks= rs1.getInt(5);
                        //store the values which are retrieved using ResultSet and print them
                    System.out.println(id + ","+title+ ","+author+ ","+publisher +","+price );
                    }
         
	    } catch (SQLException ex) {
	        throw new Error("Error ", ex);
	    } finally {
	      try {
	        if (con != null) {
	            con.close();
	        }
	      } catch (SQLException ex) {
	          System.out.println(ex.getMessage());
	      }
	    }
	  }
	}
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <title>Simple JSP Program</title>
</head>
<body>
    <h2>Welcome to My First JSP Program!</h2>
    <% 
        // Declaring a simple variable
        String userName = "User";
        // Getting the current date and time
        java.util.Date currentDate = new java.util.Date();
    %>
    <p>Hello, <%= userName %>!</p>
    <p>Current Date and Time: <%= currentDate %></p>
</body>
</html>
import java.sql.*;

public class ScrollableUpdatableResultSetExample {
    public static void main(String[] args) {
        // Database connection variables
        String url = "jdbc:oracle:thin:@localhost:1521:xe";  // Replace 'orcl' with your DB service name
        String username = "system"; // Oracle username
        String password = "1234";  // Oracle password
        
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        
        try {
            // Step 1: Load Oracle JDBC driver
            Class.forName("oracle.jdbc.OracleDriver");

            // Step 2: Establish a connection
            connection = DriverManager.getConnection(url, username, password);

            // Step 3: Create a statement with scrollable and updatable ResultSet
            statement = connection.createStatement(
                    ResultSet.TYPE_SCROLL_INSENSITIVE, // Scrollable
                    ResultSet.CONCUR_UPDATABLE          // Updatable
            );

            // Step 4: Execute the query to retrieve employees
            String query = "SELECT name, salary FROM employee";
            resultSet = statement.executeQuery(query);

            // Step 5: Scroll through the result set and update a record
            // Move to the first record
            if (resultSet.next()) {
                System.out.println("First Employee: " + resultSet.getString("name") + ", " 
                        + resultSet.getDouble("salary"));

                // Move to the second record
                if (resultSet.next()) {
                    System.out.println("Second Employee: " + resultSet.getString("name") + ", " 
                            + resultSet.getDouble("salary"));

                    // Update the salary of the second employee
                    resultSet.updateDouble("salary", resultSet.getDouble("salary") + 500); // Increase salary by 500
                    resultSet.updateRow(); // Apply the changes

                    System.out.println("Updated Salary for Second Employee: " + resultSet.getDouble("salary"));
                }
            }

            // Step 6: Commit changes (optional, if auto-commit is off)
            connection.commit();

        } catch (SQLException | ClassNotFoundException e) {
            // Handle SQL and ClassNotFound exceptions
            e.printStackTrace();
        } finally {
            // Step 7: Clean up resources
            try {
                if (resultSet != null) resultSet.close();
                if (statement != null) statement.close();
                if (connection != null) connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
#include <stdio.h>
#include <string.h>

void encrypt(char *text, int key) {
    for (int i = 0; text[i] != '\0'; i++) {
        // Encrypt uppercase letters
        if (text[i] >= 'A' && text[i] <= 'Z') {
            text[i] = (text[i] - 'A' + key) % 26 + 'A';
        }
        // Encrypt lowercase letters
        else if (text[i] >= 'a' && text[i] <= 'z') {
            text[i] = (text[i] - 'a' + key) % 26 + 'a';
        }
    }
}

void decrypt(char *text, int key) {
    // Decrypt by shifting in the opposite direction
    for (int i = 0; text[i] != '\0'; i++) {
        // Decrypt uppercase letters
        if (text[i] >= 'A' && text[i] <= 'Z') {
            text[i] = (text[i] - 'A' - key + 26) % 26 + 'A';  // +26 to handle negative
        }
        // Decrypt lowercase letters
        else if (text[i] >= 'a' && text[i] <= 'z') {
            text[i] = (text[i] - 'a' - key + 26) % 26 + 'a';  // +26 to handle negative
        }
    }
}

int main() {
    char text[100];
    int key;

    printf("Enter the text to encrypt: ");
    fgets(text, sizeof(text), stdin);
    text[strcspn(text, "\n")] = 0; // Remove trailing newline

    printf("Enter the encryption key (shift): ");
    scanf("%d", &key);

    encrypt(text, key);
    printf("Encrypted text: %s\n", text);

    decrypt(text, key);
    printf("Decrypted text: %s\n", text);

    return 0;
}

#include <stdio.h>

struct node {
    unsigned dist[20];
    unsigned from[20];
} rt[10];

int main() {
    int costmat[20][20];
    int nodes, i, j, k, count;

    printf("Enter the number of nodes: ");
    scanf("%d", &nodes);

    printf("Enter the cost matrix:\n");
    for (i = 0; i < nodes; i++) {
        for (j = 0; j < nodes; j++) {
            scanf("%d", &costmat[i][j]);
            rt[i].dist[j] = costmat[i][j]; // Initialize distance
            rt[i].from[j] = (costmat[i][j] != 0 && costmat[i][j] != 1000) ? j : -1; // Set 'from' based on cost
        }
    }

    // Set diagonal to 0
    for (i = 0; i < nodes; i++) {
        rt[i].dist[i] = 0;
        rt[i].from[i] = i;
    }

    // Floyd-Warshall Algorithm
    do {
        count = 0;
        for (i = 0; i < nodes; i++) {
            for (j = 0; j < nodes; j++) {
                for (k = 0; k < nodes; k++) {
                    if (rt[i].dist[j] > rt[i].dist[k] + rt[k].dist[j]) {
                        rt[i].dist[j] = rt[i].dist[k] + rt[k].dist[j];
                        rt[i].from[j] = k;
                        count++;
                    }
                }
            }
        }
    } while (count != 0);

    // Output the final routing table
    printf("\nUpdated routing table\n");
    for (i = 0; i < nodes; i++) {
        for (j = 0; j < nodes; j++) {
            if (rt[i].from[j] != -1) {
                printf("%d ", rt[i].dist[j]);
            } else {
                printf("inf ");  // Use "inf" to indicate no path
            }
        }
        printf("\n");
    }

    return 0;
}
#include<stdio.h>
int p,q,u,v,n;
int min=99;
int minCost=0;
int t[50][2],i,j;
int parent[50],edge[50][50];

int main(){
    clrsrc();
    printf("\nEnter the number of nodes");
    scanf("%d",&n);
    for(i=0;i<n;i++){
        printf("%d",i);
        parent[i]=-1;
    }
    printf("\n");
    for(i=0;i<n;i++){
        printf("%c",65+i);
        for(j=0;j<n;j++){
            scanf("%d",&edge[i][j]);
        }
        for(i=0;i<n;i++){
            for(j=0;j<n;j++){
                if(edge[1][j]!=99){
                    if(min<edge[i][j]){
                        min=edge[i][j];
                        u=i;
                        v=j;
                    }
                    p=find(u);
                    q=find(v);
                    
                    if(p!=q){
                        t[i][0]=u;
                        t[i][1]=v;
                        minCost =minCost+edge[u][v];
                        sunion(p,q);
                    }
                    else{
                        t[i][0]=-1;
                        t[i][1]=-1;
                    }
                }
            }
        }
        min = 99;
    }
    printf("Minimum cost is %d\n Minimum spanning tree is\n",minCost);
    for(i=0;i<n;i++){
        if(t[i][0]!=-1 && t[i][1]!=1){
            printf("%c %c %d",65+t[i][0],65+t[i][1],edge[t[i][0]] [t[i][1]]);
            printf("\n");
        }
        getch();
    }
    sunion(int I,int m){
        parent[] = m;
    }
    find(int I){
        if(parent[1]>0){
            I=parent[I];
        }
        return I;
    }
}
#include<stdio.h>
#include<stdbool.h>
#include<limits.h>
#define V 9

int minDistance(int dist[] ,bool sptset[]){
    int min = INT_MAX;  
    int min_index;
    for(int v=0;v<V;v++){
        if(sptset[v] == false && dist[v]<=min){
            min = dist[v];
            min_index = v;
        }
    }
    return min_index;
}

void printSolution(int dist[]){
    printf("Vertex\t\tDistance from source\n");
    for(int i=0;i<V;i++){
        printf("%d\t\t\t\t %d\n",i,dist[i]);
    }
}

void dijkstra(int graph[V][V],int src){
    int dist[V];
    bool sptset[V];
    for(int i=0;i<V;i++){
        dist[i] = INT_MAX;
        sptset[1]=false;
    }
    dist[src]=0;
    for(int count=0;count<V-1;count++){
        int u = minDistance(dist,sptset);
        sptset[u]=true;
        for(int v=0;v<V;v++){
            if(!sptset[v] && graph[u][v] && dist[u]!=INT_MAX && dist[u]+graph[u][v] < dist[v])
                dist[v] = dist[u]+graph[u][v];
        }
    }
    printSolution(dist);
}

int main(){
    int graph[V][V] = {{0,4,0,0,0,0,0,8,0},
               {4,0,8,0,0,0,0,11,0},
               {0,8,0,7,0,4,0,0,2},
               {0,0,7,0,9,14,0,0,0},
               {0,0,0,9,0,10,0,0,0},
               {0,0,4,14,10,0,2,0,0},
               {0,0,0,0,0,2,0,1,6},
               {8,11,0,0,0,0,1,0,7},
               {0,0,2,0,0,0,6,7,0}};
    dijkstra(graph,0);
    return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>

#define MAX_SEQ 4 // Maximum sequence number (0 to 7)
#define WINDOW_SIZE 4  // Size of the sliding window

// Packet structure
typedef struct {
    int seq_num;  // Sequence number
    bool ack;     // Acknowledgment flag
} Packet;

// Function prototypes
void sender();
void receiver();
void send_packet(Packet packet);
bool receive_packet(Packet packet);
bool simulate_packet_loss();

int main() {
    // Start sender and receiver (in a real implementation, these would run in separate threads or processes)
    sender();
    receiver();
    return 0;
}

void sender() {
    int next_seq_num = 0; // Next sequence number to send
    int acked = 0; // Last acknowledged packet
    int window_start = 0; // Start of the sliding window

    while (window_start <= MAX_SEQ) {
        // Send packets within the window
        while (next_seq_num < window_start + WINDOW_SIZE && next_seq_num <= MAX_SEQ) {
            Packet packet = {next_seq_num, false};
            send_packet(packet);
            next_seq_num++;
            sleep(1); // Simulate time taken to send a packet
        }

        // Simulate receiving an acknowledgment (in real systems this would be from the receiver)
        for (int i = acked; i < next_seq_num; i++) {
            if (receive_packet((Packet){i, true})) {
                acked++;
            }
        }

        // Slide the window
        window_start = acked;
        next_seq_num = window_start; // Move next_seq_num to the next unacknowledged packet
    }

    printf("Sender finished transmitting all packets.\n");
}

void receiver() {
    for (int i = 0; i <= MAX_SEQ; i++) {
        sleep(1); // Simulate processing time for receiving a packet
        if (simulate_packet_loss()) {
            printf("Receiver: Lost packet with seq_num %d\n", i);
            continue; // Simulate loss
        }
        printf("Receiver: Received packet with seq_num %d\n", i);
    }
}

void send_packet(Packet packet) {
    printf("Sender: Sending packet with seq_num %d\n", packet.seq_num);
}

bool receive_packet(Packet packet) {
    // Simulate acknowledgment logic
    if (packet.ack) {
        printf("Receiver: Acknowledgment for packet with seq_num %d\n", packet.seq_num);
        return true;
    }
    return false;
}

bool simulate_packet_loss() {
    // Randomly simulate packet loss (30% chance)
    return (rand() % 10) < 3;
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>University Demo</title>
    <style>
        /* Basic CSS styles for layout and appearance */
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f4f9;
        }
        header {
            background-color: #4CAF50;
            color: white;
            padding: 20px;
            text-align: center;
        }
        nav {
            background-color: #333;
            overflow: hidden;
        }
        nav a {
            float: left;
            display: block;
            color: white;
            padding: 14px 20px;
            text-align: center;
            text-decoration: none;
        }
        nav a:hover {
            background-color: #ddd;
            color: black;
        }
        section {
            padding: 20px;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        footer {
            background-color: #333;
            color: white;
            text-align: center;
            padding: 10px 0;
            position: fixed;
            width: 100%;
            bottom: 0;
        }
    </style>
</head>
<body>
    <header>
        <h1>Welcome to Our University</h1>
        <p>Empowering Future Leaders</p>
    </header>
    
    <nav>
        <a href="#about">About</a>
        <a href="#courses">Courses</a>
        <a href="#contact">Contact</a>
    </nav>

    <section id="about">
        <div class="container">
            <h2>About Us</h2>
            <p>Our University is dedicated to providing world-class education to students from all walks of life. We offer a wide range of academic programs designed to foster growth and leadership in our students.</p>
        </div>
    </section>

    <section id="courses">
        <div class="container">
            <h2>Our Courses</h2>
            <ul>
                <li>Bachelor of Science in Computer Science</li>
                <li>Master of Business Administration</li>
                <li>Bachelor of Arts in History</li>
                <li>PhD in Physics</li>
                <li>Master of Engineering in Civil</li>
            </ul>
        </div>
    </section>

    <section id="contact">
        <div class="container">
            <h2>Contact Us</h2>
            <p>Email: contact@university.com</p>
            <p>Phone: +123 456 7890</p>
            <p>Address: 123 University St, City, Country</p>
        </div>
    </section>

    <footer>
        <p>&copy; 2024 University Demo. All rights reserved.</p>
    </footer>
</body>
</html>
include <stdio.h>
#include <string.h>

#define MAX_LEN 28

char t[MAX_LEN], cs[MAX_LEN], g[MAX_LEN];
int a, e, c, b;

void xor() {
    for (c = 1; c < strlen(g); c++)
        cs[c] = ((cs[c] == g[c]) ? '0' : '1');
}

void crc() {
    for (e = 0; e < strlen(g); e++)
        cs[e] = t[e];
    
    do {
        if (cs[0] == '1') {
            xor();
        }
        
        for (c = 0; c < strlen(g) - 1; c++)
            cs[c] = cs[c + 1];
        
        cs[c] = t[e++];
    } while (e <= a + strlen(g) - 1);
}

int main() {
    int flag = 0;
    do {
        printf("\n1. CRC-12\n2. CRC-16\n3. CRC-CCITT\n4. Exit\n\nEnter your option: ");
        scanf("%d", &b);

        switch (b) {
            case 1: 
                strcpy(g, "1100000001111");
                break;
            case 2: 
                strcpy(g, "11000000000000101");
                break;
            case 3: 
                strcpy(g, "10001000000100001");
                break;
            case 4: 
                return 0;
            default:
                printf("Invalid option. Please try again.\n");
                continue;
        }

        printf("\nEnter data: ");
        scanf("%s", t);
        printf("\n-----------------------\n");
        printf("Generating polynomial: %s\n", g);
        a = strlen(t);

        // Append zeros to the data
        for (e = a; e < a + strlen(g) - 1; e++)
            t[e] = '0';
        t[e] = '\0';  // Null terminate the string

        printf("--------------------------\n");
        printf("Modified data is: %s\n", t);
        printf("-----------------------\n");
        crc();
        printf("Checksum is: %s\n", cs);
        
        // Prepare the final codeword
        for (e = a; e < a + strlen(g) - 1; e++)
            t[e] = cs[e - a];
        printf("-----------------------\n");
        printf("Final codeword is: %s\n", t);
        printf("------------------------\n");

        // Error detection option
        printf("Test error detection (0: yes, 1: no)?: ");
        scanf("%d", &e);
        if (e == 0) {
            do {
                printf("\n\tEnter the position where error is to be inserted: ");
                scanf("%d", &e);
            } while (e <= 0 || e > a + strlen(g) - 1);
            
            t[e - 1] = (t[e - 1] == '0') ? '1' : '0'; // Toggle the bit
            printf("-----------------------\n");
            printf("\nErroneous data: %s\n", t);
        }

        crc();
        for (e = 0; (e < strlen(g) - 1) && (cs[e] != '1'); e++);
        if (e < strlen(g) - 1)
            printf("Error detected\n\n");
        else
            printf("No error detected\n\n");
        
        printf("-----------------------\n");
    } while (flag != 1);

    return 0;
}


#include<stdio.h>
#include<string.h>

void bitStuffing(char *str) {
    int i, count = 0;
    char stuffedStr[100] = ""; // initialize an empty string to store the stuffed bits

    for (i = 0; i < strlen(str); i++) {
        if (str[i] == '1') {
            count++;
            if (count == 5) {
                strcat(stuffedStr, "0"); // stuff a '0' bit
                count = 0;
            }
        } else {
            count = 0;
        }
        char temp[2];
        sprintf(temp, "%c", str[i]);
        strcat(stuffedStr, temp);
    }

    printf("Original string: %s\n", str);
    printf("Bit-stuffed string: %s\n", stuffedStr);
}

int main() {
    char str[100];
    printf("Enter a binary string: ");
    scanf("%s", str);

    bitStuffing(str);

    return 0;
}
include <stdio.h>
#include <string.h>

#define FRAME_START 0x7E // Start of Frame
#define FRAME_END 0x7E   // End of Frame
#define STUFFING_CHAR 0x7D // Escape character
#define ESCAPED_CHAR 0x20  // Value to append after STUFFING_CHAR

void stuffCharacters(char *input, char *output) {
    int i, j = 0;
    int length = strlen(input);

    // Adding the frame start character
    output[j++] = FRAME_START;

    for (i = 0; i < length; i++) {
        if (input[i] == FRAME_START || input[i] == FRAME_END || input[i] == STUFFING_CHAR) {
            output[j++] = STUFFING_CHAR; // Stuffing character
            output[j++] = input[i] ^ ESCAPED_CHAR; // Escape the character
        } else {
            output[j++] = input[i]; // Normal character
        }
    }

    // Adding the frame end charactera
    output[j++] = FRAME_END;
    output[j] = '\0'; // Null-terminate the output string
}

void unstuffCharacters(char *input, char *output) {
    int i, j = 0;
    int length = strlen(input);

    // Skip frame start
    i = 1; 

    while (i < length - 1) { // Skip frame end
        if (input[i] == STUFFING_CHAR) {
            // Unstuffing character
            output[j++] = input[i + 1] ^ ESCAPED_CHAR;
            i += 2; // Move past the stuffed character
        } else {
            output[j++] = input[i++];
        }
    }

    output[j] = '\0'; // Null-terminate the output string
}

int main() {
    char input[256]; // Buffer for input message
    char stuffed[512]; // Buffer for stuffed message (larger to accommodate potential expansion)
    char unstuffed[256]; // Buffer for unstuffed message

    printf("Enter your message: ");
    fgets(input, sizeof(input), stdin); // Read input from the keyboard

    // Remove newline character if present
    input[strcspn(input, "\n")] = 0;

    printf("Original Message: %s\n", input);

    // Perform character stuffing
    stuffCharacters(input, stuffed);
    printf("Stuffed Message: ");
    for (int i = 0; stuffed[i] != '\0'; i++) {
        printf("%02X ", (unsigned char)stuffed[i]);
    }
    printf("\n");

    // Perform character unstuffing
    unstuffCharacters(stuffed, unstuffed);
    printf("Unstuffed Message: %s\n", unstuffed);

    return 0;
}

#include<stdio.h>
#include<string.h>

int main(){
    int n,i,j,c=0,count=0;
    char str[100]; 
    printf("Enter the string: ");
    scanf("%s", str); 

    printf("Enter the number of frames:");
    scanf("%d",&n);
    int frames[n];

    printf("Enter the frame size of the frames:\n");
    for(int i=0;i<n;i++){
        printf("Frame %d:",i);
        scanf("%d",&frames[i]);
    }

    printf("\nThe number of frames:%d\n",n);
    c = 0;
    for(int i=0;i<n;i++){
        printf("The content of the frame %d:",i);
        j=0;
        count = 0; 
        while(c < strlen(str) && j < frames[i]){
            printf("%c",str[c]);
            if(str[c]!='\0'){
                count++;
            }
            c=c+1;
            j=j+1;
        }
        printf("\nSize of frame %d: %d\n\n",i,count);
    }
    return 0;
}
/*
* Clears the keyboard if an invalid input was put in
*/
void clear_keyboard_buffer(void)
{
	char c = 'a';
	while (c != '\n')
	{
		scanf("%c", &c);
	}
	return;
}
/*
* Gets a user integer greater than a specified value
* @param int val
*		- The value that the user input is to be greater than 
*/
int get_user_greater_int(int val)
{
	int input, noc;
	printf("Enter an Interger Greater than %d: ", val);
	noc = scanf("%d", &input);
	clear_keyboard_buffer();

	while (noc != 1 || !(input >= 0))
	{
		printf("Invalid input\nEnter an Interger Greater than %d", val);
		noc = scanf("%d", &input);
		clear_keyboard_buffer();
	}

	return input;
}
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;

@WebServlet("/hello")
public class HelloWorldServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        response.getWriter().println("<h1>Hello, World!</h1>");
    }
}
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.ServletConfig;
import javax.servlet.annotation.WebServlet;

@WebServlet("/lifecycle")
public class LifecycleServlet implements javax.servlet.Servlet {
    public void init(ServletConfig config) throws ServletException {
        System.out.println("Servlet Initialized");
    }

    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        System.out.println("Servlet is servicing the request");
    }

    public void destroy() {
        System.out.println("Servlet Destroyed");
    }

    public ServletConfig getServletConfig() {
        return null;
    }

    public String getServletInfo() {
        return null;
    }
}
web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="3.0">
    <servlet>
        <servlet-name>LifecycleServlet</servlet-name>
        <servlet-class>LifecycleServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LifecycleServlet</servlet-name>
        <url-pattern>/lifecycle</url-pattern>
    </servlet-mapping>
</web-app>
import java.sql.*;

public class DatabaseMetadataExample {
    public static void main(String[] args) {
        try {
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database", "username", "password");
            DatabaseMetaData metaData = connection.getMetaData();
            
            System.out.println("Database Product Name: " + metaData.getDatabaseProductName());
            System.out.println("Database Product Version: " + metaData.getDatabaseProductVersion());
            System.out.println("Driver Name: " + metaData.getDriverName());
            System.out.println("Driver Version: " + metaData.getDriverVersion());
            
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.validation.*;
import java.io.File;

public class DOMXMLValidator {
    public static void main(String[] args) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new File("example.xml"));
            
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = schemaFactory.newSchema(new File("schema.xsd"));
            Validator validator = schema.newValidator();
            validator.validate(new DOMSource(doc));
            
            System.out.println("XML is valid.");
        } catch (Exception e) {
            System.out.println("XML is not valid: " + e.getMessage());
        }
    }
}
function greetUserPromise(name) {
    return new Promise((resolve) => {
        console.log(`Hi ${name}`);  
        resolve();
    });
}

function greetUserCallback(name, callback) {
    callback();
    console.log(`${name}`); 
}

function greetforCall() {
    console.log("Hello");
}

async function greetUserAsync() {
    try {
        await greetUserPromise("Arun");
        console.log("Hello Arun");
    } catch (error) {
        console.error("An error occurred:", error);
    }
}

greetUserAsync();

greetUserCallback("Arun", greetforCall);
int user_wishes_to_continue(void)
{
	char c;
	do
	{
		printf("Do you wish to continue? (Y/N)");
		scanf("%c", &c);
		clear_keyboard_buffer();
	} while (c != 'y' && c != 'Y' && c != 'n' && c != 'N');

	return (c == 'Y');
}

void clear_keyboard_buffer(void)
{
	char c = 'a';
	while (c != '\n')
	{
		scanf_s("%c", &c);
	}
	return;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Responsive Web Design</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

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


        header {
            background-color: #3498db;
            color: white;
            padding: 20px;
            text-align: center;
        }


        .container {
            padding: 20px;
        }


        .content {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 20px;
        }

        .content div {
            background-color: #2980b9;
            color: white;
            text-align: center;
            padding: 20px;
            border-radius: 8px;
        }

        @media (max-width: 768px) {
            .content {
                grid-template-columns: repeat(2, 1fr);

            }
        }


        @media (max-width: 480px) {
            .content {
                grid-template-columns: 1fr;

            }

            header {
                padding: 15px;

            }

            .content div {
                font-size: 14px;

            }
        }
    </style>
</head>

<body>
    <header>
        <h1>Responsive Web Design</h1>
    </header>

    <div class="container">
        <div class="content">
            <div>Item 1</div>
            <div>Item 2</div>
            <div>Item 3</div>
        </div>
    </div>
</body>

</html>
star

Sat Nov 16 2024 01:49:41 GMT+0000 (Coordinated Universal Time)

@login123

star

Sat Nov 16 2024 01:48:29 GMT+0000 (Coordinated Universal Time)

@login123

star

Sat Nov 16 2024 01:42:52 GMT+0000 (Coordinated Universal Time)

@login123

star

Sat Nov 16 2024 01:42:06 GMT+0000 (Coordinated Universal Time)

@login123

star

Sat Nov 16 2024 01:41:21 GMT+0000 (Coordinated Universal Time)

@login123

star

Sat Nov 16 2024 01:40:34 GMT+0000 (Coordinated Universal Time)

@login123

star

Sat Nov 16 2024 01:34:39 GMT+0000 (Coordinated Universal Time)

@login123

star

Sat Nov 16 2024 01:31:45 GMT+0000 (Coordinated Universal Time)

@login123

star

Sat Nov 16 2024 01:29:28 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Sat Nov 16 2024 01:05:55 GMT+0000 (Coordinated Universal Time)

@webtechnologies

star

Sat Nov 16 2024 00:37:53 GMT+0000 (Coordinated Universal Time)

@webtechnologies

star

Sat Nov 16 2024 00:27:34 GMT+0000 (Coordinated Universal Time)

@webtechnologies

star

Fri Nov 15 2024 20:49:33 GMT+0000 (Coordinated Universal Time)

@CarlosR

star

Fri Nov 15 2024 20:38:46 GMT+0000 (Coordinated Universal Time)

@belleJar #groovy

star

Fri Nov 15 2024 20:18:16 GMT+0000 (Coordinated Universal Time)

@belleJar #groovy

star

Fri Nov 15 2024 19:40:18 GMT+0000 (Coordinated Universal Time)

@login123

star

Fri Nov 15 2024 19:30:27 GMT+0000 (Coordinated Universal Time)

@signup1

star

Fri Nov 15 2024 19:29:59 GMT+0000 (Coordinated Universal Time)

@signup1

star

Fri Nov 15 2024 19:29:34 GMT+0000 (Coordinated Universal Time)

@signup1

star

Fri Nov 15 2024 19:28:58 GMT+0000 (Coordinated Universal Time)

@signup1

star

Fri Nov 15 2024 19:08:56 GMT+0000 (Coordinated Universal Time)

@login123

star

Fri Nov 15 2024 19:07:47 GMT+0000 (Coordinated Universal Time)

@login123

star

Fri Nov 15 2024 19:04:10 GMT+0000 (Coordinated Universal Time)

@signup_returns

star

Fri Nov 15 2024 19:03:14 GMT+0000 (Coordinated Universal Time)

@login123

star

Fri Nov 15 2024 19:02:15 GMT+0000 (Coordinated Universal Time)

@signup_returns

star

Fri Nov 15 2024 19:01:18 GMT+0000 (Coordinated Universal Time)

@signup_returns

star

Fri Nov 15 2024 19:01:03 GMT+0000 (Coordinated Universal Time)

@login123

star

Fri Nov 15 2024 19:00:08 GMT+0000 (Coordinated Universal Time)

@signup_returns

star

Fri Nov 15 2024 18:50:38 GMT+0000 (Coordinated Universal Time)

@signup_returns

star

Fri Nov 15 2024 17:55:08 GMT+0000 (Coordinated Universal Time)

@coding1

star

Fri Nov 15 2024 17:54:36 GMT+0000 (Coordinated Universal Time)

@coding1

star

Fri Nov 15 2024 17:53:58 GMT+0000 (Coordinated Universal Time)

@coding1

star

Fri Nov 15 2024 17:53:26 GMT+0000 (Coordinated Universal Time)

@coding1

star

Fri Nov 15 2024 17:52:53 GMT+0000 (Coordinated Universal Time)

@coding1

star

Fri Nov 15 2024 17:52:46 GMT+0000 (Coordinated Universal Time)

@signup_returns

star

Fri Nov 15 2024 17:52:16 GMT+0000 (Coordinated Universal Time)

@coding1

star

Fri Nov 15 2024 17:51:43 GMT+0000 (Coordinated Universal Time)

@coding1

star

Fri Nov 15 2024 17:51:04 GMT+0000 (Coordinated Universal Time)

@coding1

star

Fri Nov 15 2024 17:50:13 GMT+0000 (Coordinated Universal Time)

@coding1

star

Fri Nov 15 2024 17:37:48 GMT+0000 (Coordinated Universal Time)

@Bantling21

star

Fri Nov 15 2024 17:37:17 GMT+0000 (Coordinated Universal Time)

@Bantling21

star

Fri Nov 15 2024 17:21:33 GMT+0000 (Coordinated Universal Time)

@webtechnologies

star

Fri Nov 15 2024 17:20:51 GMT+0000 (Coordinated Universal Time)

@webtechnologies

star

Fri Nov 15 2024 17:19:50 GMT+0000 (Coordinated Universal Time)

@webtechnologies

star

Fri Nov 15 2024 17:19:05 GMT+0000 (Coordinated Universal Time)

@webtechnologies

star

Fri Nov 15 2024 17:07:43 GMT+0000 (Coordinated Universal Time)

@Bantling21

star

Fri Nov 15 2024 17:06:58 GMT+0000 (Coordinated Universal Time)

@webtechnologies

Save snippets that work with our extensions

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