import java.sql.*;
public class JdbcDmlExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database_name"; // Replace with your database name
String user = "your_username"; // Replace with your database username
String password = "your_password"; // Replace with your database password
try (Connection conn = DriverManager.getConnection(url, user, password)) {
// Prepared Statement for Insert
String insertSQL = "INSERT INTO users (name, email) VALUES (?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(insertSQL)) {
pstmt.setString(1, "John Doe");
pstmt.setString(2, "john@example.com");
pstmt.executeUpdate();
System.out.println("User inserted successfully.");
}
// Prepared Statement for Update
String updateSQL = "UPDATE users SET email = ? WHERE name = ?";
try (PreparedStatement pstmt = conn.prepareStatement(updateSQL)) {
pstmt.setString(1, "john.doe@example.com");
pstmt.setString(2, "John Doe");
pstmt.executeUpdate();
System.out.println("User updated successfully.");
}
// Prepared Statement for Delete
String deleteSQL = "DELETE FROM users WHERE name = ?";
try (PreparedStatement pstmt = conn.prepareStatement(deleteSQL)) {
pstmt.setString(1, "John Doe");
pstmt.executeUpdate();
System.out.println("User deleted successfully.");
}
// Callable Statement for retrieving users
String callableSQL = "{CALL getAllUsers()}"; // Assume this stored procedure exists
try (CallableStatement cstmt = conn.prepareCall(callableSQL)) {
ResultSet rs = cstmt.executeQuery();
System.out.println("Users in the database:");
while (rs.next()) {
System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
How to Run the Java Program
Setup JDBC: Ensure you have the MySQL JDBC Driver in your classpath.
Create a Java File: Save the code above in a file named JdbcDmlExample.java.
Create the Database and Table: Ensure you have a database with a users table that has at least id, name, and email columns. Also, create a stored procedure getAllUsers to fetch users.
Compile and Run: Compile and run the Java program. Update the placeholders with your actual database connection details.
////////******* LOOPS IN JS ********///
// while loop
let index = 0
while(index <= 10){
console.log(`the value of index is ${index}`);
index = index+2;
}
let myarray = ["srk" , "salman khan" , "amir khan"]
let arr = 0
while(arr < myarray.length){
console.log(`value is ${myarray[arr]}`);
arr = arr +1
}
// do while loop
let score = 0
do{
console.log(`Score is ${score}`)
score++
}
while(score <= 10);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Design with CSS Units</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
}
.container {
max-width: 1200px; /* Maximum width using px */
margin: 0 auto; /* Center the container */
}
h1 {
font-size: 2rem; /* Font size using rem */
color: #333;
}
p {
font-size: 1em; /* Font size using em (relative to the parent) */
line-height: 1.5; /* Line height using unitless value */
}
.responsive-box {
width: 100%; /* Full width using % */
max-width: 600px; /* Max width using px */
padding: 20px; /* Padding using px */
margin: 20px auto; /* Margin using px */
background-color: #f0f0f0;
border: 1px solid #ccc;
box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1);
}
@media (max-width: 600px) {
h1 {
font-size: 1.5rem; /* Adjust font size for smaller screens */
}
}
</style>
</head>
<body>
<div class="container">
<h1>Responsive Design Using Different CSS Units</h1>
<p>This paragraph demonstrates the use of <strong>em</strong> and <strong>rem</strong> for font sizes. It will scale based on the user's default font size settings.</p>
<div class="responsive-box">
<p>This box adjusts its size and padding using a combination of CSS units. Resize the window to see how it responds!</p>
</div>
</div>
</body>
</html>
This Java application uses JDBC to connect to a MySQL database and demonstrate how to use updatable and scrollable result sets.
java
Copy code
import java.sql.*;
public class ScrollableUpdatableResultSet {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database_name"; // Replace with your database name
String user = "your_username"; // Replace with your database username
String password = "your_password"; // Replace with your database password
try (Connection conn = DriverManager.getConnection(url, user, password)) {
// Create a statement for updatable and scrollable result set
Statement stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE
);
// Execute query
ResultSet rs = stmt.executeQuery("SELECT * FROM users"); // Replace 'users' with your table name
// Move to the last row and display the last record
if (rs.last()) {
System.out.println("Last User ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
}
// Move to the first row
if (rs.first()) {
System.out.println("First User ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
// Update the first record
rs.updateString("name", "Updated Name");
rs.updateRow();
System.out.println("Updated User Name to 'Updated Name'.");
}
// Close the result set and statement
rs.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
How to Run the Java Application
Setup JDBC: Make sure you have the MySQL JDBC Driver in your classpath.
Create a Java File: Name it ScrollableUpdatableResultSet.java and copy the code above.
Compile and Run: Compile the Java program and run it. Ensure to replace the placeholders with your actual database connection details.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Bootstrap Grid</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h1 class="text-center my-4">Responsive Bootstrap Grid Example</h1>
<div class="row">
<div class="col-md-4 col-sm-6 mb-4">
<div class="card">
<div class="card-body">
<h5 class="card-title">Column 1</h5>
<p class="card-text">Content for column 1. This column is responsive.</p>
</div>
</div>
</div>
<div class="col-md-4 col-sm-6 mb-4">
<div class="card">
<div class="card-body">
<h5 class="card-title">Column 2</h5>
<p class="card-text">Content for column 2. This column is responsive.</p>
</div>
</div>
</div>
<div class="col-md-4 col-sm-12 mb-4">
<div class="card">
<div class="card-body">
<h5 class="card-title">Column 3</h5>
<p class="card-text">Content for column 3. This column is responsive.</p>
</div>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
import java.sql.*;
public class DatabaseMetadataExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database_name"; // Replace with your database URL
String user = "your_username"; // Replace with your database username
String password = "your_password"; // Replace with your database password
try (Connection conn = DriverManager.getConnection(url, user, password)) {
// Get Database Metadata
DatabaseMetaData metaData = conn.getMetaData();
// Print database information
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());
// Get and print tables
ResultSet tables = metaData.getTables(null, null, null, new String[]{"TABLE"});
System.out.println("\nTables in the database:");
while (tables.next()) {
System.out.println("Table Name: " + tables.getString("TABLE_NAME"));
}
tables.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Input Form</title>
</head>
<body>
<h1>User Input Form</h1>
<form action="processForm" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/processForm")
public class FormProcessorServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Retrieve request parameters
String name = request.getParameter("name");
String email = request.getParameter("email");
// Set response type
response.setContentType("text/html");
// Generate response
response.getWriter().println("<html><body>");
response.getWriter().println("<h1>Form Submission Successful</h1>");
response.getWriter().println("<p>Name: " + name + "</p>");
response.getWriter().println("<p>Email: " + email + "</p>");
response.getWriter().println("</body></html>");
}
}
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>FormProcessorServlet</servlet-name>
<servlet-class>FormProcessorServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FormProcessorServlet</servlet-name>
<url-pattern>/processForm</url-pattern>
</servlet-mapping>
</web-app>
How to Run the Example
Create a Dynamic Web Project: Use an IDE like Eclipse or IntelliJ to create a new Dynamic Web Project.
Add the HTML Form: Create an HTML file (e.g., form.html) and paste the form code into it. Place this file in the WebContent or root folder.
Add the Servlet: Create a new servlet class (FormProcessorServlet) and paste the servlet code into it.
Configure web.xml: If you are not using annotations, add the servlet configuration in the web.xml file located in the WEB-INF directory.
Run the Server: Deploy the project on a servlet container (like Apache Tomcat).
Access the Form: Open a web browser and navigate to http://localhost:8080/YourProjectName/form.html to access the form.
Submit the Form: Fill in the form and submit it. The servlet will process the input and display the name and email back to the user.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Landing Page</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
<style>
body {
background-color: #f8f9fa;
}
.hero-section {
background-color: #4CAF50; /* Green */
color: white;
padding: 100px 0;
}
</style>
</head>
<body>
<!-- Hero Section -->
<section class="hero-section text-center">
<div class="container">
<h1 class="display-4 mb-4">Welcome to Our Service</h1>
<p class="lead mb-5">Innovative solutions for your business.</p>
<a href="#" class="btn btn-light btn-lg">Get Started</a>
</div>
</section>
<!-- Features Section -->
<section class="py-5">
<div class="container text-center">
<h2 class="mb-4">Features</h2>
<div class="row">
<div class="col-md-4 mb-4"><h3>Feature One</h3><p>Description here.</p></div>
<div class="col-md-4 mb-4"><h3>Feature Two</h3><p>Description here.</p></div>
<div class="col-md-4 mb-4"><h3>Feature Three</h3><p>Description here.</p></div>
</div>
</div>
</section>
<!-- Call to Action -->
<section class="py-5 bg-light text-center">
<h2 class="mb-4">Ready to Get Started?</h2>
<a href="#" class="btn btn-primary btn-lg">Sign Up Now</a>
</section>
<!-- Footer -->
<footer class="py-4 bg-dark text-white text-center">
<p>© 2024 Your Company Name. All Rights Reserved.</p>
</footer>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
@WebServlet("/configDemo")
public class ConfigDemoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init(ServletConfig config) throws ServletException {
super.init(config);
// You can retrieve ServletConfig parameters here
String initParam = config.getInitParameter("exampleParam");
System.out.println("ServletConfig exampleParam: " + initParam);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String contextParam = getServletContext().getInitParameter("contextParam");
ServletContext context = getServletContext();
response.getWriter().println("<html><body>");
response.getWriter().println("<h1>ServletConfig and ServletContext Demo</h1>");
response.getWriter().println("<p>ServletConfig Parameter: " +
request.getServletContext().getInitParameter("contextParam") + "</p>");
response.getWriter().println("<p>ServletContext Parameter: " +
contextParam + "</p>");
response.getWriter().println("</body></html>");
}
}
web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>ConfigDemoServlet</servlet-name>
<servlet-class>ConfigDemoServlet</servlet-class>
<init-param>
<param-name>exampleParam</param-name>
<param-value>This is a ServletConfig parameter</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ConfigDemoServlet</servlet-name>
<url-pattern>/configDemo</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextParam</param-name>
<param-value>This is a ServletContext parameter</param-value>
</context-param>
</web-app>
////////******* LOOPS IN JS ********///
// for loop
for (let i = 1; i <= 10; i++) {
//console.log(`outer loop: ${i}`);
for (let j = 1; j <= 10; j++) {
// console.log(`${i} * ${j} = ${i * j}`);
}
}
// loops in array for printing elements
let myarray = ["srk" , "salman khan" , "amir khan"]
console.log(myarray.length);
for(let i = 0 ; i < myarray.length; i++){
const element = myarray[i];
console.log(element);
}
//// key words
// break keyword
for(let i = 0 ; i <= 10 ; i++){
if(i == 5){
console.log("number 5 is detected");
break
}
console.log(`the number is ${i}`);
}
// continue keyword
for(let i = 0 ; i <= 10 ; i++){
if(i == 5){
console.log("number 5 is detected");
continue
}
console.log(`the number is ${i}`);
}
Here's an example validation for registration, user login, user profile, and payment pages using JavaScript:
Registration Page Validation
// Registration form validation
const registerForm = document.getElementById('register-form');
registerForm.addEventListener('submit', (e) => {
e.preventDefault();
const username = document.getElementById('username').value.trim();
const email = document.getElementById('email').value.trim();
const password = document.getElementById('password').value.trim();
const confirmPassword = document.getElementById('confirm-password').value.trim();
if (username === '') {
alert('Username is required');
return;
}
if (email === '') {
alert('Email is required');
return;
}
if (!validateEmail(email)) {
alert('Invalid email format');
return;
}
if (password === '') {
alert('Password is required');
return;
}
if (password.length < 8) {
alert('Password must be at least 8 characters');
return;
}
if (password !== confirmPassword) {
alert('Passwords do not match');
return;
}
// Register user logic here
});
// Email validation function
function validateEmail(email) {
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
return emailRegex.test(email);
}
Login Page Validation
// Login form validation
const loginForm = document.getElementById('login-form');
loginForm.addEventListener('submit', (e) => {
e.preventDefault();
const email = document.getElementById('email').value.trim();
const password = document.getElementById('password').value.trim();
if (email === '') {
alert('Email is required');
return;
}
if (!validateEmail(email)) {
alert('Invalid email format');
return;
}
if (password === '') {
alert('Password is required');
return;
}
// Login user logic here
});
// Email validation function
function validateEmail(email) {
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
return emailRegex.test(email);
}
User Profile Validation
// Profile form validation
const profileForm = document.getElementById('profile-form');
profileForm.addEventListener('submit', (e) => {
e.preventDefault();
const name = document.getElementById('name').value.trim();
const email = document.getElementById('email').value.trim();
const phone = document.getElementById('phone').value.trim();
if (name === '') {
alert('Name is required');
return;
}
if (email === '') {
alert('Email is required');
return;
}
if (!validateEmail(email)) {
alert('Invalid email format');
return;
}
if (phone === '') {
alert('Phone number is required');
return;
}
if (!validatePhone(phone)) {
alert('Invalid phone number format');
return;
}
// Update profile logic here
});
// Email validation function
function validateEmail(email) {
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
return emailRegex.test(email);
}
// Phone number validation function
function validatePhone(phone) {
const phoneRegex = /^\d{3}-\d{3}-\d{4}$/;
return phoneRegex.test(phone);
}
Payment Page Validation
// Payment form validation
const paymentForm = document.getElementById('payment-form');
paymentForm.addEventListener('submit', (e) => {
e.preventDefault();
const cardNumber = document.getElementById('card-number').value.trim();
const expirationDate = document.getElementById('expiration-date').value.trim();
const cvv = document.getElementById('cvv').value.trim();
if (cardNumber === '') {
alert('Card number is required');
return;
}
if (!validateCardNumber(cardNumber)) {
alert('Invalid card number format');
return;
}
if (expirationDate === '') {
alert('Expiration date is required');
return;
}
if (!validateExpirationDate(expirationDate)) {
alert('Invalid expiration date format');
return;
}
if (cvv === '') {
alert('CVV is required');
return;
}
if (!validateCVV(cvv)) {
alert('Invalid CVV format');
return;
}
// Process payment logic here
});
// Card number validation function
function validateCardNumber(cardNumber) {
const cardNumberRegex = /^(\d{4}[- ]?){4}$/;
return cardNumberRegex.test(cardNumber);
}
// Expiration date validation
<!DOCTYPE html>
<html lang="en">
<head>
<title>Online Book Store</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
background-color: #f4f4f4;
}
header {
background-color: #333;
color: white;
padding: 15px;
text-align: center;
}
nav a {
color: white;
margin: 10px;
text-decoration: none;
}
.container {
display: none; /* Hide all sections initially */
padding: 20px;
}
.active {
display: block; /* Show the active section */
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
input[type="text"], input[type="email"], input[type="password"] {
width: 100%;
padding: 10px;
margin: 5px 0 10px;
border: 1px solid #ccc;
}
input[type="submit"] {
background-color: #4CAF50;
color: white;
padding: 10px;
border: none;
cursor: pointer;
width: 100%;
}
input[type="submit"]:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<header>
<h1>Online Book Store</h1>
<nav>
<a href="#" onclick="showSection('home')">Home</a>
<a href="#" onclick="showSection('login')">Login</a>
<a href="#" onclick="showSection('catalogue')">Catalogue</a>
<a href="#" onclick="showSection('registration')">Register</a>
</nav>
</header>
<div id="home" class="container active">
<h2>Welcome to the Online Book Store!</h2>
<p>Find your favorite books here.</p>
</div>
<div id="login" class="container">
<h2>Login</h2>
<form action="#">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<input type="submit" value="Login">
</form>
</div>
<div id="catalogue" class="container">
<h2>Book Catalogue</h2>
<table>
<thead>
<tr>
<th>Book Title</th>
<th>Author</th>
<th>Price</th>
<th>Availability</th>
</tr>
</thead>
<tbody>
<tr>
<td>The Great Gatsby</td>
<td>F. Scott Fitzgerald</td>
<td>$10.99</td>
<td>In Stock</td>
</tr>
<tr>
<td>1984</td>
<td>George Orwell</td>
<td>$8.99</td>
<td>In Stock</td>
</tr>
<tr>
<td>To Kill a Mockingbird</td>
<td>Harper Lee</td>
<td>$12.99</td>
<td>Out of Stock</td>
</tr>
<tr>
<td>Pride and Prejudice</td>
<td>Jane Austen</td>
<td>$7.99</td>
<td>In Stock</td>
</tr>
</tbody>
</table>
</div>
<div id="registration" class="container">
<h2>Registration</h2>
<form action="#">
<label for="new-username">Username:</label>
<input type="text" id="new-username" name="username" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="new-password">Password:</label>
<input type="password" id="new-password" name="password" required>
<input type="submit" value="Register">
</form>
</div>
<script>
function showSection(sectionId) {
const sections = document.querySelectorAll('.container');
sections.forEach(section => {
section.classList.remove('active'); // Hide all sections
});
document.getElementById(sectionId).classList.add('active'); // Show the selected section
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Minimal Responsive Website</title>
<style>
body {
margin: 0;
font-family: Arial, sans-serif;
}
header, footer {
background: #4CAF50;
color: white;
text-align: center;
padding: 10px 0;
}
nav {
background: #333;
text-align: center;
}
nav a {
color: white;
padding: 10px;
text-decoration: none;
display: inline-block;
}
.container {
padding: 10px;
}
.box {
border: 1px solid #ccc;
margin: 10px 0;
padding: 10px;
text-align: center;
}
/* Media Queries */
@media (min-width: 600px) {
.box {
display: inline-block;
width: calc(33% - 20px);
margin: 10px;
}
}
</style>
</head>
<body>
<header>
<h1>Responsive Website</h1>
</header>
<nav>
<a href="#home">Home</a>
<a href="#about">About</a>
<a href="#services">Services</a>
<a href="#contact">Contact</a>
</nav>
<div class="container">
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
</div>
<footer>
<p>Footer © 2024</p>
</footer>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Pop-Up Examples</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
button {
margin: 10px 0;
padding: 10px 15px;
font-size: 16px;
}
input[type="text"] {
margin-top: 10px;
width: 200px;
padding: 10px;
}
</style>
</head>
<body>
<h1>JavaScript Pop-Up Examples</h1>
<h2>Display Current Date</h2>
<button onclick="displayDate()">Display Date</button>
<input type="text" id="dateOutput" placeholder="Date will be displayed here" readonly>
<!-- b) Factorial -->
<h2>Calculate Factorial</h2>
<button onclick="calculateFactorial()">Calculate Factorial</button>
<!-- c) Multiplication Table -->
<h2>Multiplication Table</h2>
<button onclick="multiplicationTable()">Show Multiplication Table</button>
<script>
// Function a: Display current date in the textbox
function displayDate() {
const date = new Date();
document.getElementById('dateOutput').value = date.toLocaleString();
}
// Function b: Calculate factorial of a number
function calculateFactorial() {
const n = prompt("Enter a number to calculate its factorial:");
if (n === null || n === "" || isNaN(n) || n < 0) {
alert("Please enter a valid non-negative number.");
return;
}
let factorial = 1;
for (let i = 1; i <= n; i++) {
factorial *= i;
}
alert(`Factorial of ${n} is ${factorial}`);
}
// Function c: Show multiplication table of a number
function multiplicationTable() {
const n = prompt("Enter a number to see its multiplication table:");
if (n === null || n === "" || isNaN(n)) {
alert("Please enter a valid number.");
return;
}
let table = `Multiplication Table of ${n}:\n`;
for (let i = 1; i <= 10; i++) {
table += `${n} x ${i} = ${n * i}\n`;
}
alert(table);
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>CSS Grid and Flexbox</title>
<style>
body {
font-family: Arial, sans-serif;
}
.header, .footer {
display: flex;
justify-content: center;
align-items: center;
background: #4CAF50;
color: #fff;
height: 60px;
}
.content {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
padding: 20px;
}
.box {
padding: 20px;
background: #2196F3;
color: #fff;
text-align: center;
transition: transform 0.3s;
}
.box:hover { transform: scale(1.05); background: #1E88E5; }
</style>
</head>
<body>
<div class="header">Header</div>
<div class="content">
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
</div>
<div class="footer">Footer</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Data Attribute Example</title>
<style>
.item { cursor: pointer; margin: 10px 0; }
</style>
</head>
<body>
<h2>Product List</h2>
<div class="item" data-description="A fresh apple from the orchard" onclick="showDetails(this)">Apple</div>
<div class="item" data-description="A ripe, sweet banana" onclick="showDetails(this)">Banana</div>
<div class="item" data-description="A juicy bunch of grapes" onclick="showDetails(this)">Grapes</div>
<h3>Details:</h3>
<p id="details"></p>
<script>
function showDetails(element) {
const description = element.getAttribute("data-description");
document.getElementById("details").textContent = description;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Simple Responsive Flexbox Layout</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
height: 100vh;
}
header, footer {
background: #35424a;
color: white;
text-align: center;
padding: 10px 0;
}
.container {
display: flex;
flex: 1; /* Take remaining space */
padding: 20px;
gap: 20px; /* Space between items */
}
main {
flex: 3; /* Main content takes more space */
background: white;
padding: 20px;
border-radius: 5px;
}
aside {
flex: 1; /* Sidebar takes less space */
background: #e7e7e7;
padding: 20px;
border-radius: 5px;
}
/* Responsive Styles */
</style>
</head>
<body>
<header>
<h1>Responsive Flexbox Layout</h1>
</header>
<div class="container">
<main>
<h2>Main Content</h2>
<p>This is the main content area. You can place your articles, images, or other important information here.</p>
</main>
<aside>
<h2>Sidebar</h2>
<p>This is a sidebar. You can add additional links, ads, or other content here.</p>
</aside>
</div>
<footer>
<p>© 2024 Your Website. All rights reserved.</p>
</footer>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Interactive CSS3 Animations</title>
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
background-color: #f4f4f4;
margin: 0;
}
.box {
width: 100px;
height: 100px;
background-color: #3498db;
transition: transform 0.3s, background-color 0.3s;
}
.box:hover {
background-color: #2980b9;
transform: scale(1.1);
}
button {
margin-top: 20px;
padding: 10px 20px;
background-color: #e67e22;
color: white;
border: none;
cursor: pointer;
}
.move {
animation: move 1s forwards;
}
@keyframes move {
from { transform: translateX(0); }
to { transform: translateX(200px); }
}
</style>
</head>
<body>
<div class="box" id="box"></div>
<button id="moveBtn">Move Box</button>
<script>
const box = document.getElementById('box');
const moveBtn = document.getElementById('moveBtn');
moveBtn.addEventListener('click', () => {
box.classList.toggle('move');
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Canvas Drawing App</title>
<style>
canvas { border: 1px solid black; }
</style>
</head>
<body>
<h2>Drawing App</h2>
<canvas id="drawCanvas" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById("drawCanvas");
const ctx = canvas.getContext("2d");
let drawing = false;
canvas.addEventListener("mousedown", () => drawing = true);
canvas.addEventListener("mouseup", () => drawing = false);
canvas.addEventListener("mousemove", draw);
function draw(event) {
if (!drawing) return;
ctx.lineWidth = 2;
ctx.lineCap = "round";
ctx.strokeStyle = "black";
ctx.lineTo(event.clientX - canvas.offsetLeft, event.clientY - canvas.offsetTop);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(event.clientX - canvas.offsetLeft, event.clientY - canvas.offsetTop);
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Scientific Calculator</title>
</head>
<body>
<h2>Scientific Calculator</h2>
<input type="text" id="display" readonly>
<br>
<button onclick="clearDisplay()">C</button>
<button onclick="appendToDisplay('7')">7</button>
<button onclick="appendToDisplay('8')">8</button>
<button onclick="appendToDisplay('9')">9</button>
<button onclick="appendToDisplay('/')">/</button>
<br>
<button onclick="appendToDisplay('4')">4</button>
<button onclick="appendToDisplay('5')">5</button>
<button onclick="appendToDisplay('6')">6</button>
<button onclick="appendToDisplay('')"></button>
<br>
<button onclick="appendToDisplay('1')">1</button>
<button onclick="appendToDisplay('2')">2</button>
<button onclick="appendToDisplay('3')">3</button>
<button onclick="appendToDisplay('-')">-</button>
<br>
<button onclick="appendToDisplay('0')">0</button>
<button onclick="calculate()">=</button>
<button onclick="appendToDisplay('+')">+</button>
<br>
<button onclick="appendToDisplay('Math.sqrt(')">√</button>
<button onclick="appendToDisplay('Math.pow(')">^</button>
<button onclick="appendToDisplay('Math.sin(')">sin</button>
<button onclick="appendToDisplay('Math.cos(')">cos</button>
<script>
function appendToDisplay(value) {
document.getElementById("display").value += value;
}
function clearDisplay() {
document.getElementById("display").value = "";
}
function calculate() {
try {
document.getElementById("display").value = eval(document.getElementById("display").value);
} catch {
document.getElementById("display").value = "Error";
}
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Customized Bootstrap Theme</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
<style>
/* Custom Theme Colors */
:root {
--primary-color: #4CAF50; /* Green */
--secondary-color: #FF5722; /* Orange */
}
body {
background-color: #f8f9fa;
}
.btn-custom {
background-color: var(--primary-color);
color: white;
border-radius: 30px;
}
.btn-custom:hover {
background-color: var(--secondary-color);
}
.form-control-custom {
border: 2px solid var(--primary-color);
border-radius: 10px;
}
.form-control-custom:focus {
border-color: var(--secondary-color);
box-shadow: 0 0 5px var(--secondary-color);
}
h1, h2 {
color: var(--primary-color);
}
</style>
</head>
<body>
<!-- Navigation Bar -->
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Brand Logo</a>
<div class="collapse navbar-collapse">
<ul class="navbar-nav">
<li class="nav-item active"><a class="nav-link" href="#">Home</a></li>
<li class="nav-item"><a class="nav-link" href="#">About</a></li>
<li class="nav-item"><a class="nav-link" href="#">Contact</a></li>
</ul>
</div>
</nav>
<div class="container mt-5">
<h1>Welcome!</h1>
<button class="btn btn-custom">Get Started</button>
<h2 class="mt-5">Sign Up</h2>
<form>
<input type="text" class="form-control form-control-custom" placeholder="Name">
<input type="email" class="form-control form-control-custom mt-3" placeholder="Email">
<input type="password" class="form-control form-control-custom mt-3" placeholder="Password">
<button type="submit" class="btn btn-custom mt-3">Submit</button>
</form>
</div>
<!-- Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bootstrap Example</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<!-- Navigation Bar -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
<a class="navbar-brand" href="#">My Website</a>
<div class="collapse navbar-collapse">
<ul class="navbar-nav">
<li class="nav-item active"><a class="nav-link" href="#">Home</a></li>
<li class="nav-item"><a class="nav-link" href="#" data-toggle="modal" data-target="#myModal">Open Modal</a></li>
<li class="nav-item"><a class="nav-link" href="#cards">Cards</a></li>
</ul>
</div>
</nav>
<!-- Main Content -->
<div class="container mt-5">
<h1>Welcome to My Bootstrap Website!</h1>
<div id="cards" class="row mt-3">
<div class="col-md-4">
<div class="card mb-4"><img src="https://via.placeholder.com/350" class="card-img-top" alt="Card image">
<div class="card-body">
<h5 class="card-title">Card 1</h5>
<p class="card-text">Description for Card 1.</p>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-4"><img src="https://via.placeholder.com/350" class="card-img-top" alt="Card image">
<div class="card-body">
<h5 class="card-title">Card 2</h5>
<p class="card-text">Description for Card 2.</p>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-4"><img src="https://via.placeholder.com/350" class="card-img-top" alt="Card image">
<div class="card-body">
<h5 class="card-title">Card 3</h5>
<p class="card-text">Description for Card 3.</p>
</div>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal title</h5>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body"><p>This is a simple modal example.</p></div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<library>
<book>
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<isbn>9780743273565</isbn>
<publisher>Scribner</publisher>
<edition>1st</edition>
<price>10.99</price>
</book>
<book>
<title>To Kill a Mockingbird</title>
<author>Harper Lee</author>
<isbn>9780061120084</isbn>
<publisher>Harper Perennial</publisher>
<edition>50th Anniversary Edition</edition>
<price>7.99</price>
</book>
<book>
<title>1984</title>
<author>George Orwell</author>
<isbn>9780451524935</isbn>
<publisher>Signet Classic</publisher>
<edition>Plume Edition</edition>
<price>9.99</price>
</book>
</library>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Multimedia Page</title>
</head>
<body>
<h2>Multimedia Page</h2>
<h3>Video Player</h3>
<video width="320" height="240" controls>
<source src="1.mp4" type="video/mp4">
</video>
<h3>Audio Player</h3>
<audio controls>
<source src="audio.mp3" type="audio/mpeg">
</audio>
</body>
</html>
// SICP JS 4.1.4
// functions from SICP JS 4.1.1
function evaluate(component, env) {
return is_literal(component)
? literal_value(component)
: is_name(component)
? lookup_symbol_value(symbol_of_name(component), env)
: is_application(component)
? apply(evaluate(function_expression(component), env),
list_of_values(arg_expressions(component), env))
: is_operator_combination(component)
? evaluate(operator_combination_to_application(component),
env)
: is_conditional(component)
? eval_conditional(component, env)
: is_lambda_expression(component)
? make_function(lambda_parameter_symbols(component),
lambda_body(component), env)
: is_sequence(component)
? eval_sequence(sequence_statements(component), env)
: is_block(component)
? eval_block(component, env)
: is_return_statement(component)
? eval_return_statement(component, env)
: is_function_declaration(component)
? evaluate(function_decl_to_constant_decl(component), env)
: is_declaration(component)
? eval_declaration(component, env)
: is_assignment(component)
? eval_assignment(component, env)
: error(component, "unknown syntax -- evaluate");
}
function apply(fun, args) {
if (is_primitive_function(fun)) {
return apply_primitive_function(fun, args);
} else if (is_compound_function(fun)) {
const result = evaluate(function_body(fun),
extend_environment(
function_parameters(fun),
args,
function_environment(fun)));
return is_return_value(result)
? return_value_content(result)
: undefined;
} else {
error(fun, "unknown function type -- apply");
}
}
function list_of_values(exps, env) {
return map(arg => evaluate(arg, env), exps);
}
function eval_conditional(component, env) {
return is_truthy(evaluate(conditional_predicate(component), env))
? evaluate(conditional_consequent(component), env)
: evaluate(conditional_alternative(component), env);
}
function eval_sequence(stmts, env) {
if (is_empty_sequence(stmts)) {
return undefined;
} else if (is_last_statement(stmts)) {
return evaluate(first_statement(stmts), env);
} else {
const first_stmt_value =
evaluate(first_statement(stmts), env);
if (is_return_value(first_stmt_value)) {
return first_stmt_value;
} else {
return eval_sequence(rest_statements(stmts), env);
}
}
}
function scan_out_declarations(component) {
return is_sequence(component)
? accumulate(append,
null,
map(scan_out_declarations,
sequence_statements(component)))
: is_declaration(component)
? list(declaration_symbol(component))
: null;
}
function eval_block(component, env) {
const body = block_body(component);
const locals = scan_out_declarations(body);
const unassigneds = list_of_unassigned(locals);
return evaluate(body, extend_environment(locals,
unassigneds,
env));
}
function list_of_unassigned(symbols) {
return map(symbol => "*unassigned*", symbols);
}
function eval_return_statement(component, env) {
return make_return_value(evaluate(return_expression(component),
env));
}
function eval_assignment(component, env) {
const value = evaluate(assignment_value_expression(component),
env);
assign_symbol_value(assignment_symbol(component), value, env);
return value;
}
function eval_declaration(component, env) {
assign_symbol_value(
declaration_symbol(component),
evaluate(declaration_value_expression(component), env),
env);
return undefined;
}
// functions from SICP JS 4.1.2
function is_tagged_list(component, the_tag) {
return is_pair(component) && head(component) === the_tag;
}
function is_literal(component) {
return is_tagged_list(component, "literal");
}
function literal_value(component) {
return head(tail(component));
}
function make_literal(value) {
return list("literal", value);
}
function is_name(component) {
return is_tagged_list(component, "name");
}
function make_name(symbol) {
return list("name", symbol);
}
function symbol_of_name(component) {
return head(tail(component));
}
function is_assignment(component) {
return is_tagged_list(component, "assignment");
}
function assignment_symbol(component) {
return head(tail(head(tail(component))));
}
function assignment_value_expression(component) {
return head(tail(tail(component)));
}
function is_declaration(component) {
return is_tagged_list(component, "constant_declaration") ||
is_tagged_list(component, "variable_declaration") ||
is_tagged_list(component, "function_declaration");
}
function declaration_symbol(component) {
return symbol_of_name(head(tail(component)));
}
function declaration_value_expression(component) {
return head(tail(tail(component)));
}
function make_constant_declaration(name, value_expression) {
return list("constant_declaration", name, value_expression);
}
function is_lambda_expression(component) {
return is_tagged_list(component, "lambda_expression");
}
function lambda_parameter_symbols(component) {
return map(symbol_of_name, head(tail(component)));
}
function lambda_body(component) {
return head(tail(tail(component)));
}
function make_lambda_expression(parameters, body) {
return list("lambda_expression", parameters, body);
}
function is_function_declaration(component) {
return is_tagged_list(component, "function_declaration");
}
function function_declaration_name(component) {
return list_ref(component, 1);
}
function function_declaration_parameters(component) {
return list_ref(component, 2);
}
function function_declaration_body(component) {
return list_ref(component, 3);
}
function function_decl_to_constant_decl(component) {
return make_constant_declaration(
function_declaration_name(component),
make_lambda_expression(
function_declaration_parameters(component),
function_declaration_body(component)));
}
function is_return_statement(component) {
return is_tagged_list(component, "return_statement");
}
function return_expression(component) {
return head(tail(component));
}
function is_conditional(component) {
return is_tagged_list(component, "conditional_expression") ||
is_tagged_list(component, "conditional_statement");
}
function conditional_predicate(component) {
return list_ref(component, 1);
}
function conditional_consequent(component) {
return list_ref(component, 2);
}
function conditional_alternative(component) {
return list_ref(component, 3);
}
function is_sequence(stmt) {
return is_tagged_list(stmt, "sequence");
}
function sequence_statements(stmt) {
return head(tail(stmt));
}
function first_statement(stmts) {
return head(stmts);
}
function rest_statements(stmts) {
return tail(stmts);
}
function is_empty_sequence(stmts) {
return is_null(stmts);
}
function is_last_statement(stmts) {
return is_null(tail(stmts));
}
function is_block(component) {
return is_tagged_list(component, "block");
}
function block_body(component) {
return head(tail(component));
}
function make_block(statement) {
return list("block", statement);
}
function is_operator_combination(component) {
return is_unary_operator_combination(component) ||
is_binary_operator_combination(component);
}
function is_unary_operator_combination(component) {
return is_tagged_list(component, "unary_operator_combination");
}
function is_binary_operator_combination(component) {
return is_tagged_list(component, "binary_operator_combination");
}
function operator_symbol(component) {
return list_ref(component, 1);
}
function first_operand(component) {
return list_ref(component, 2);
}
function second_operand(component) {
return list_ref(component, 3);
}
function make_application(function_expression, argument_expressions) {
return list("application",
function_expression, argument_expressions);
}
function operator_combination_to_application(component) {
const operator = operator_symbol(component);
return is_unary_operator_combination(component)
? make_application(make_name(operator),
list(first_operand(component)))
: make_application(make_name(operator),
list(first_operand(component),
second_operand(component)));
}
function is_application(component) {
return is_tagged_list(component, "application");
}
function function_expression(component) {
return head(tail(component));
}
function arg_expressions(component) {
return head(tail(tail(component)));
}
// functions from SICP JS 4.1.3
function is_truthy(x) {
return is_boolean(x)
? x
: error(x, "boolean expected, received");
}
function is_falsy(x) { return ! is_truthy(x); }
function make_function(parameters, body, env) {
return list("compound_function", parameters, body, env);
}
function is_compound_function(f) {
return is_tagged_list(f, "compound_function");
}
function function_parameters(f) { return list_ref(f, 1); }
function function_body(f) { return list_ref(f, 2); }
function function_environment(f) { return list_ref(f, 3); }
function make_return_value(content) {
return list("return_value", content);
}
function is_return_value(value) {
return is_tagged_list(value, "return_value");
}
function return_value_content(value) {
return head(tail(value));
}
function enclosing_environment(env) { return tail(env); }
function first_frame(env) { return head(env); }
const the_empty_environment = null;
function make_frame(symbols, values) { return pair(symbols, values); }
function frame_symbols(frame) { return head(frame); }
function frame_values(frame) { return tail(frame); }
function extend_environment(symbols, vals, base_env) {
return length(symbols) === length(vals)
? pair(make_frame(symbols, vals), base_env)
: length(symbols) > length(vals)
? error("too many arguments supplied: " +
stringify(symbols) + ", " +
stringify(vals))
: error("too few arguments supplied: " +
stringify(symbols) + ", " +
stringify(vals));
}
function lookup_symbol_value(symbol, env) {
function env_loop(env) {
function scan(symbols, vals) {
return is_null(symbols)
? env_loop(enclosing_environment(env))
: symbol === head(symbols)
? head(vals)
: scan(tail(symbols), tail(vals));
}
if (env === the_empty_environment) {
error(symbol, "unbound name");
} else {
const frame = first_frame(env);
return scan(frame_symbols(frame), frame_values(frame));
}
}
return env_loop(env);
}
function assign_symbol_value(symbol, val, env) {
function env_loop(env) {
function scan(symbols, vals) {
return is_null(symbols)
? env_loop(enclosing_environment(env))
: symbol === head(symbols)
? set_head(vals, val)
: scan(tail(symbols), tail(vals));
}
if (env === the_empty_environment) {
error(symbol, "unbound name -- assignment");
} else {
const frame = first_frame(env);
return scan(frame_symbols(frame), frame_values(frame));
}
}
return env_loop(env);
}
// functions from SICP JS 4.1.4
function is_primitive_function(fun) {
return is_tagged_list(fun, "primitive");
}
function primitive_implementation(fun) { return head(tail(fun)); }
function modified_greater_than(x,y){ //CHANGED: ADDED modifed_greater_than function
if ((is_primitive_function(x) || is_compound_function(x)) && is_list(y)){
return map(p => apply(x, list(p)), y);
} else {
return x > y;
}
}
const primitive_functions = list(
list("head", head ),
list("tail", tail ),
list("pair", pair ),
list("list", list ),
list("is_null", is_null ),
list("display", display ),
list("error", error ),
list("math_abs",math_abs ),
list("+", (x, y) => x + y ),
list("-", (x, y) => x - y ),
list("-unary", x => - x ),
list("*", (x, y) => x * y ),
list("/", (x, y) => x / y ),
list("%", (x, y) => x % y ),
list("===", (x, y) => x === y),
list("!==", (x, y) => x !== y),
list(">", modified_greater_than),//CHANGED: replaced previous call with modified_greater_than
list(">=", (x, y) => x >= y),
list(">", (x, y) => x > y),
list(">=", (x, y) => x >= y),
list("!", x => ! x)
);
const primitive_function_symbols =
map(head, primitive_functions);
const primitive_function_objects =
map(fun => list("primitive", head(tail(fun))),
primitive_functions);
const primitive_constants = list(list("undefined", undefined),
list("Infinity", Infinity),
list("math_PI", math_PI),
list("math_E", math_E),
list("NaN", NaN)
);
const primitive_constant_symbols =
map(c => head(c), primitive_constants);
const primitive_constant_values =
map(c => head(tail(c)), primitive_constants);
function apply_primitive_function(fun, arglist) {
return apply_in_underlying_javascript(
primitive_implementation(fun), arglist);
}
function setup_environment() {
return extend_environment(append(primitive_function_symbols,
primitive_constant_symbols),
append(primitive_function_objects,
primitive_constant_values),
the_empty_environment);
}
const the_global_environment = setup_environment();
function parse_and_evaluate(p) {
// wrap the program in a block: the program block
return evaluate(parse("{ " + p + " }"),
the_global_environment);
}
// Use this evaluator in the Programmable REPL
set_evaluator(parse_and_evaluate);
// SICP JS 4.1.4
// functions from SICP JS 4.1.1
function evaluate(component, env) {
return is_literal(component)
? literal_value(component)
: is_name(component)
? lookup_symbol_value(symbol_of_name(component), env)
: is_application(component)
? apply(evaluate(function_expression(component), env),
list_of_values(arg_expressions(component), env))
: is_operator_combination(component)
? evaluate(operator_combination_to_application(component),
env)
: is_conditional(component)
? eval_conditional(component, env)
: is_lambda_expression(component)
? make_function(lambda_parameter_symbols(component),
lambda_body(component), env)
: is_sequence(component)
? eval_sequence(sequence_statements(component), env)
: is_block(component)
? eval_block(component, env)
: is_return_statement(component)
? eval_return_statement(component, env)
: is_function_declaration(component)
? evaluate(function_decl_to_constant_decl(component), env)
: is_declaration(component)
? eval_declaration(component, env)
: is_assignment(component)
? eval_assignment(component, env)
: error(component, "unknown syntax -- evaluate");
}
function apply(fun, args) {
if (is_primitive_function(fun)) {
return apply_primitive_function(fun, args);
} else if (is_compound_function(fun)) {
const result = evaluate(function_body(fun),
extend_environment(
function_parameters(fun),
args,
function_environment(fun)));
return is_return_value(result)
? return_value_content(result)
: undefined;
} else {
error(fun, "unknown function type -- apply");
}
}
function list_of_values(exps, env) {
return map(arg => evaluate(arg, env), exps);
}
function eval_conditional(component, env) {
return is_truthy(evaluate(conditional_predicate(component), env))
? evaluate(conditional_consequent(component), env)
: evaluate(conditional_alternative(component), env);
}
function eval_sequence(stmts, env) {
if (is_empty_sequence(stmts)) {
return undefined;
} else if (is_last_statement(stmts)) {
return evaluate(first_statement(stmts), env);
} else {
const first_stmt_value =
evaluate(first_statement(stmts), env);
if (is_return_value(first_stmt_value)) {
return first_stmt_value;
} else {
return eval_sequence(rest_statements(stmts), env);
}
}
}
function scan_out_declarations(component) {
return is_sequence(component)
? accumulate(append,
null,
map(scan_out_declarations,
sequence_statements(component)))
: is_declaration(component)
? list(declaration_symbol(component))
: null;
}
function eval_block(component, env) {
const body = block_body(component);
const locals = scan_out_declarations(body);
const unassigneds = list_of_unassigned(locals);
return evaluate(body, extend_environment(locals,
unassigneds,
env));
}
function list_of_unassigned(symbols) {
return map(symbol => "*unassigned*", symbols);
}
function eval_return_statement(component, env) {
return make_return_value(evaluate(return_expression(component),
env));
}
function eval_assignment(component, env) {
const value = evaluate(assignment_value_expression(component),
env);
assign_symbol_value(assignment_symbol(component), value, env);
return value;
}
function eval_declaration(component, env) {
assign_symbol_value(
declaration_symbol(component),
evaluate(declaration_value_expression(component), env),
env);
return undefined;
}
// functions from SICP JS 4.1.2
function is_tagged_list(component, the_tag) {
return is_pair(component) && head(component) === the_tag;
}
function is_literal(component) {
return is_tagged_list(component, "literal");
}
function literal_value(component) {
return head(tail(component));
}
function make_literal(value) {
return list("literal", value);
}
function is_name(component) {
return is_tagged_list(component, "name");
}
function make_name(symbol) {
return list("name", symbol);
}
function symbol_of_name(component) {
return head(tail(component));
}
function is_assignment(component) {
return is_tagged_list(component, "assignment");
}
function assignment_symbol(component) {
return head(tail(head(tail(component))));
}
function assignment_value_expression(component) {
return head(tail(tail(component)));
}
function is_declaration(component) {
return is_tagged_list(component, "constant_declaration") ||
is_tagged_list(component, "variable_declaration") ||
is_tagged_list(component, "function_declaration");
}
function declaration_symbol(component) {
return symbol_of_name(head(tail(component)));
}
function declaration_value_expression(component) {
return head(tail(tail(component)));
}
function make_constant_declaration(name, value_expression) {
return list("constant_declaration", name, value_expression);
}
function is_lambda_expression(component) {
return is_tagged_list(component, "lambda_expression");
}
function lambda_parameter_symbols(component) {
return map(symbol_of_name, head(tail(component)));
}
function lambda_body(component) {
return head(tail(tail(component)));
}
function make_lambda_expression(parameters, body) {
return list("lambda_expression", parameters, body);
}
function is_function_declaration(component) {
return is_tagged_list(component, "function_declaration");
}
function function_declaration_name(component) {
return list_ref(component, 1);
}
function function_declaration_parameters(component) {
return list_ref(component, 2);
}
function function_declaration_body(component) {
return list_ref(component, 3);
}
function function_decl_to_constant_decl(component) {
return make_constant_declaration(
function_declaration_name(component),
make_lambda_expression(
function_declaration_parameters(component),
function_declaration_body(component)));
}
function is_return_statement(component) {
return is_tagged_list(component, "return_statement");
}
function return_expression(component) {
return head(tail(component));
}
function is_conditional(component) {
return is_tagged_list(component, "conditional_expression") ||
is_tagged_list(component, "conditional_statement");
}
function conditional_predicate(component) {
return list_ref(component, 1);
}
function conditional_consequent(component) {
return list_ref(component, 2);
}
function conditional_alternative(component) {
return list_ref(component, 3);
}
function is_sequence(stmt) {
return is_tagged_list(stmt, "sequence");
}
function sequence_statements(stmt) {
return head(tail(stmt));
}
function first_statement(stmts) {
return head(stmts);
}
function rest_statements(stmts) {
return tail(stmts);
}
function is_empty_sequence(stmts) {
return is_null(stmts);
}
function is_last_statement(stmts) {
return is_null(tail(stmts));
}
function is_block(component) {
return is_tagged_list(component, "block");
}
function block_body(component) {
return head(tail(component));
}
function make_block(statement) {
return list("block", statement);
}
function is_operator_combination(component) {
return is_unary_operator_combination(component) ||
is_binary_operator_combination(component);
}
function is_unary_operator_combination(component) {
return is_tagged_list(component, "unary_operator_combination");
}
function is_binary_operator_combination(component) {
return is_tagged_list(component, "binary_operator_combination");
}
function operator_symbol(component) {
return list_ref(component, 1);
}
function first_operand(component) {
return list_ref(component, 2);
}
function second_operand(component) {
return list_ref(component, 3);
}
function make_application(function_expression, argument_expressions) {
return list("application",
function_expression, argument_expressions);
}
function operator_combination_to_application(component) {
const operator = operator_symbol(component);
return is_unary_operator_combination(component)
? make_application(make_name(operator),
list(first_operand(component)))
: make_application(make_name(operator),
list(first_operand(component),
second_operand(component)));
}
function is_application(component) {
return is_tagged_list(component, "application");
}
function function_expression(component) {
return head(tail(component));
}
function arg_expressions(component) {
return head(tail(tail(component)));
}
// functions from SICP JS 4.1.3
function is_truthy(x) {
return is_boolean(x)
? x
: error(x, "boolean expected, received");
}
function is_falsy(x) { return ! is_truthy(x); }
function make_function(parameters, body, env) {
return list("compound_function", parameters, body, env);
}
function is_compound_function(f) {
return is_tagged_list(f, "compound_function");
}
function function_parameters(f) { return list_ref(f, 1); }
function function_body(f) { return list_ref(f, 2); }
function function_environment(f) { return list_ref(f, 3); }
function make_return_value(content) {
return list("return_value", content);
}
function is_return_value(value) {
return is_tagged_list(value, "return_value");
}
function return_value_content(value) {
return head(tail(value));
}
function enclosing_environment(env) { return tail(env); }
function first_frame(env) { return head(env); }
const the_empty_environment = null;
function make_frame(symbols, values) { return pair(symbols, values); }
function frame_symbols(frame) { return head(frame); }
function frame_values(frame) { return tail(frame); }
function extend_environment(symbols, vals, base_env) {
return length(symbols) === length(vals)
? pair(make_frame(symbols, vals), base_env)
: length(symbols) > length(vals)
? error("too many arguments supplied: " +
stringify(symbols) + ", " +
stringify(vals))
: error("too few arguments supplied: " +
stringify(symbols) + ", " +
stringify(vals));
}
function lookup_symbol_value(symbol, env) {
function env_loop(env) {
function scan(symbols, vals) {
return is_null(symbols)
? env_loop(enclosing_environment(env))
: symbol === head(symbols)
? head(vals)
: scan(tail(symbols), tail(vals));
}
if (env === the_empty_environment) {
error(symbol, "unbound name");
} else {
const frame = first_frame(env);
return scan(frame_symbols(frame), frame_values(frame));
}
}
return env_loop(env);
}
function assign_symbol_value(symbol, val, env) {
function env_loop(env) {
function scan(symbols, vals) {
return is_null(symbols)
? env_loop(enclosing_environment(env))
: symbol === head(symbols)
? set_head(vals, val)
: scan(tail(symbols), tail(vals));
}
if (env === the_empty_environment) {
error(symbol, "unbound name -- assignment");
} else {
const frame = first_frame(env);
return scan(frame_symbols(frame), frame_values(frame));
}
}
return env_loop(env);
}
// functions from SICP JS 4.1.4
function is_primitive_function(fun) {
return is_tagged_list(fun, "primitive");
}
function primitive_implementation(fun) { return head(tail(fun)); }
//CHANGED: CREATED NEW modified_plus_interpretation function
function modified_plus_interpretation(x,y){
if (is_list(x) && is_list(y)){
return append(x,y);
} else {
return x + y;
}
}
const primitive_functions = list(
list("head", head ),
list("tail", tail ),
list("pair", pair ),
list("list", list ),
list("is_null", is_null ),
list("display", display ),
list("error", error ),
list("math_abs",math_abs ),
list("+", modified_plus_interpretation), //CHANGED: ADDED modified_plus_interpretation function
list("-", (x, y) => x - y ),
list("-unary", x => - x ),
list("*", (x, y) => x * y ),
list("/", (x, y) => x / y ),
list("%", (x, y) => x % y ),
list("===", (x, y) => x === y),
list("!==", (x, y) => x !== y),
list(">", (x, y) => x > y),
list(">=", (x, y) => x >= y),
list(">", (x, y) => x > y),
list(">=", (x, y) => x >= y),
list("!", x => ! x)
);
const primitive_function_symbols =
map(head, primitive_functions);
const primitive_function_objects =
map(fun => list("primitive", head(tail(fun))),
primitive_functions);
const primitive_constants = list(list("undefined", undefined),
list("Infinity", Infinity),
list("math_PI", math_PI),
list("math_E", math_E),
list("NaN", NaN)
);
const primitive_constant_symbols =
map(c => head(c), primitive_constants);
const primitive_constant_values =
map(c => head(tail(c)), primitive_constants);
function apply_primitive_function(fun, arglist) {
return apply_in_underlying_javascript(
primitive_implementation(fun), arglist);
}
function setup_environment() {
return extend_environment(append(primitive_function_symbols,
primitive_constant_symbols),
append(primitive_function_objects,
primitive_constant_values),
the_empty_environment);
}
const the_global_environment = setup_environment();
function parse_and_evaluate(p) {
// wrap the program in a block: the program block
return evaluate(parse("{ " + p + " }"),
the_global_environment);
}
// Use this evaluator in the Programmable REPL
set_evaluator(parse_and_evaluate);
/*list(1, 2, 3) + list(4, 5, 6);*/
print("Goodbye, World!")
<!DOCTYPE html>
<html lang="en">
<head>
<title>To-Do List</title>
</head>
<body>
<input id="task" placeholder="New Task">
<button onclick="addTask()">Add</button>
<ul id="taskList"></ul>
<script>
function addTask() {
const task = document.getElementById("task").value;
if (task) {
const li = document.createElement("li");
li.textContent = task;
const removeBtn = document.createElement("button");
removeBtn.textContent = "Remove";
removeBtn.onclick = () => li.remove();
li.appendChild(removeBtn);
li.onclick = () => li.classList.toggle("completed");
document.getElementById("taskList").appendChild(li);
document.getElementById("task").value = "";
}
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>CSS Grid and Flexbox</title>
<style>
body {
font-family: Arial, sans-serif;
}
.header, .footer {
display: flex;
justify-content: center;
align-items: center;
background: #4CAF50;
color: #fff;
height: 60px;
}
.content {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
padding: 20px;
}
.box {
padding: 20px;
background: #2196F3;
color: #fff;
text-align: center;
transition: transform 0.3s;
}
.box:hover { transform: scale(1.05); background: #1E88E5; }
</style>
</head>
<body>
<div class="header">Header</div>
<div class="content">
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
</div>
<div class="footer">Footer</div>
</body>
</html>
let function_object_count = 1; //CHANGED: ADDED GLOBAL VARIABLE
// SICP JS 4.1.4
// functions from SICP JS 4.1.1
function evaluate(component, env) {
return is_literal(component)
? literal_value(component)
: is_name(component)
? lookup_symbol_value(symbol_of_name(component), env)
: is_application(component)
? apply(evaluate(function_expression(component), env),
list_of_values(arg_expressions(component), env))
: is_operator_combination(component)
? evaluate(operator_combination_to_application(component),
env)
: is_conditional(component)
? eval_conditional(component, env)
: is_lambda_expression(component)
? make_function(lambda_parameter_symbols(component),
lambda_body(component), env)
: is_sequence(component)
? eval_sequence(sequence_statements(component), env)
: is_block(component)
? eval_block(component, env)
: is_return_statement(component)
? eval_return_statement(component, env)
: is_function_declaration(component)
? evaluate(function_decl_to_constant_decl(component), env)
: is_declaration(component)
? eval_declaration(component, env)
: is_assignment(component)
? eval_assignment(component, env)
: error(component, "unknown syntax -- evaluate");
}
function apply(fun, args) {
if (is_primitive_function(fun)) {
return apply_primitive_function(fun, args);
} else if (is_compound_function(fun)) {
const result = evaluate(function_body(fun),
extend_environment(
function_parameters(fun),
args,
function_environment(fun)));
return is_return_value(result)
? return_value_content(result)
: undefined;
} else {
error(fun, "unknown function type -- apply");
}
}
function list_of_values(exps, env) {
return map(arg => evaluate(arg, env), exps);
}
function eval_conditional(component, env) {
return is_truthy(evaluate(conditional_predicate(component), env))
? evaluate(conditional_consequent(component), env)
: evaluate(conditional_alternative(component), env);
}
function eval_sequence(stmts, env) {
if (is_empty_sequence(stmts)) {
return undefined;
} else if (is_last_statement(stmts)) {
return evaluate(first_statement(stmts), env);
} else {
const first_stmt_value =
evaluate(first_statement(stmts), env);
if (is_return_value(first_stmt_value)) {
return first_stmt_value;
} else {
return eval_sequence(rest_statements(stmts), env);
}
}
}
function scan_out_declarations(component) {
return is_sequence(component)
? accumulate(append,
null,
map(scan_out_declarations,
sequence_statements(component)))
: is_declaration(component)
? list(declaration_symbol(component))
: null;
}
function eval_block(component, env) {
const body = block_body(component);
const locals = scan_out_declarations(body);
const unassigneds = list_of_unassigned(locals);
return evaluate(body, extend_environment(locals,
unassigneds,
env));
}
function list_of_unassigned(symbols) {
return map(symbol => "*unassigned*", symbols);
}
function eval_return_statement(component, env) {
return make_return_value(evaluate(return_expression(component),
env));
}
function eval_assignment(component, env) {
const value = evaluate(assignment_value_expression(component),
env);
assign_symbol_value(assignment_symbol(component), value, env);
return value;
}
function eval_declaration(component, env) {
assign_symbol_value(
declaration_symbol(component),
evaluate(declaration_value_expression(component), env),
env);
return undefined;
}
// functions from SICP JS 4.1.2
function is_tagged_list(component, the_tag) {
return is_pair(component) && head(component) === the_tag;
}
function is_literal(component) {
return is_tagged_list(component, "literal");
}
function literal_value(component) {
return head(tail(component));
}
function make_literal(value) {
return list("literal", value);
}
function is_name(component) {
return is_tagged_list(component, "name");
}
function make_name(symbol) {
return list("name", symbol);
}
function symbol_of_name(component) {
return head(tail(component));
}
function is_assignment(component) {
return is_tagged_list(component, "assignment");
}
function assignment_symbol(component) {
return head(tail(head(tail(component))));
}
function assignment_value_expression(component) {
return head(tail(tail(component)));
}
function is_declaration(component) {
return is_tagged_list(component, "constant_declaration") ||
is_tagged_list(component, "variable_declaration") ||
is_tagged_list(component, "function_declaration");
}
function declaration_symbol(component) {
return symbol_of_name(head(tail(component)));
}
function declaration_value_expression(component) {
return head(tail(tail(component)));
}
function make_constant_declaration(name, value_expression) {
return list("constant_declaration", name, value_expression);
}
function is_lambda_expression(component) {
return is_tagged_list(component, "lambda_expression");
}
function lambda_parameter_symbols(component) {
return map(symbol_of_name, head(tail(component)));
}
function lambda_body(component) {
return head(tail(tail(component)));
}
function make_lambda_expression(parameters, body) {
return list("lambda_expression", parameters, body);
}
function is_function_declaration(component) {
return is_tagged_list(component, "function_declaration");
}
function function_declaration_name(component) {
return list_ref(component, 1);
}
function function_declaration_parameters(component) {
return list_ref(component, 2);
}
function function_declaration_body(component) {
return list_ref(component, 3);
}
function function_decl_to_constant_decl(component) {
return make_constant_declaration(
function_declaration_name(component),
make_lambda_expression(
function_declaration_parameters(component),
function_declaration_body(component)));
}
function is_return_statement(component) {
return is_tagged_list(component, "return_statement");
}
function return_expression(component) {
return head(tail(component));
}
function is_conditional(component) {
return is_tagged_list(component, "conditional_expression") ||
is_tagged_list(component, "conditional_statement");
}
function conditional_predicate(component) {
return list_ref(component, 1);
}
function conditional_consequent(component) {
return list_ref(component, 2);
}
function conditional_alternative(component) {
return list_ref(component, 3);
}
function is_sequence(stmt) {
return is_tagged_list(stmt, "sequence");
}
function sequence_statements(stmt) {
return head(tail(stmt));
}
function first_statement(stmts) {
return head(stmts);
}
function rest_statements(stmts) {
return tail(stmts);
}
function is_empty_sequence(stmts) {
return is_null(stmts);
}
function is_last_statement(stmts) {
return is_null(tail(stmts));
}
function is_block(component) {
return is_tagged_list(component, "block");
}
function block_body(component) {
return head(tail(component));
}
function make_block(statement) {
return list("block", statement);
}
function is_operator_combination(component) {
return is_unary_operator_combination(component) ||
is_binary_operator_combination(component);
}
function is_unary_operator_combination(component) {
return is_tagged_list(component, "unary_operator_combination");
}
function is_binary_operator_combination(component) {
return is_tagged_list(component, "binary_operator_combination");
}
function operator_symbol(component) {
return list_ref(component, 1);
}
function first_operand(component) {
return list_ref(component, 2);
}
function second_operand(component) {
return list_ref(component, 3);
}
function make_application(function_expression, argument_expressions) {
return list("application",
function_expression, argument_expressions);
}
function operator_combination_to_application(component) {
const operator = operator_symbol(component);
return is_unary_operator_combination(component)
? make_application(make_name(operator),
list(first_operand(component)))
: make_application(make_name(operator),
list(first_operand(component),
second_operand(component)));
}
function is_application(component) {
return is_tagged_list(component, "application");
}
function function_expression(component) {
return head(tail(component));
}
function arg_expressions(component) {
return head(tail(tail(component)));
}
// functions from SICP JS 4.1.3
function is_truthy(x) {
return is_boolean(x)
? x
: error(x, "boolean expected, received");
}
function is_falsy(x) { return ! is_truthy(x); }
function make_function(parameters, body, env) { //CHANGED: ADDED FUNCTION OBJECT INCREMENT
function_object_count = function_object_count + 1;
return list("compound_function", parameters, body, env);
}
function is_compound_function(f) {
return is_tagged_list(f, "compound_function");
}
function function_parameters(f) { return list_ref(f, 1); }
function function_body(f) { return list_ref(f, 2); }
function function_environment(f) { return list_ref(f, 3); }
function make_return_value(content) {
return list("return_value", content);
}
function is_return_value(value) {
return is_tagged_list(value, "return_value");
}
function return_value_content(value) {
return head(tail(value));
}
function enclosing_environment(env) { return tail(env); }
function first_frame(env) { return head(env); }
const the_empty_environment = null;
function make_frame(symbols, values) { return pair(symbols, values); }
function frame_symbols(frame) { return head(frame); }
function frame_values(frame) { return tail(frame); }
function extend_environment(symbols, vals, base_env) {
return length(symbols) === length(vals)
? pair(make_frame(symbols, vals), base_env)
: length(symbols) > length(vals)
? error("too many arguments supplied: " +
stringify(symbols) + ", " +
stringify(vals))
: error("too few arguments supplied: " +
stringify(symbols) + ", " +
stringify(vals));
}
function lookup_symbol_value(symbol, env) {
function env_loop(env) {
function scan(symbols, vals) {
return is_null(symbols)
? env_loop(enclosing_environment(env))
: symbol === head(symbols)
? head(vals)
: scan(tail(symbols), tail(vals));
}
if (env === the_empty_environment) {
error(symbol, "unbound name");
} else {
const frame = first_frame(env);
return scan(frame_symbols(frame), frame_values(frame));
}
}
return env_loop(env);
}
function assign_symbol_value(symbol, val, env) {
function env_loop(env) {
function scan(symbols, vals) {
return is_null(symbols)
? env_loop(enclosing_environment(env))
: symbol === head(symbols)
? set_head(vals, val)
: scan(tail(symbols), tail(vals));
}
if (env === the_empty_environment) {
error(symbol, "unbound name -- assignment");
} else {
const frame = first_frame(env);
return scan(frame_symbols(frame), frame_values(frame));
}
}
return env_loop(env);
}
// functions from SICP JS 4.1.4
function is_primitive_function(fun) {
return is_tagged_list(fun, "primitive");
}
function primitive_implementation(fun) { return head(tail(fun)); }
const primitive_functions = list(
list("head", head ),
list("tail", tail ),
list("pair", pair ),
list("list", list ),
list("is_null", is_null ),
list("display", display ),
list("error", error ),
list("math_abs",math_abs ),
list("+", (x, y) => x + y ),
list("-", (x, y) => x - y ),
list("-unary", x => - x ),
list("*", (x, y) => x * y ),
list("/", (x, y) => x / y ),
list("%", (x, y) => x % y ),
list("===", (x, y) => x === y),
list("!==", (x, y) => x !== y),
list(">", (x, y) => x > y),
list(">=", (x, y) => x >= y),
list(">", (x, y) => x > y),
list(">=", (x, y) => x >= y),
list("!", x => ! x)
);
const primitive_function_symbols =
map(head, primitive_functions);
const primitive_function_objects =
map(fun => list("primitive", head(tail(fun))),
primitive_functions);
const primitive_constants = list(list("undefined", undefined),
list("Infinity", Infinity),
list("math_PI", math_PI),
list("math_E", math_E),
list("NaN", NaN)
);
const primitive_constant_symbols =
map(c => head(c), primitive_constants);
const primitive_constant_values =
map(c => head(tail(c)), primitive_constants);
function apply_primitive_function(fun, arglist) {
return apply_in_underlying_javascript(
primitive_implementation(fun), arglist);
}
function setup_environment() {
return extend_environment(append(primitive_function_symbols,
primitive_constant_symbols),
append(primitive_function_objects,
primitive_constant_values),
the_empty_environment);
}
const the_global_environment = setup_environment();
function parse_and_evaluate(p) {
// wrap the program in a block: the program block
return evaluate(parse("{ " + p + " }"),
the_global_environment);
}
// set_evaluator configures the "Run" button
// in the Programmable REPL tab on the right
// to apply the given evaluate function to the
// program text in the Programmable REPL editor.
set_evaluator(parse_and_evaluate);
// your testing
function count_function_objects_created(program_string) {
function_object_count = 0;
parse_and_evaluate(program_string);
return function_object_count;
}
// use your function object counter in the Programmable REPL
set_evaluator(count_function_objects_created);
/*
Test function:
function fun(x){
const y = x => x * 2;
function inner(a){
return g;
}
return inner(y);
}
const g = a => a * 3;
fun(2);
*/
let frame_count = 0; // CHANGED: ADDED GLOBAL VARIABLE
// SICP JS 4.1.4
// functions from SICP JS 4.1.1
function evaluate(component, env) {
return is_literal(component)
? literal_value(component)
: is_name(component)
? lookup_symbol_value(symbol_of_name(component), env)
: is_application(component)
? apply(evaluate(function_expression(component), env),
list_of_values(arg_expressions(component), env))
: is_operator_combination(component)
? evaluate(operator_combination_to_application(component),
env)
: is_conditional(component)
? eval_conditional(component, env)
: is_lambda_expression(component)
? make_function(lambda_parameter_symbols(component),
lambda_body(component), env)
: is_sequence(component)
? eval_sequence(sequence_statements(component), env)
: is_block(component)
? eval_block(component, env)
: is_return_statement(component)
? eval_return_statement(component, env)
: is_function_declaration(component)
? evaluate(function_decl_to_constant_decl(component), env)
: is_declaration(component)
? eval_declaration(component, env)
: is_assignment(component)
? eval_assignment(component, env)
: error(component, "unknown syntax -- evaluate");
}
function apply(fun, args) {
if (is_primitive_function(fun)) {
return apply_primitive_function(fun, args);
} else if (is_compound_function(fun)) {
const result = evaluate(function_body(fun),
extend_environment(
function_parameters(fun),
args,
function_environment(fun)));
return is_return_value(result)
? return_value_content(result)
: undefined;
} else {
error(fun, "unknown function type -- apply");
}
}
function list_of_values(exps, env) {
return map(arg => evaluate(arg, env), exps);
}
function eval_conditional(component, env) {
return is_truthy(evaluate(conditional_predicate(component), env))
? evaluate(conditional_consequent(component), env)
: evaluate(conditional_alternative(component), env);
}
function eval_sequence(stmts, env) {
if (is_empty_sequence(stmts)) {
return undefined;
} else if (is_last_statement(stmts)) {
return evaluate(first_statement(stmts), env);
} else {
const first_stmt_value =
evaluate(first_statement(stmts), env);
if (is_return_value(first_stmt_value)) {
return first_stmt_value;
} else {
return eval_sequence(rest_statements(stmts), env);
}
}
}
function scan_out_declarations(component) {
return is_sequence(component)
? accumulate(append,
null,
map(scan_out_declarations,
sequence_statements(component)))
: is_declaration(component)
? list(declaration_symbol(component))
: null;
}
function eval_block(component, env) {
const body = block_body(component);
const locals = scan_out_declarations(body);
const unassigneds = list_of_unassigned(locals);
return evaluate(body, extend_environment(locals,
unassigneds,
env));
}
function list_of_unassigned(symbols) {
return map(symbol => "*unassigned*", symbols);
}
function eval_return_statement(component, env) {
return make_return_value(evaluate(return_expression(component),
env));
}
function eval_assignment(component, env) {
const value = evaluate(assignment_value_expression(component),
env);
assign_symbol_value(assignment_symbol(component), value, env);
return value;
}
function eval_declaration(component, env) {
assign_symbol_value(
declaration_symbol(component),
evaluate(declaration_value_expression(component), env),
env);
return undefined;
}
// functions from SICP JS 4.1.2
function is_tagged_list(component, the_tag) {
return is_pair(component) && head(component) === the_tag;
}
function is_literal(component) {
return is_tagged_list(component, "literal");
}
function literal_value(component) {
return head(tail(component));
}
function make_literal(value) {
return list("literal", value);
}
function is_name(component) {
return is_tagged_list(component, "name");
}
function make_name(symbol) {
return list("name", symbol);
}
function symbol_of_name(component) {
return head(tail(component));
}
function is_assignment(component) {
return is_tagged_list(component, "assignment");
}
function assignment_symbol(component) {
return head(tail(head(tail(component))));
}
function assignment_value_expression(component) {
return head(tail(tail(component)));
}
function is_declaration(component) {
return is_tagged_list(component, "constant_declaration") ||
is_tagged_list(component, "variable_declaration") ||
is_tagged_list(component, "function_declaration");
}
function declaration_symbol(component) {
return symbol_of_name(head(tail(component)));
}
function declaration_value_expression(component) {
return head(tail(tail(component)));
}
function make_constant_declaration(name, value_expression) {
return list("constant_declaration", name, value_expression);
}
function is_lambda_expression(component) {
return is_tagged_list(component, "lambda_expression");
}
function lambda_parameter_symbols(component) {
return map(symbol_of_name, head(tail(component)));
}
function lambda_body(component) {
return head(tail(tail(component)));
}
function make_lambda_expression(parameters, body) {
return list("lambda_expression", parameters, body);
}
function is_function_declaration(component) {
return is_tagged_list(component, "function_declaration");
}
function function_declaration_name(component) {
return list_ref(component, 1);
}
function function_declaration_parameters(component) {
return list_ref(component, 2);
}
function function_declaration_body(component) {
return list_ref(component, 3);
}
function function_decl_to_constant_decl(component) {
return make_constant_declaration(
function_declaration_name(component),
make_lambda_expression(
function_declaration_parameters(component),
function_declaration_body(component)));
}
function is_return_statement(component) {
return is_tagged_list(component, "return_statement");
}
function return_expression(component) {
return head(tail(component));
}
function is_conditional(component) {
return is_tagged_list(component, "conditional_expression") ||
is_tagged_list(component, "conditional_statement");
}
function conditional_predicate(component) {
return list_ref(component, 1);
}
function conditional_consequent(component) {
return list_ref(component, 2);
}
function conditional_alternative(component) {
return list_ref(component, 3);
}
function is_sequence(stmt) {
return is_tagged_list(stmt, "sequence");
}
function sequence_statements(stmt) {
return head(tail(stmt));
}
function first_statement(stmts) {
return head(stmts);
}
function rest_statements(stmts) {
return tail(stmts);
}
function is_empty_sequence(stmts) {
return is_null(stmts);
}
function is_last_statement(stmts) {
return is_null(tail(stmts));
}
function is_block(component) {
return is_tagged_list(component, "block");
}
function block_body(component) {
return head(tail(component));
}
function make_block(statement) {
return list("block", statement);
}
function is_operator_combination(component) {
return is_unary_operator_combination(component) ||
is_binary_operator_combination(component);
}
function is_unary_operator_combination(component) {
return is_tagged_list(component, "unary_operator_combination");
}
function is_binary_operator_combination(component) {
return is_tagged_list(component, "binary_operator_combination");
}
function operator_symbol(component) {
return list_ref(component, 1);
}
function first_operand(component) {
return list_ref(component, 2);
}
function second_operand(component) {
return list_ref(component, 3);
}
function make_application(function_expression, argument_expressions) {
return list("application",
function_expression, argument_expressions);
}
function operator_combination_to_application(component) {
const operator = operator_symbol(component);
return is_unary_operator_combination(component)
? make_application(make_name(operator),
list(first_operand(component)))
: make_application(make_name(operator),
list(first_operand(component),
second_operand(component)));
}
function is_application(component) {
return is_tagged_list(component, "application");
}
function function_expression(component) {
return head(tail(component));
}
function arg_expressions(component) {
return head(tail(tail(component)));
}
// functions from SICP JS 4.1.3
function is_truthy(x) {
return is_boolean(x)
? x
: error(x, "boolean expected, received");
}
function is_falsy(x) { return ! is_truthy(x); }
function make_function(parameters, body, env) {
return list("compound_function", parameters, body, env);
}
function is_compound_function(f) {
return is_tagged_list(f, "compound_function");
}
function function_parameters(f) { return list_ref(f, 1); }
function function_body(f) { return list_ref(f, 2); }
function function_environment(f) { return list_ref(f, 3); }
function make_return_value(content) {
return list("return_value", content);
}
function is_return_value(value) {
return is_tagged_list(value, "return_value");
}
function return_value_content(value) {
return head(tail(value));
}
function enclosing_environment(env) { return tail(env); }
function first_frame(env) { return head(env); }
const the_empty_environment = null;
function make_frame(symbols, values) { //CHANGED: ADDED FRAME INCREMENT
frame_count = frame_count + 1;
return pair(symbols, values); }
function frame_symbols(frame) { return head(frame); }
function frame_values(frame) { return tail(frame); }
function extend_environment(symbols, vals, base_env) {
return length(symbols) === length(vals)
? pair(make_frame(symbols, vals), base_env)
: length(symbols) > length(vals)
? error("too many arguments supplied: " +
stringify(symbols) + ", " +
stringify(vals))
: error("too few arguments supplied: " +
stringify(symbols) + ", " +
stringify(vals));
}
function lookup_symbol_value(symbol, env) {
function env_loop(env) {
function scan(symbols, vals) {
return is_null(symbols)
? env_loop(enclosing_environment(env))
: symbol === head(symbols)
? head(vals)
: scan(tail(symbols), tail(vals));
}
if (env === the_empty_environment) {
error(symbol, "unbound name");
} else {
const frame = first_frame(env);
return scan(frame_symbols(frame), frame_values(frame));
}
}
return env_loop(env);
}
function assign_symbol_value(symbol, val, env) {
function env_loop(env) {
function scan(symbols, vals) {
return is_null(symbols)
? env_loop(enclosing_environment(env))
: symbol === head(symbols)
? set_head(vals, val)
: scan(tail(symbols), tail(vals));
}
if (env === the_empty_environment) {
error(symbol, "unbound name -- assignment");
} else {
const frame = first_frame(env);
return scan(frame_symbols(frame), frame_values(frame));
}
}
return env_loop(env);
}
// functions from SICP JS 4.1.4
function is_primitive_function(fun) {
return is_tagged_list(fun, "primitive");
}
function primitive_implementation(fun) { return head(tail(fun)); }
const primitive_functions = list(
list("head", head ),
list("tail", tail ),
list("pair", pair ),
list("list", list ),
list("is_null", is_null ),
list("display", display ),
list("error", error ),
list("math_abs",math_abs ),
list("+", (x, y) => x + y ),
list("-", (x, y) => x - y ),
list("-unary", x => - x ),
list("*", (x, y) => x * y ),
list("/", (x, y) => x / y ),
list("%", (x, y) => x % y ),
list("===", (x, y) => x === y),
list("!==", (x, y) => x !== y),
list(">", (x, y) => x > y),
list(">=", (x, y) => x >= y),
list(">", (x, y) => x > y),
list(">=", (x, y) => x >= y),
list("!", x => ! x)
);
const primitive_function_symbols =
map(head, primitive_functions);
const primitive_function_objects =
map(fun => list("primitive", head(tail(fun))),
primitive_functions);
const primitive_constants = list(list("undefined", undefined),
list("Infinity", Infinity),
list("math_PI", math_PI),
list("math_E", math_E),
list("NaN", NaN)
);
const primitive_constant_symbols =
map(c => head(c), primitive_constants);
const primitive_constant_values =
map(c => head(tail(c)), primitive_constants);
function apply_primitive_function(fun, arglist) {
return apply_in_underlying_javascript(
primitive_implementation(fun), arglist);
}
function setup_environment() {
return extend_environment(append(primitive_function_symbols,
primitive_constant_symbols),
append(primitive_function_objects,
primitive_constant_values),
the_empty_environment);
}
const the_global_environment = setup_environment();
function parse_and_evaluate(p) {
// wrap the program in a block: the program block
return evaluate(parse("{ " + p + " }"),
the_global_environment);
}
// set_evaluator configures the "Run" button
// in the Programmable REPL tab on the right
// to apply the given evaluate function to the
// program text in the Programmable REPL editor.
set_evaluator(parse_and_evaluate);
// your testing
function count_frames_created(program_string) {
frame_count = 0;
evaluate(parse("{ " + program_string + " }"),
the_global_environment);
return frame_count;
}
// use your frame counter in the Programmable REPL
set_evaluator(count_frames_created);
/*
function fun(x){
return g;
}
const g = x => x * x;
fun(2);
*/
#Open the path: C:\Users\MuraliM\AppData\Local\Microsoft\Edge\User Data #backup the file 'Local State'
C Program to Construct Shortest Path Tree (SPT):
#include <stdio.h>
#include <limits.h>
#define V 5 // Define the number of vertices in the graph
// Function to find the vertex with the minimum distance value
int minDistance(int dist[], int sptSet[]) {
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == 0 && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
// Function to print the constructed tree and distances
void printTree(int parent[], int dist[], int src) {
printf("Shortest Path Tree:\n");
printf("Vertex\tDistance from Source\tParent\n");
for (int i = 0; i < V; i++) {
printf("%d\t\t%d\t\t%d\n", i, dist[i], parent[i]);
}
}
// Dijkstra's algorithm to construct the shortest path tree
void dijkstra(int graph[V][V], int src) {
int dist[V]; // dist[i] will hold the shortest distance from src to i
int sptSet[V]; // sptSet[i] will be true if vertex i is included in SPT
int parent[V]; // To store the shortest path tree
// Initialize all distances as INFINITE and sptSet[] as false
for (int i = 0; i < V; i++) {
dist[i] = INT_MAX;
sptSet[i] = 0;
parent[i] = -1; // Parent of the root node will be -1
}
// Distance of source vertex from itself is always 0
dist[src] = 0;
// Find the shortest path for all vertices
for (int count = 0; count < V - 1; count++) {
// Pick the minimum distance vertex from the set of vertices not yet
processed
int u = minDistance(dist, sptSet);
// Mark the picked vertex as processed
sptSet[u] = 1;
// Update dist value of the adjacent vertices of the picked vertex
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];
parent[v] = u; // Update the parent of vertex v
}
}
// Print the constructed shortest path tree
printTree(parent, dist, src);
}
int main() {
// Example graph represented using an adjacency matrix
int graph[V][V] = {
{0, 10, 0, 0, 5}, // Node 0 to 1 has weight 10, to 4 has weight 5
{0, 0, 1, 0, 3}, // Node 1 to 2 has weight 1, to 4 has weight 3
{0, 0, 0, 4, 0}, // Node 2 to 3 has weight 4
{7, 0, 6, 0, 0}, // Node 3 to 0 has weight 7, to 2 has weight 6
{0, 3, 9, 2, 0} // Node 4 to 1 has weight 3, to 2 has weight 9, to 3 has weight
2
};
// Source node for the algorithm
int source = 0;
// Call Dijkstra's algorithm to construct the shortest path tree
dijkstra(graph, source);
return 0;
}
{
...
"content_security_policy": {
"sandbox": "sandbox allow-scripts; script-src 'self' https://example.com"
},
"sandbox": {
"pages": [
"page1.html",
"directory/page2.html"
]
},
...
}
{
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": " :star: Boost Days: What's on in Melbourne! :star: "
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "\n\n Hey Melbourne, happy Monday! Please see below for what's on this week. "
}
},
{
"type": "divider"
},
{
"type": "header",
"text": {
"type": "plain_text",
"text": "Xero Café ",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "\n :new-thing: *This week we are offering:* \n\n Yo Yo Biscuits, Funny Face Biscuits & Jumbo Smarties Cookies :cookie: \n\n *Weekly Café Special:* _ *French Mint Hot Chocolate* _ :frenchie:"
}
},
{
"type": "header",
"text": {
"type": "plain_text",
"text": " Wednesday, 13th November :calendar-date-13:",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "\n\n :tart: Afternoon Tea from *2pm* in the L3 kitchen \n\n"
}
},
{
"type": "header",
"text": {
"type": "plain_text",
"text": "Thursday, 14th November :calendar-date-14:",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": ":breakfast: *Breakfast*: Provided by *Kartel Catering* from *8:30am - 10:30am* in the Wominjeka Breakout Space.\n\n "
}
},
{
"type": "divider"
},
{
"type": "header",
"text": {
"type": "plain_text",
"text": ":magic-blob: :xero-unicorn: End of Year Event - A Sprinkle of Magic :xero-unicorn: :magic-blob:",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "\n\n *Date:* 28th November 2024 \n*Time:* 4pm - 10pm \n *Location:* The Timber Yard, Port Melbourne \nPlease click <https://xero-wx.jomablue.com/reg/store/eoy_mel|here> to RSVP! \nRegistrations close on the *_14th November 2024_* :party-wx:"
}
}
]
}
$text = "Your text goes here" $filePath = "C:\path\to\your\file.txt" $text | Out-File -FilePath $filePath Start-Process notepad.exe $filePath
//1 ....datapreprocessing**************************************************
import pandas as pd
df=pd.read_csv("/content/sample.csv")
#print(df)
print("DATA SET:\n", df)
print("DATA SET SIZE:",df.size)
print("DATA SET SHAPE:",df.shape)
print("DATA SET DIMENSIONS:",df.ndim)
print("Head\n",df.head())
print("Tail\n", df.tail())
print("Head(2)\n",df.head(2))
print("Tail(2)\n",df.tail(2))
print("Head(-2)\n",df.head(-2))
print("Tail(-2) \n",df.tail(-2))
print("DATA TYPES")
df.info()
print("STATISTICS:\n",df.describe().T)
print("FRE. COUNT OF RECORDS:\n",df.value_counts())
print("\nFRE. COUNT OF GENDER",df['GENDER'].value_counts())
#print("TWO FEATURES FRQ", df[['GENDER','M1']].value_counts())
print("\nEXISTANCE of NaNs in data set", df.isna())
print("\nCOL-WISE NaNs in data set", df.isna().sum())
print("\nOVERALL NaNs in data set", df.isna().sum().sum())
print("\nTOT NaNs in M1", df['M1'].isna().sum())
print("\nBefore Filling\n", df)
df['M1'].fillna(df['M1'].mean(),inplace=True) #saving update/permament
df['PHY'].fillna(df['PHY'].mean(),inplace=True) #saving update/permament
print("\nAFTER Filling\n", df)
print("BEFORE DROP - DF")
print(df)
df.drop_duplicates('SID',keep='first',inplace=True,ignore_index=True)
print("AFTER DROP DF")
print(df)
def remove_outliers_iqr(df, column):
Q1 = df[column].quantile(0.25)
Q3 = df[column].quantile(0.75)
IQR = Q3 - Q1
lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR
print("lower_bound :",lower_bound,"upper_bound:",upper_bound)
return df[(df[column] >= lower_bound) & (df[column] <= upper_bound)]
# Remove outliers from the 'Math' column
df_no_outliers_math = remove_outliers_iqr(df, 'M1')
print("\nDataFrame after Removing Outliers in 'M1':")
print(df_no_outliers_math)
import matplotlib.pyplot as plt
import seaborn as sns
# Line Plot
plt.plot(df['M1'], df['PHY'],color='green')
plt.xlabel('M1')
plt.ylabel('PHY')
plt.title('Line Plot')
plt.show()
# Scatter Plot
plt.scatter(df['M1'], df['PHY'])
plt.xlabel('M1')
plt.ylabel('PHY')
plt.title('Scatter Plot')
plt.show()
plt.hist(df['M1'], bins=30, edgecolor='black')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Histogram')
plt.show()
sns.boxplot(data=df)
plt.title('Box Plot')
plt.show()
sns.pairplot(df)
plt.title('Pair Plot')
plt.show()
sns.barplot(x='GENDER', y='M1', data=df)
plt.title('Bar Plot')
plt.show()
2.regression************************************************************
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn import metrics
# Sample data
df=pd.read_csv("/content/Stud_Data.csv")
# Reshape the data :: Single Feature
hours_studied = np.array(df["hours_studied"])
print(hours_studied.shape)
hours_studied =hours_studied.reshape(-1, 1)
print(hours_studied.shape)
scores=df["scores"]
# Create a linear regression model
model = LinearRegression()
# Fit the model
model.fit(hours_studied, scores)
#Print the Parameters
print("Beta 0 :", model.intercept_)
print("Beta 1 :", model.coef_[0])
#Regression Model
print("Y=",model.intercept_,"+",model.coef_[0],"X")
# Make predictions
predicted_scores = model.predict(hours_studied)
df["predicted_scores"]=predicted_scores
print("ORIGINAL SCORES:\n",df["scores"])
print("PREDICTED SCORES:\n",df["predicted_scores"])
print("MAE",metrics.mean_absolute_error(scores,predicted_scores))
print("MSE",metrics.mean_squared_error(scores,predicted_scores))
print("RMSE",np.sqrt(metrics.mean_squared_error(scores,predicted_scores)))
r2 = metrics.r2_score(scores,predicted_scores)
print('r2 score/Coefficient of Determination for perfect model is', r2)
print("\nCorrelation Coefficient: r =",df['hours_studied'].corr(df['scores']))
### USING MACHINE LEARNING APPROACH
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn import metrics
from sklearn.model_selection import train_test_split
# Sample data
df=pd.read_csv("/content/AgeData.csv")
#print(df.describe())
x = df[['Income (in $1000s)', 'Education Level (Years)', 'Years of Experience']]
y= df['Age']
#print(x)
#print(y)
x_train, x_test, y_train, y_test=train_test_split(x, y, test_size = 0.3)
#Fitting the Multiple Linear Regression model
mlr = LinearRegression()
mlr.fit(x_train, y_train)
#Intercept and Coefficient
print("Intercept: (Beta 0) ", mlr.intercept_)
#print("Coefficients:")
#print(list(zip(x, mlr.coef_)))
print("\nCoefficients:\n Beta 1:",mlr.coef_[0])
print("\n Beta 2:",mlr.coef_[1])
print("\n Beta 3:",mlr.coef_[2])
print("\nRegression Equation:",mlr.intercept_,"+",mlr.coef_[0],"*Income (in $1000s)+"
,mlr.coef_[1],"*Education Level (Years)+",mlr.coef_[2],"*Years of Experience")
#Prediction of test set
y_pred_mlr= mlr.predict(x_test)
meanAbErr = metrics.mean_absolute_error(y_test, y_pred_mlr)
meanSqErr = metrics.mean_squared_error(y_test, y_pred_mlr)
rootMeanSqErr = np.sqrt(metrics.mean_squared_error(y_test, y_pred_mlr))
#print('\nR squared: {:.2f}'.format(mlr.score(x,y)*100))
print('\nR squared: {:.2f}'.format(mlr.score(x,y)))
print('Mean Absolute Error:', meanAbErr)
print('Mean Square Error:', meanSqErr)
print('Root Mean Square Error:', rootMeanSqErr)
#### PREDICTING AGE BASED ON TEST/NEW OBSERVATION
newobs_df=pd.DataFrame([[38,15,12]], columns=x.columns)
y_pred_new= mlr.predict(newobs_df)
print("PREDICTED AGE OF NEW RESPONDENT",y_pred_new[0])
5 a..decision tree**********************************************
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import classification_report,accuracy_score
import seaborn as sns
import matplotlib.pyplot as plt
# Load and display top 2 records of the Soybean dataset
df=pd.read_csv("/content/Soybean.csv")
print(df.head(2))
# DATA EXPLORATION
#Data set details/info
print(df.info())
print(df.describe())
#### DATA PRE-PROCESSING
# Missing Values , Duplicated and Outliers Handling
# Handling Missing Values
#Verify Missing Values
#print(df.isna().sum())
#Fill Missing Values with mean value of the respective feature/column
cols=list(df.columns)
print("Before Pre-Processing - Total Missing Values",df.isna().sum().sum())
for i in range(0,len(cols)-1):
#print(cols[i])
if(df[cols[i]].isna().sum()>0):
df[cols[i]].fillna(df[cols[i]].mean(),inplace=True)
print("After Pre-Processing - Total Missing Values",df.isna().sum().sum())
# Handling Duplicate Values
#Verify Duplicate Values/records
print("BEFORE DROP :: DATA SIZE", df.shape)
df.drop_duplicates(keep="first",inplace=True)
#Verify Duplicate Values/records
print("AFTER DROP :: DATA SIZE", df.shape)
# Handling Outliers
#verify Outliers
#Plotting the box plot
plt.figure(figsize=(20, 8))
sns.boxplot(data=df, orient="v", palette="Set2")
plt.title("Box Plot of Soybean Dataset Features")
plt.show()
''' NOTE:: DATA HAS OUTLIERS BUT THEY ARE VALID RESPONSES , HENCE WE ARE NOT DROPPING THE OUTLIERS.
IF THEY ARE REALLY OUTLERS THEN WE SHOULD DROP THE OUTLIERS USING THE BELOW CODE
# #DROP Outliers
# def remove_outliers_iqr(df, column):
# Q1 = df[column].quantile(0.25)
# Q3 = df[column].quantile(0.75)
# IQR = Q3 - Q1
# lower_bound = Q1 - 1.5 * IQR
# upper_bound = Q3 + 1.5 * IQR
# print(column,":","lower_bound :",lower_bound,"upper_bound:",upper_bound)
# return df[(df[column] >= lower_bound) & (df[column] <= upper_bound)]
# # Remove outliers from the 'sepal_width' column
# print("BOX PLOT - B4", df.shape)
# for i in range(0,len(cols)-1):
# df = remove_outliers_iqr(df, cols[i])
# print("BOX PLOT - AFTER", df.shape)
'''
### MACHINE LEANING MODEL DESIGN AND EVALUATION
#Feature Set
X= df.iloc[:, :-1] #"Input Features
#Target Variable/ Classs variable
Y=df.iloc[:, [-1]]
# print("Input Features (X) : \n" , X)
# print("Target Variable/Class Variable (Y) : \n" , Y)
# Split data into train and test sets
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=42)
# Initialising Decision Tree Classifier
clf = DecisionTreeClassifier()
clf.fit(X_train,Y_train)
# Train the model
# Y_train array Should be flatten into a 1D array
clf.fit(X_train, np.array(Y_train).ravel())
# Predict on the test data
Y_pred = clf.predict(X_test)
# Print accuracy
accuracy = accuracy_score(Y_test, Y_pred)
print(f"Accuracy: {accuracy:.2f}")
# # Print detailed classification report
# report = classification_report(Y_test, Y_pred)
# print("Classification Report:")
# print(report)
#Predict the class of the new observation
new_observation= pd.DataFrame([[6,0,2,1,0,3,0,1,1,1,1,1,0,2,2,0,0,0,1,0,3,1,1,1,0,0,0,0,4,0,0,0,0,0,0]], columns=X.columns)
predicted_class = clf.predict(new_observation)
print("Predicted Class of NEW OBSERVATION :: ", predicted_class[0])
5 b knn*************************************************************
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report,accuracy_score
import seaborn as sns
import matplotlib.pyplot as plt
# Load the Iris dataset
df=pd.read_csv("/content/sample_data/Iris.csv")
# DATA EXPLORATION
print(df.head())
print(df.info())
print(df.describe())
#Verify Missing Values
print(df.isna().sum())
#Verify Duplicate Values/records
print("BEFORE", df[df.duplicated()])
df.drop_duplicates(keep="first",inplace=True)
#Verify Duplicate Values/records
print("AFTER",df[df.duplicated()])
#verify Outliers
#Plotting the box plot
plt.figure(figsize=(12, 8))
sns.boxplot(data=df, orient="v", palette="Set2")
plt.title("Box Plot of Iris Dataset Features")
plt.show()
#DROP Outliers
def remove_outliers_iqr(df, column):
Q1 = df[column].quantile(0.25)
Q3 = df[column].quantile(0.75)
IQR = Q3 - Q1
lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR
print("lower_bound :",lower_bound,"upper_bound:",upper_bound)
return df[(df[column] >= lower_bound) & (df[column] <= upper_bound)]
# Remove outliers from the 'sepal_width' column
df_no_outliers_sepal_width = remove_outliers_iqr(df, 'sepal_width')
print("\nDataFrame after Removing Outliers in 'sepal_width':")
print(df_no_outliers_sepal_width)
df=df_no_outliers_sepal_width
#verify Outliers
#Plotting the box plot
plt.figure(figsize=(12, 8))
sns.boxplot(data=df, orient="v", palette="Set2")
plt.title("Box Plot of Iris Dataset Features AFTER OULIERS DROPPED")
plt.show()
### MACHINE LEANING MODEL DESIGN AND EVALUATION
#Feature Set
X= df.iloc[:, :-1]
#Target Variable/ Classs variable
Y=df.iloc[:, [-1]]
print("Input Features (X) : \n" , X)
print("Target Variable/Class Variable (Y) : \n" , Y)
# Split data into train and test sets
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=42)
# Initialize KNN classifier
k = 3 # Define the number of neighbors
knn = KNeighborsClassifier(n_neighbors=k)
# Train the model
# Y_train array Should be flatten into a 1D array
knn.fit(X_train, np.array(Y_train).ravel())
# Predict on the test data
Y_pred = knn.predict(X_test)
# Print accuracy
accuracy = accuracy_score(Y_test, Y_pred)
print(f"Accuracy: {accuracy:.2f}")
# Print detailed classification report
report = classification_report(Y_test, Y_pred)
print("Classification Report:")
print(report)
#Predict the class of the new observation
#new_observation with sepal_length sepal_width petal_length petal_width
new_observation= pd.DataFrame([[5.1, 3.5, 1.4, 0.2]], columns=X.columns)
predicted_class = knn.predict(new_observation)
print("Predicted Class of NEW OBSERVATION :: ", predicted_class[0])
6.random forest *************************************************
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report,accuracy_score
import seaborn as sns
import matplotlib.pyplot as plt
# Load and display top 2 records of the Soybean dataset
df=pd.read_csv("/content/Loandata.csv")
# DATA EXPLORATION
print(df.info())
#print(df.head(2))
#DROP LOAN ID - NOT USEFUL IN ANALYSIS
df.drop(labels='Loan_ID', axis=1, inplace=True)
#REPLACE DEPENDENTS COUNT 3+ to 3
df['Dependents'] = df['Dependents'].replace('3+', '3')
#Missing Values Management
print("Before :: MISSING VALUE COUNT\n",df.isna().sum())
df['Gender'].fillna(df['Gender'].mode()[0],inplace=True)
df['Married'].fillna(df['Married'].mode()[0],inplace=True)
df['Dependents'].fillna(df['Dependents'].mode()[0],inplace=True)
df['Education'].fillna(df['Education'].mode()[0],inplace=True)
df['Self_Employed'].fillna(df['Self_Employed'].mode()[0],inplace=True)
df['Property_Area'].fillna(df['Property_Area'].mode()[0],inplace=True)
df['Loan_Status'].fillna(df['Loan_Status'].mode()[0],inplace=True)
df['Credit_History'].fillna(df['Credit_History'].mode()[0],inplace=True)
### FILL WITH MEAN
df['LoanAmount'].fillna(df['LoanAmount'].mean(),inplace=True)
df['Loan_Amount_Term'].fillna(df['Loan_Amount_Term'].mean(),inplace=True)
print("After :: MISSING VALUE COUNT\n",df.isna().sum())
# Handling Duplicate Values
#Verify Duplicate Values/records
print("BEFORE DROP :: DATA SIZE", df.shape)
df.drop_duplicates(keep="first",inplace=True)
#Verify Duplicate Values/records
print("AFTER DROP :: DATA SIZE", df.shape)
# Handling Outliers
#NOTE:: DATA HAS OUTLIERS BUT THEY ARE VALID RESPONSES , HENCE WE ARE NOT DROPPING THE OUTLIERS.
#verify Outliers
#Plotting the box plot
plt.figure(figsize=(20, 8))
sns.boxplot(data=df, orient="v", palette="Set2")
plt.title("Box Plot of Soybean Dataset Features")
plt.show()
#DATA TRANSORMATION
# Initialize the LabelEncoder
label_encoder = LabelEncoder()
print(df['Loan_Status'].value_counts())
# Fit and transform the columns
df['Gender'] = label_encoder.fit_transform(df['Gender'])
df['Married'] = label_encoder.fit_transform(df['Married'])
df['Education'] = label_encoder.fit_transform(df['Education'])
df['Self_Employed'] = label_encoder.fit_transform(df['Self_Employed'])
df['Property_Area'] = label_encoder.fit_transform(df['Property_Area'])
df['Loan_Status'] = label_encoder.fit_transform(df['Loan_Status'])
print(df['Loan_Status'].value_counts())
df.to_csv('CleanFile.csv', index=False)
### MACHINE LEANING MODEL DESIGN AND EVALUATION
#Feature Set
X= df.iloc[:, :-1] #"Input Features
#Target Variable/ Classs variable
Y=df.iloc[:, [-1]]
# print("Input Features (X) : \n" , X)
# print("Target Variable/Class Variable (Y) : \n" , Y)
# Split data into train and test sets
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=42)
# Ensure Y_train and Y_test are 1D arrays
Y_train = np.array(Y_train).ravel()
Y_test = np.array(Y_test).ravel()
# Train a Random Forest Classifier
clf = RandomForestClassifier(n_estimators=100, random_state=42)
clf.fit(X_train, Y_train)
# Train the model
# Y_train array Should be flatten into a 1D array
clf.fit(X_train, Y_train)
# Predict on the test data
Y_pred = clf.predict(X_test)
# Print accuracy
accuracy = accuracy_score(Y_test, Y_pred)
print(f"Accuracy: {accuracy:.2f}")
# Print detailed classification report
report = classification_report(Y_test, Y_pred)
print("Classification Report:")
print(report)
#Predict the class of the new observation
new_observation= pd.DataFrame([[1,1,0,1,0,2583,2358.0,120.0,360.0,1.0,2]], columns=X.columns)
predicted_class = clf.predict(new_observation)
#### 0 - NO 1 - YES
if (predicted_class[0]=='0') :
classLable="No"
else:
classLable="Yes"
print("Predicted Class of NEW OBSERVATION :: ",classLable)
1.mergesort***********************************************
import java.util.Scanner;
import java.util.Arrays;
public class Mergesort {
public static void mergeSort(int[] array, int left, int right) {
if (left < right) {
int mid = (left + right) / 2;
mergeSort(array, left, mid);
mergeSort(array, mid + 1, right);
merge(array, left, mid, right);
}
}
public static void merge(int[] array, int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
int[] leftArray = new int[n1];
int[] rightArray = new int[n2];
for (int i = 0; i < n1; i++) {
leftArray[i] = array[left + i];
}
for (int j = 0; j < n2; j++) {
rightArray[j] = array[mid + 1 + j];
}
int i = 0, j = 0;
int k = left;
while (i < n1 && j < n2) {
if (leftArray[i] <= rightArray[j]) {
array[k] = leftArray[i];
i++;
} else {
array[k] = rightArray[j];
j++;
}
k++;
}
while (i < n1) {
array[k] = leftArray[i];
i++;
k++;
}
while (j < n2) {
array[k] = rightArray[j];
j++;
k++;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements in the array: ");
int n = scanner.nextInt();
int[] array = new int[n];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
}
System.out.println("Original array:"+Arrays.toString(array));
mergeSort(array, 0, array.length - 1);
System.out.println("Sorted array:"+Arrays.toString(array));
scanner.close();
}
}
2.quicksort*****************************************************************
import java.util.Scanner;
import java.util.Arrays;
public class QuickSort {
// Main method that sorts the array
public static void quickSort(int[] array, int low, int high) {
if (low < high) {
// Partition the array and get the pivot index
int pivotIndex = partition(array, low, high);
// Recursively sort the elements before and after partition
quickSort(array, low, pivotIndex - 1);
quickSort(array, pivotIndex + 1, high);
}
}
// Partition method with the first element as pivot
private static int partition(int[] array, int low, int high) {
int pivot = array[low]; // Choosing the first element as pivot
int i = low + 1; // Start from the element after the pivot
for (int j = low + 1; j <= high; j++) {
// If the current element is smaller than or equal to the pivot
if (array[j] <= pivot) {
swap(array, i, j);
i++;
}
}
// Swap the pivot element with the element at index i-1
swap(array, low, i - 1);
return i - 1; // Return the partitioning index
}
// Swap helper method
private static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
// Method to print the array
// Main method to test the algorithm
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements in the array: ");
int n = scanner.nextInt();
int[] array = new int[n];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
}
System.out.println("Original array:"+Arrays.toString(array));
quickSort(array, 0, array.length - 1);
System.out.println("Sorted array:"+Arrays.toString(array));
scanner.close();
}
}
3.articulation point**************************************************************
import java.util.*;
public class Articulation {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of vertices: ");
int v = sc.nextInt(); // Number of vertices
int[][] adj = new int[v + 1][v + 1];
// Input adjacency matrix
System.out.println("Enter adjacency matrix:");
for (int i = 1; i <= v; i++) {
for (int j = 1; j <= v; j++) {
adj[i][j] = sc.nextInt();
}
}
System.out.println("Articulation points are:");
// Finding articulation points
for (int i = 1; i <= v; i++) {
boolean[] visited = new boolean[v + 1];
int components = 0;
// Counting connected components when vertex i is ignored
for (int j = 1; j <= v; j++) {
if (j != i && !visited[j]) {
dfs(j, visited, adj, v, i);
components++;
}
}
// If more than one component, i is an articulation point
if (components > 1) {
System.out.println(i);
}
}
}
private static void dfs(int curr, boolean[] visited, int[][] adj, int v, int ignore) {
visited[curr] = true;
for (int k = 1; k <= v; k++) {
if (adj[curr][k] == 1 && k != ignore && !visited[k]) {
dfs(k, visited, adj, v, ignore);
}
}
}
}
4.prims*************************************************************************
import java.util.*;
public class Prims {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of vertices: ");
int n = sc.nextInt();
int[][] graph = new int[n][n];
System.out.println("Enter adjacency matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
graph[i][j] = sc.nextInt();
}
}
// Arrays to store the MST data
boolean[] inMST = new boolean[n];
int[] key = new int[n];
int[] parent = new int[n];
// Initialize keys as infinite, and select the first vertex to start
Arrays.fill(key, Integer.MAX_VALUE);
key[0] = 0;
parent[0] = -1;
// Prim's algorithm loop
for (int i = 0; i < n - 1; i++) {
int u = minKey(key, inMST, n); // Find vertex with minimum key value
inMST[u] = true; // Include this vertex in MST
// Update the key and parent arrays
for (int v = 0; v < n; v++) {
if (graph[u][v] != 0 && !inMST[v] && graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
}
// Output the edges of the MST
int totalWeight = 0;
System.out.println("Edge \tWeight");
for (int i = 1; i < n; i++) {
System.out.println(parent[i] + " - " + i + "\t" + graph[i][parent[i]]);
totalWeight += graph[i][parent[i]];
}
System.out.println("Total weight of MST: " + totalWeight);
}
// Function to find the vertex with the minimum key value
static int minKey(int[] key, boolean[] inMST, int n) {
int min = Integer.MAX_VALUE, minIndex = -1;
for (int v = 0; v < n; v++) {
if (!inMST[v] && key[v] < min) {
min = key[v];
minIndex = v;
}
}
return minIndex;
}
}
5.knapsack*****************************************************************
import java.util.*;
public class Knapsack1 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of objects");
int n = sc.nextInt();
int[] p = new int[n];
int[] w = new int[n];
System.out.println("Enter the item weight and value:");
for (int i = 0; i < n; i++) {
System.out.println("Item " + (i + 1) + " weight:");
w[i] = sc.nextInt();
System.out.println("Item " + (i + 1) + " profit:");
p[i] = sc.nextInt();
}
System.out.println("Enter maximum knapsack capacity:");
int m = sc.nextInt();
sort(w, p);
double maxProfit = 0;
double remainingCapacity = m;
System.out.println("Selected items:");
for (int i = 0; i < w.length; i++) {
if (remainingCapacity >= w[i]) {
maxProfit += p[i];
remainingCapacity -= w[i];
System.out.println("Added item with weight " + w[i] + " and profit " + p[i]);
} else {
double fraction = remainingCapacity / (double) w[i];
maxProfit += p[i] * fraction;
System.out.println(
"Added fraction: " + fraction + " of item with weight " + w[i] + " and profit " + p[i]);
break;
}
}
System.out.println("Maximum profit: " + maxProfit);
}
public static void sort(int[] w, int[] p) {
// Sort items based on profit-to-weight ratio in descending order
for (int i = 0; i < w.length - 1; i++) {
for (int j = i + 1; j < w.length; j++) {
double ratio1 = (double) p[i] / w[i];
double ratio2 = (double) p[j] / w[j];
if (ratio1 < ratio2) {
// Swap weights
int tempW = w[i];
w[i] = w[j];
w[j] = tempW;
// Swap profits
int tempP = p[i];
p[i] = p[j];
p[j] = tempP;
}
}
}
}
}
6.job sequencing*********************************************************
import java.util.Scanner;
public class JobSequencing
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of jobs: ");
int n = sc.nextInt();
int[] d = new int[n + 1];
int[] profits = new int[n + 1];
for (int i = 0; i < n; i++)
{
System.out.println("Enter the profits and deadlines of Job: " + (i + 1));
profits[i + 1] = sc.nextInt();
d[i + 1] = sc.nextInt();
}
// Arranging profits in descending order- therefore swaping deadlines too
for (int i = 1; i < n; i++)
{
for (int j = 1; j < n; j++)
{
if (profits[j] < profits[j + 1])
{
int temp = profits[j];
profits[j] = profits[j + 1];
profits[j + 1] = temp;
temp = d[j];
d[j] = d[j + 1];
d[j + 1] = temp;
}
}
}
// optimal sol logic
int[] j = new int[n + 1];
j[0] = 0;
d[0] = 0;
j[1] = 1;
int k = 1;
for (int i = 2; i <= n; i++)
{
int r = k;
while ((d[j[r]] > d[i]) && d[j[r]] != r)
{
r--;
}
if ((d[j[r]] <= d[i]) && d[i] > r)
{
for (int x = k; x >= r + 1; x--)
{
j[x + 1] = j[x];
}
j[r + 1] = i;
k++;
}
}
int profit = 0;
System.out.println("Final Job Sequence: ");
for (int i = 1; i < n + 1; i++)
{
System.out.println(j[i] + " ");
profit +=profits[j[i]];
}
System.out.println(profit);
}
}
7.shortestpath ****************************************************************
import java.util.*;
public class Source {
private static final int INF = Integer.MAX_VALUE; // Constant for infinity
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of vertices: ");
int n = scanner.nextInt(); // Number of vertices
int[][] graph = new int[n][n]; // Initialize the adjacency matrix
// Input graph values from the user
System.out.println("Enter the adjacency matrix (0 for no edge):");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
graph[i][j] = scanner.nextInt();
}
}
single(graph, n, 0); // Start from vertex 0
scanner.close();
}
public static void single(int[][] graph, int n, int start) {
int[] dist = new int[n]; // Distance from source to each vertex
boolean[] s = new boolean[n]; // Track visited vertices
// Initialize distances based on direct edges from the start vertex
for (int i = 0; i < n; i++) {
dist[i] = (graph[start][i] != 0) ? graph[start][i] : INF;
s[i] = false;
}
dist[start] = 0; // Distance to the source is 0
s[start] = true; // Mark the starting vertex as visited
int count = 0;
do {
int u = minDistance(dist, s, n);
s[u] = true; // Mark the vertex as visited
// Update the distance of the adjacent vertices
for (int v = 0; v < n; v++) {
if (!s[v] && graph[u][v] != 0 && dist[u] != INF && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
count++;
} while (count < n - 1);
// Print the distances and calculate the sum
int totalDistance = 0;
System.out.println("Vertex Distance from Source");
for (int i = 0; i < n; i++) {
if (dist[i] != INF) {
totalDistance += dist[i];
}
}
// Print the total distance
System.out.println("Total distance from source: " + totalDistance);
}
// Function to find the vertex with the minimum distance value
private static int minDistance(int[] dist, boolean[] s, int n) {
int min = INF, minIndex = -1;
for (int v = 0; v < n; v++) {
if (!s[v] && dist[v] <= min) {
min = dist[v];
minIndex = v;
}
}
return minIndex;
}
}
////////******* IIFE IN JS ************///////////
// why IIFE is used in js ??
// IIFE function is used when we want to invoke function immediately and also removes pollution of global scope variables
// 1 method
// NAMED IIFE
(function chai(){
console.log("db connected");
})(); // // here we used ; because there is 2 IIFE in a programme
// here first() is for creating function and second () for calling the function
// 2 method
// UNNAMED IIFE
( (name) => { //name is function parameter in which we put value ,
console.log(`db connected${name}`);
})("tanishq"); // here tanishq is just passing value in name
// here first() is for creating function and second () for calling the function
////////*******THIS IN JS ************///////////
const user ={
username: "hitesh",
price: 999,
welcomeMessage: function(){
console.log(`${this.username}, welcome to website `);
// console.log(this); // it will print whole function
}
}
user.welcomeMessage() // hitesh, welcome to website
user.username = "harry"
user.welcomeMessage() // harry, welcome to website
console.log(this); // OUTPUT = {}
const chai = () => {
let username = "hitesh "
console.log(this);
}
chai()
///////////////********ARROW FUNCTION IN JS************//////////////
//// FIRST METHOD
const add2 = (num1 , num2 ) =>{ // implict function (when we use parethensis{} we have to write return also )
return num1 + num2
}
console.log(add2(2,3));
//// SECOND METHOD
const addtwo = (num1 , num2 ) => (num1 + num2) // explict function (when we don't use parethensis{} we have no need to write return also )
console.log(addtwo(5,3));
////////
Laravel Cache Clear php artisan optimize:clear php artisan cache:clear php artisan config:clear php artisan config:cache php artisan view:clear php artisan view:cache php artisan route:clear php artisan route:cache php artisan event:clear php artisan event:cache php artisan clear-compiled Clearing Composer Cache composer dump-autoload composer clear-cache composer clearcache composer cc Schedule Backup DB php artisan backup:run php artisan backup:run --only-db php artisan backup:clean
Secure File Transfer Protocol (SFTP) sftp> put – Upload file sftp> get – Download file sftp> cd path – Change remote directory to ‘path’ sftp> pwd – Display remote working directory sftp> lcd path – Change the local directory to ‘path’ sftp> lpwd – Display local working directory sftp> ls – Display the contents of the remote working directory sftp> lls – Display the contents of the local working directory sftp -P port usrename@your_server_ip_or_domain I.e sftp -P 39922 root@45.58.35.53 zip -r filename.zip /path/to/folder1 Secure Copy Protocol (SCP) -p: Use passive mode. This is not directly related to specifying the port but is a commonly used option for FTP connections. -u username: Specify the username to use for the FTP connection. hostname: The IP address or domain name of the FTP server. port: The port number on which the FTP server is running. -P 39922: Specifies the SSH port on the remote server (replace 39922 with your actual port if different). root: The username on the remote server. 45.58.35.53: The IP address or hostname of the remote server. /path/on/remote/server/file: The path to the file on the remote server. /path/on/local/machine: The destination path on your local machine. For upload File scp destinationor source scp -P 39922 /path/on/local/machine/file root@45.58.35.55:/path/on/remote/server scp -P 39922 /home/hur/quickinvoice_details_202309202129.sql root@45.58.35.53:/var/www/html/ For Download File scp source destinationor scp -P 39922 root@45.58.35.55:/path/on/remote/server/file /path/on/local/machine I.e scp -P 39922 root@45.58.35.53:/var/www/html/quickinvoice_details_202309202129.sql /home/hur/Music Rsync to copy or sync files between your servers rsync [option] [source] [destination] -a | copy files recursively -h | produce a readable output –progress | displays the process while the command is being run -q | processes running in the background will not be shown -v | processes that are run will be written out for the user to read -z | compress the data rsync [option] [source] user@hostname-or-ip:[destination path] rsync -avh root@5.252.161.46:/home/receive-rsync/ /home/test-rsync/ I.e rsync -e "ssh -p 39922" root@45.58.35.53:/var/www/html/quickinvoice_details_202309202129.sql /home/hur/Videos
sudo nano /etc/php/8.3/cli/php.ini sudo update-alternatives --config php sudo apt-get install php8.3-grpc php -m | grep grpc For uninstall sudo apt-get remove php8.3-grpc
{
"blocks": [
{
"type": "section",
"text": {
"type": "plain_text",
"text": "Stay In the Know - November | 2024 \n\n Stay in the loop about what’s happening at the office such as upcoming visitors, onsite meetings, lunches, and more. Don’t miss out—click to subscribe below!",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": ":google-workspace-calendar: DEN Happenings calendar"
},
"accessory": {
"type": "button",
"text": {
"type": "plain_text",
"text": "Click Me",
"emoji": true
},
"value": "click_me_123",
"url": "https://calendar.google.com/calendar/u/0/embed?src=xero.com_5r7ut3e120f1mfj5aptg90tm34@group.calendar.google.com&ctz=America/Denver",
"action_id": "button-action"
}
},
{
"type": "divider"
},
{
"type": "rich_text",
"elements": [
{
"type": "rich_text_section",
"elements": [
{
"type": "text",
"text": " "
},
{
"type": "text",
"text": "Announcments",
"style": {
"bold": true
}
}
]
}
]
},
{
"type": "section",
"text": {
"type": "plain_text",
"text": " :door: New Doors - You should see our new doors installed. Stay tuned for a Q&A and some FAQ info on the new doors, processes and expectations.",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "plain_text",
"text": ":WX:Boost Days - Boost days have been extended until March 2025 due to the great feedback gathered. Yay!",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "plain_text",
"text": ":celebrate:End of Year party - Don't forget to RSVP for the Denver party at The Lob on 22 Nov. A Sprinkle of magic and lots of fun to be had! ",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "plain_text",
"text": ":turkey: Please emoji a Turkey on this post to let us know if you will be in office for breakfast on Nov 26th so we can determine if we will run service that day. Nov 28th and 29th the office will be closed for the Holiday.",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "plain_text",
"text": ":wave: Keep an eye our for visitors from the US Roadshow and US XPAc visit duriing the week of the 18th.",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "plain_text",
"text": ":calendar-date-14: Our next US Stand Up is Nov 14 at 2PM MDT. Add it to your calendar below and join us for a quick meeting with some fun updates. This is a monthly meeting and we would love to see you there!",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "Add to Calendar"
},
"accessory": {
"type": "button",
"text": {
"type": "plain_text",
"text": "Click Me",
"emoji": true
},
"value": "meet.google.com/awh-gacj-hfw",
"action_id": "meet.google.com/awh-gacj-hfw"
}
},
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "plain_text",
"text": "Breakfast & Lunch Schedule\n\n :calendar-date-5: Trez banderas\n\n:calendar-date-7: Costa Vida\n\n:calendar-date-12: That Personal Touch\n\n:calendar-date-14: Lazo Empanadas\n\n:calendar-date-19: Renegade Burrito\n\n:calendar-date-21: Paradise Biryani\n\n:calendar-date-26: TBD - Please emoji :turkey: if you will be here.\n\n:calendar-date-28: No Service - Holiday",
"emoji": true
}
},
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "plain_text",
"text": "Boost Days Café - Tue and Thur\n\n On Boost Days enjoy your free cup of coffee on or beverage on Xero from Blue Sparrow on the 1st floor Lobby.Show your ID :badge: and don't forget to hit the 12% tip as this is included in our budget. ",
"emoji": true
}
},
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "plain_text",
"text": "WX offers comprehensive event planning services, including:\n\n:dot:Assistance with logistics and coordination\n\n:dot:Access to a network of vendors for catering, supply ordering, etc.",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "plain_text",
"text": "Note: Are you traveling to a Xero office? Please notify Wx ahead of your visit to ensure access. Even if you don’t need our assistance but are using the office space, kindly inform WX.\n\n:pushpin: Have something important to add to our calendar? Don’t hesitate to reach out if you have any questions or concerns. Get in touch with us at via the Help Centre or at #hello-px\n\nWishing everyone a successful month ahead!",
"emoji": true
}
}
]
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Scientific Calculator</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.calculator {
width: 300px;
background: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.2);
}
.display {
width: 100%;
height: 50px;
margin-bottom: 10px;
font-size: 1.5rem;
text-align: right;
border: 1px solid #ddd;
border-radius: 5px;
padding: 5px;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
}
.button {
height: 50px;
background: #2196f3;
color: white;
font-size: 1.2rem;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background 0.3s;
}
.button:hover {
background: #1976d2;
}
.button.clear {
background: #f44336;
}
.button.clear:hover {
background: #d32f2f;
}
</style>
</head>
<body>
<div class="calculator">
<input type="text" id="display" class="display" disabled>
<div class="buttons">
<button class="button" onclick="append('7')">7</button>
<button class="button" onclick="append('8')">8</button>
<button class="button" onclick="append('9')">9</button>
<button class="button" onclick="append('/')">/</button>
<button class="button" onclick="append('4')">4</button>
<button class="button" onclick="append('5')">5</button>
<button class="button" onclick="append('6')">6</button>
<button class="button" onclick="append('*')">*</button>
<button class="button" onclick="append('1')">1</button>
<button class="button" onclick="append('2')">2</button>
<button class="button" onclick="append('3')">3</button>
<button class="button" onclick="append('-')">-</button>
<button class="button" onclick="append('0')">0</button>
<button class="button" onclick="append('.')">.</button>
<button class="button" onclick="calculate()">=</button>
<button class="button" onclick="append('+')">+</button>
<button class="button clear" onclick="clearDisplay()">C</button>
<button class="button" onclick="append('%')">%</button>
</div>
</div>
<script>
const display = document.getElementById('display');
function append(value) {
display.value += value;
}
function calculate() {
try {
display.value = eval(display.value);
} catch (error) {
display.value = "Error";
}
}
function clearDisplay() {
display.value = '';
}
</script>
</body>
</html>
java
Copy code
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
PrintWriter out = response.getWriter();
out.println("Hello from HttpServlet!");
}
}
Step 1: Install Apache Tomcat
Download and install Apache Tomcat.
Set up Tomcat by configuring environment variables (CATALINA_HOME and JAVA_HOME), if needed.
Step 2: Save and Structure Your Servlet
Save the servlet code in a file named HelloServlet.java.
Organize it within the WEB-INF/classes directory inside your web application folder. For example:
Copy code
your-webapp
├── WEB-INF
│ ├── classes
│ │ └── HelloServlet.java
│ └── web.xml
Step 3: Compile the Servlet
Open a terminal or command prompt, navigate to WEB-INF/classes, and compile:
bash
Copy code
javac -classpath <path-to-servlet-api.jar> HelloServlet.java
Replace <path-to-servlet-api.jar> with the path to servlet-api.jar in the lib folder of your Tomcat installation.
Step 4: Configure web.xml
In the WEB-INF folder, create or update web.xml with the servlet mapping:
xml
Copy code
<web-app>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
Step 5: Deploy and Start Tomcat
Place the your-webapp folder in Tomcat’s webapps directory.
Start Tomcat by running startup.sh (Linux/Mac) or startup.bat (Windows) in the bin folder.
Step 6: Access the Servlet
Open a browser and navigate to: http://localhost:8080/your-webapp/hello
Expected Output
If everything is set up correctly, you should see:
plaintext
Copy code
Hello from HttpServlet!
vSTEP 1: Create an Empty Activity
STEP 2: Create a raw resource folder
Create a raw resource folder under the res folder and copy one of
the .mp3 file extension.
Right Click on "raw" folder ----> select "new" ---> click on "Android
Resource Directory" ----> Change resource type values to "raw" ---->
then finally click "OK".
Download required audio MP3 file (Size <500kb approximately) from
Internet , right click and Paste it in "raw" folder whatever newly created.
--------------------------------------------------------------------
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="HardcodedText">
<TextView
android:id="@+id/headingText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="32dp"
android:text="MEDIA PLAYER"
android:textSize="18sp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/headingText"
android:layout_marginTop="16dp"
android:gravity="center_horizontal">
<Button
android:id="@+id/stopButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:backgroundTint="@color/colorPrimary"
android:text="STOP"
android:textColor="@android:color/white"
tools:ignore="ButtonStyle,TextContrastCheck" />
<Button
android:id="@+id/playButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:backgroundTint="@color/colorPrimary"
android:text="PLAY"
android:textColor="@android:color/white"
tools:ignore="ButtonStyle,TextContrastCheck" />
<Button
android:id="@+id/pauseButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="@color/colorPrimary"
android:text="PAUSE"
android:textColor="@android:color/white"
tools:ignore="ButtonStyle,TextContrastCheck" />
</LinearLayout>
</RelativeLayout>
MainActivity.kt
// As per your application (or) file name package name will displayed
package com.example.mediaplayer
import android.media.MediaPlayer
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// create an instance of mediplayer for audio playback
val mediaPlayer: MediaPlayer =
MediaPlayer.create(applicationContext, R.raw.music)
// register all the buttons using their appropriate IDs
val bPlay: Button = findViewById(R.id.playButton)
val bPause: Button = findViewById(R.id.pauseButton)
val bStop: Button = findViewById(R.id.stopButton)
// handle the start button to
// start the audio playback
bPlay.setOnClickListener {
// start method is used to start
// playing the audio file
mediaPlayer.start()
}
// handle the pause button to put the
// MediaPlayer instance at the Pause state
bPause.setOnClickListener {
// pause() method can be used to
// pause the mediaplyer instance
mediaPlayer.pause()
}
// handle the stop button to stop playing
// and prepare the mediaplayer instance
// for the next instance of play
bStop.setOnClickListener {
// stop() method is used to completely
// stop playing the mediaplayer instance
mediaPlayer.stop()
// after stopping the mediaplayer instance
// it is again need to be prepared
// for the next instance of playback
mediaPlayer.prepare()
ACTIVITY_MAIN.XML:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ACTIVITY LIFE CYCLE DEMO"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.5" />
</androidx.constraintlayout.widget.ConstraintLayout>
MAINACTIVITY.kt
package com.example.myapp_activitylifecyclemethods
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Toast.makeText(applicationContext,"ONCREATE()
CALLED",Toast.LENGTH_SHORT).show()
}
override fun onStart() {
super.onStart()
Toast.makeText(applicationContext,"ONSTART()
CALLED",Toast.LENGTH_SHORT).show()
}
override fun onRestart() {
super.onRestart()
Toast.makeText(applicationContext,"ONRESTART()
CALLED",Toast.LENGTH_SHORT).show()
}
override fun onResume() {
super.onResume()
Toast.makeText(applicationContext,"ONRESUME()
CALLED",Toast.LENGTH_SHORT).show()
}
override fun onPause() {
super.onPause()
Toast.makeText(applicationContext,"ONPAUSE()
CALLED",Toast.LENGTH_SHORT).show()
}
override fun onStop() {
super.onStop()
Toast.makeText(applicationContext,"ONSTOP()
CALLED",Toast.LENGTH_SHORT).show()
}
override fun onDestroy() {
super.onDestroy()
Toast.makeText(applicationContext,"ONDESTROY()
CALLED",Toast.LENGTH_SHORT).show()
}
}
java
Copy code
import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;
public class MyServlet implements Servlet {
public void init(ServletConfig config) throws ServletException {}
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
PrintWriter out = res.getWriter();
out.println("Hello Servlet Lifecycle!");
}
public void destroy() {}
public ServletConfig getServletConfig() { return null; }
public String getServletInfo() { return null; }
}
Step 1: Install Apache Tomcat
Download and install Apache Tomcat.
Set up Tomcat by configuring the environment variables (CATALINA_HOME and JAVA_HOME), if necessary.
Step 2: Save Your Java Code
Save your servlet code in a file named MyServlet.java.
Ensure that this file is located in the WEB-INF/classes directory within your web application directory
structure. For example:
Copy code
your-webapp ├── WEB-INF │ ├── classes │ │ └── MyServlet.java │ └── web.xml
Step 3: Compile the Servlet
Open a terminal or command prompt and navigate to the WEB-INF/classes directory.
Compile the servlet:
bash
Copy code
javac -classpath <path-to-servlet-api.jar> MyServlet.java
Replace <path-to-servlet-api.jar> with the path to the servlet-api.jar file in your Tomcat installation, typically
located in the lib folder.
Step 4: Configure web.xml
In the WEB-INF folder, create or update the web.xml file with the following content:
xml
Copy code
<web-app> <servlet>
class>
<servlet-name>MyServlet</servlet-name>
</servlet> <servlet-mapping>
<servlet-class>MyServlet</servlet
<servlet-name>MyServlet</servlet-name>
pattern>/myservlet</url-pattern> </servlet-mapping> </web-app>
This configuration maps the servlet to the URL path /myservlet.
Step 5: Deploy and Run
<url
Copy your web application folder (your-webapp) into the webapps directory of your Tomcat installation.
Start Tomcat by running the startup.sh (Linux/Mac) or startup.bat (Windows) file located in the bin directory
of your Tomcat installation.
Open a web browser and navigate to http://localhost:8080/your-webapp/myservlet.
Expected Output
If the servlet is configured and deployed correctly, you should see:
plaintext
Copy code
Hello Servlet Lifecycle!
If there’s an error, the Tomcat logs (located in the logs directory of your Tomcat installation) will contain
information to help you debug.
java
Copy code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class JDBCPreparedStatementExample {
public static void main(String[] args) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "user",
"password");
PreparedStatement pstmt = con.prepareStatement("INSERT INTO books (title, author) VALUES (?, ?)");
pstmt.setString(1, "Java Programming");
pstmt.setString(2, "Author Name");
pstmt.executeUpdate();
System.out.println("Data inserted successfully");
} catch (Exception e) {
System.out.println(e);
}
}
}
Set Up Your Database:
Ensure you have a MySQL server running on localhost with a database named testdb.
Create a books table with at least a title column:
sql
Copy code
CREATE TABLE books (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL
);
Compile the java code in cmd and expected output
Data inserted successfully
[OR]
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class App {
public static void main(String[] args) {
// Database connection details
String url = "jdbc:mysql://localhost:3306/testdb"; // Replace with your DB name
String user = "root"; // Replace with your DB username
String password = "Varun13@"; // Replace with your DB password
// SQL queries
String insertQuery = "INSERT INTO books (title, author) VALUES (?, ?)";
String updateQuery = "UPDATE books SET author = ? WHERE id = ?";
String deleteQuery = "DELETE FROM books WHERE id = ?";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
System.out.println("Connected to the database!");
// INSERT operation
try (PreparedStatement insertStmt = conn.prepareStatement(insertQuery)) {
insertStmt.setString(1, "John Doe");
insertStmt.setString(2, "john.doe@example.com");
int rowsInserted = insertStmt.executeUpdate();
System.out.println(rowsInserted + " row(s) inserted.");
}
// UPDATE operation
try (PreparedStatement updateStmt = conn.prepareStatement(updateQuery)) {
updateStmt.setString(1, "john.newemail@example.com");
updateStmt.setInt(2, 1); // Assuming user with ID 1 exists
int rowsUpdated = updateStmt.executeUpdate();
System.out.println(rowsUpdated + " row(s) updated.");
}
// DELETE operation
try (PreparedStatement deleteStmt = conn.prepareStatement(deleteQuery)) {
deleteStmt.setInt(1, 1); // Assuming user with ID 1 exists
int rowsDeleted = deleteStmt.executeUpdate();
System.out.println(rowsDeleted + " row(s) deleted.");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
star
photo_camera
Fri Nov 01 2024 10:28:22 GMT+0000 (Coordinated Universal Time) https://techcommunity.microsoft.com/t5/discussions/add-import-export-flags-option/m-p/1118546#M22328
star
photo_camera
Fri Nov 01 2024 05:15:01 GMT+0000 (Coordinated Universal Time) https://developer.chrome.com/docs/extensions/reference/manifest/sandbox?thumb


