import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.navigation.NavController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.example.prog2.ui.theme.Prog2Theme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContent { val nav_Controller = rememberNavController() NavHost(navController = nav_Controller, startDestination = "fragment1") { composable("fragment1") { Fragment1(nav_Controller) } composable("fragment2") { Fragment2(nav_Controller) } } } } } @Composable fun Fragment1(navController: NavController){ Column { Button(onClick={ navController.navigate("fragment2")}) { Text(text = "Navigate to fragment2 ") } } } @Composable fun Fragment2(navController: NavController) { Row(horizontalArrangement = Arrangement.SpaceEvenly){ Button(onClick = { navController.navigateUp() }) { Text(text = "Back to Fragment 1") } } }
/////////*********** LOOPS FOR ARRAYS IN JS //////////////// // for of const arr = [1,3,3,4,5] for(const n of arr){ // n is just a variable in which array elements is stored console.log(n); // OUTPUT = 1 3 3 4 5 } const greet = "hello world" for(const greetings of greet){ // greetings is just a variable in which array elements is stored console.log(`the value of greet ${greetings}`); } /// Maps (always take different values means no repetation and always print in the order they re saved ) maps are not itterable too const map = new Map(); map.set('IN', "INDIA"); map.set('FR', "FRANCE"); map.set('US', "UNITED STATES OF AMERICA"); console.log(map); for(const[key,value] of map){ console.log(key,":->",value) }// OUTPUT = IN :-> INDIA FR :-> FRANCE US :-> UNITED STATES OF AMERICA
// MainActivity.kt package com.example.dbtest import android.os.Bundle import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.* import androidx.compose.material3.Button import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.room.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext // Room Database-related code (User entity, DAO, and Database class) // User data class representing the database table @Entity(tableName = "users") data class User( @PrimaryKey(autoGenerate = true) val uid: Int = 0, val username: String, val phone: String ) // DAO interface for database operations @Dao interface UserDAO { @Insert suspend fun insert(user: User) } // Room Database class @Database(entities = [User::class], version = 1) abstract class UserDatabase : RoomDatabase() { abstract fun userDao(): UserDAO companion object { @Volatile private var INSTANCE: UserDatabase? = null fun getInstance(context: android.content.Context): UserDatabase { return INSTANCE ?: synchronized(this) { val instance = Room.databaseBuilder( context.applicationContext, UserDatabase::class.java, "user_database" ).build() INSTANCE = instance instance } } } } // Main Activity to set up the content and provide the database instance class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val database = UserDatabase.getInstance(this) setContent { InsertRecord(database) } } } // Composable function for inserting user data @Composable fun InsertRecord(database: UserDatabase) { val context = LocalContext.current val userDao = database.userDao() var name by remember { mutableStateOf("") } var phone by remember { mutableStateOf("") } val scope = rememberCoroutineScope() Column( modifier = Modifier .fillMaxSize() .padding(16.dp) ) { Text(text = "Enter your details here") Spacer(modifier = Modifier.height(25.dp)) OutlinedTextField( value = name, onValueChange = { name = it }, label = { Text(text = "Enter your name") }, modifier = Modifier.fillMaxWidth() ) Spacer(modifier = Modifier.height(25.dp)) OutlinedTextField( value = phone, onValueChange = { phone = it }, label = { Text(text = "Enter your phone number") }, modifier = Modifier.fillMaxWidth() ) Spacer(modifier = Modifier.height(25.dp)) Button(onClick = { scope.launch(Dispatchers.IO) { // Insert user data in the database userDao.insert(User(username = name, phone = phone)) // Display Toast on the main thread withContext(Dispatchers.Main) { Toast.makeText(context, "Record Inserted Successfully", Toast.LENGTH_LONG).show() } } }) { Text(text = "Insert Now") } } } //Plugins //kotlin("kapt") //Dependencies //val room_version = "2.6.1" // implementation("androidx.room:room-runtime:$room_version") // kapt("androidx.room:room-compiler:$room_version") // implementation("androidx.room:room-ktx:$room_version")
show databases; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | test | +--------------------+ 4 rows in set (0.01 sec) mysql> create database varshitha; Query OK, 1 row affected (0.02 sec) mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | test | | varshitha | +--------------------+ 5 rows in set (0.00 sec) mysql> use varshitha; Database changed mysql> show tables; +---------------------+ | Tables_in_varshitha | +---------------------+ | students | +---------------------+ 1 row in set (0.02 sec) mysql> desc students; +-------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(50) | NO | | NULL | | | age | int(11) | YES | | NULL | | | grade | varchar(10) | YES | | NULL | | +-------+-------------+------+-----+---------+----------------+ 4 rows in set (0.01 sec) mysql> select * from students; +----+-------+------+-------+ | id | name | age | grade | +----+-------+------+-------+ | 1 | Alice | 20 | A | | 2 | Bob | 22 | B | +----+-------+------+-------+ 2 rows in set (0.00 sec) mysql> DELIMITER // mysql> CREATE PROCEDURE selectGradeAStudents() -> BEGIN -> SELECT * FROM Students WHERE grade = 'A'; -> END // Query OK, 0 rows affected (0.00 sec) mysql> DELIMITER ; mysql> mysql> DELIMITER // mysql> CREATE FUNCTION getAverageAgeByGrade(gradeInput VARCHAR(10)) -> RETURNS DOUBLE -> BEGIN -> DECLARE avgAge DOUBLE; -> SELECT AVG(age) INTO avgAge FROM Students WHERE grade = gradeInput; -> RETURN avgAge; -> END // Query OK, 0 rows affected (0.00 sec) mysql> DELIMITER ;
package task11; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; public class metadata { // Database URL, user, and password static final String JDBC_URL = "jdbc:mysql://localhost:3306/varshitha"; // Replace with your database name static final String JDBC_USER = "root"; // Replace with your username static final String JDBC_PASSWORD = "root"; // Replace with your password public static void main(String[] args) { try (Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD)) { // Get database metadata DatabaseMetaData dbMetaData = connection.getMetaData(); // Display general database information System.out.println("Database Product Name: " + dbMetaData.getDatabaseProductName()); System.out.println("Database Product Version: " + dbMetaData.getDatabaseProductVersion()); System.out.println("Database Driver Name: " + dbMetaData.getDriverName()); System.out.println("Database Driver Version: " + dbMetaData.getDriverVersion()); // Retrieve and display table metadata System.out.println("\nTables in the database:"); ResultSet tables = dbMetaData.getTables(null, null, "%", new String[] { "TABLE" }); while (tables.next()) { String tableName = tables.getString("TABLE_NAME"); System.out.println("Table: " + tableName); // Retrieve and display column metadata for each table ResultSet columns = dbMetaData.getColumns(null, null, tableName, "%"); while (columns.next()) { String columnName = columns.getString("COLUMN_NAME"); String columnType = columns.getString("TYPE_NAME"); int columnSize = columns.getInt("COLUMN_SIZE"); System.out.println(" Column: " + columnName + " - Type: " + columnType + " - Size: " + columnSize); } columns.close(); } tables.close(); } catch (SQLException e) { System.out.println("SQL Exception: " + e.getMessage()); } } }
package task10; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class updandscroll { // Database credentials and URL static final String JDBC_URL = "jdbc:mysql://localhost:3306/varshitha"; // Replace with your database name static final String JDBC_USER = "root"; // Replace with your MySQL username static final String JDBC_PASSWORD = "root"; // Replace with your MySQL password public static void main(String[] args) { try (Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD); Statement statement = connection.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, // Scrollable ResultSet ResultSet.CONCUR_UPDATABLE)) { // Updatable ResultSet // Query to select all records from Students String selectSQL = "SELECT id, name, age, grade FROM Students"; ResultSet resultSet = statement.executeQuery(selectSQL); // Scroll to last row and display data if (resultSet.last()) { System.out.println("Last Row - ID: " + resultSet.getInt("id") + ", Name: " + resultSet.getString("name") + ", Age: " + resultSet.getInt("age") + ", Grade: " + resultSet.getString("grade")); } // Move to the first row and update the age and grade resultSet.first(); resultSet.updateInt("age", resultSet.getInt("age") + 1); // Increase age by 1 resultSet.updateString("grade", "A"); // Set grade to 'A' resultSet.updateRow(); // Commit the update System.out.println("Updated first row age and grade."); // Insert a new row into the ResultSet resultSet.moveToInsertRow(); resultSet.updateInt("id", 101); // Example ID resultSet.updateString("name", "New Student"); resultSet.updateInt("age", 20); resultSet.updateString("grade", "B"); resultSet.insertRow(); System.out.println("Inserted new row."); // Display all rows after the updates resultSet.beforeFirst(); // Move cursor to the beginning System.out.println("Updated Students Table:"); while (resultSet.next()) { System.out.println("ID: " + resultSet.getInt("id") + ", Name: " + resultSet.getString("name") + ", Age: " + resultSet.getInt("age") + ", Grade: " + resultSet.getString("grade")); } } catch (SQLException e) { System.out.println("SQL Exception: " + e.getMessage()); } } }
package task9; import java.sql.Connection; import java.sql.DriverManager; import java.sql.CallableStatement; import java.sql.ResultSet; import java.sql.SQLException; public class callablefunctions { // Database credentials and URL static final String JDBC_URL = "jdbc:mysql://localhost:3306/varshitha"; // Replace with your database name static final String JDBC_USER = "root"; // Replace with your MySQL username static final String JDBC_PASSWORD = "root"; // Replace with your MySQL password public static void main(String[] args) { // SQL query to call the stored function String callFunctionSQL = "{? = call getAverageAgeByGrade(?)}"; try (Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD); CallableStatement callableStatement = connection.prepareCall(callFunctionSQL)) { // Register the output parameter (the average age) callableStatement.registerOutParameter(1, java.sql.Types.DOUBLE); // Set the input parameter (the grade for which we want the average age) callableStatement.setString(2, "A"); // Change the grade as needed // Execute the function callableStatement.execute(); // Retrieve the output parameter double averageAge = callableStatement.getDouble(1); System.out.println("Average age of students with grade 'A': " + averageAge); } catch (SQLException e) { System.out.println("SQL Exception: " + e.getMessage()); } } }
package task9; import java.sql.Connection; import java.sql.DriverManager; import java.sql.CallableStatement; import java.sql.ResultSet; import java.sql.SQLException; public class callableprocedures { // Database credentials and URL static final String JDBC_URL = "jdbc:mysql://localhost:3306/varshitha"; // Replace with your database name static final String JDBC_USER = "root"; // Replace with your MySQL username static final String JDBC_PASSWORD = "root"; // Replace with your MySQL password public static void main(String[] args) { // SQL query to call the stored procedure String callProcedureSQL = "{call selectGradeAStudents()}"; try (Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD); CallableStatement callableStatement = connection.prepareCall(callProcedureSQL); ResultSet resultSet = callableStatement.executeQuery()) { System.out.println("Students with Grade A:"); while (resultSet.next()) { // Assuming the Students table has columns: id, name, age, and grade int id = resultSet.getInt("id"); String name = resultSet.getString("name"); int age = resultSet.getInt("age"); String grade = resultSet.getString("grade"); System.out.printf("ID: %d, Name: %s, Age: %d, Grade: %s%n", id, name, age, grade); } } catch (SQLException e) { System.out.println("SQL Exception: " + e.getMessage()); } }
package task9; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class preparedstmt { // Database credentials and URL static final String JDBC_URL = "jdbc:mysql://localhost:3306/varshitha"; // Replace with your database name static final String JDBC_USER = "root"; // Replace with your MySQL username static final String JDBC_PASSWORD = "root"; // Replace with your MySQL password public static void main(String[] args) { // SQL query to insert data into the Students table String insertSQL = "INSERT INTO Students (name, age, grade) VALUES (?, ?, ?)"; // Try with resources to automatically close the connection and statement try (Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD); PreparedStatement preparedStatement = connection.prepareStatement(insertSQL)) { // Insert first student preparedStatement.setString(1, "Alice"); preparedStatement.setInt(2, 20); preparedStatement.setString(3, "A"); preparedStatement.executeUpdate(); System.out.println("Inserted first student: Alice"); // Insert second student preparedStatement.setString(1, "Bob"); preparedStatement.setInt(2, 22); preparedStatement.setString(3, "B"); preparedStatement.executeUpdate(); System.out.println("Inserted second student:s Bob"); } catch (SQLException e) { System.out.println("SQL Exception: " + e.getMessage()); } } }
package task8; import java.sql.*; public class jdbcex { // Database credentials and URL static final String JDBC_URL = "jdbc:mysql://localhost:3306/varshitha"; // Replace with your database name static final String JDBC_USER = "root"; // Replace with your MySQL username static final String JDBC_PASSWORD = "root"; // Replace with your MySQL password public static void main(String[] args) { try { // Load the MySQL JDBC driver Class.forName("com.mysql.cj.jdbc.Driver"); // Establish the connection Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD); System.out.println("Connected to the database."); // Create a statement object to execute SQL commands Statement statement = connection.createStatement(); // SQL query to create a table named "Students" String createTableSQL = "CREATE TABLE IF NOT EXISTS Students (" + "id INT AUTO_INCREMENT PRIMARY KEY, " + "name VARCHAR(50) NOT NULL, " + "age INT, " + "grade VARCHAR(10)" + ");"; // Execute the SQL command to create the table statement.executeUpdate(createTableSQL); System.out.println("Table 'Students' created successfully."); // Close the statement and connection statement.close(); connection.close(); } catch (SQLException | ClassNotFoundException e) { System.out.println("Error: " + e.getMessage()); } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dynamic Pricing Table</title> <style> body { font-family: Arial, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f4f4f4; margin: 0; } .pricing-table { display: flex; justify-content: space-around; width: 80%; } .card { background-color: #fff; border: 1px solid #ccc; border-radius: 10px; padding: 20px; text-align: center; transition: transform 0.3s, box-shadow 0.3s; width: 30%; box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1); } .card:hover { transform: scale(1.05); box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2); } .card.selected { background-color: #007bff; color: white; border: none; } .card.selected:hover { box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3); } .price { font-size: 2rem; margin: 10px 0; } button { padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; background-color: #007bff; color: white; transition: background-color 0.3s; } button:hover { background-color: #0056b3; } </style> </head> <body> <div class="pricing-table"> <div class="card" onclick="selectCard(this)"> <h3>Basic Plan</h3> <div class="price">$10/month</div> <p>Basic features included.</p> <button>Choose</button> </div> <div class="card" onclick="selectCard(this)"> <h3>Standard Plan</h3> <div class="price">$20/month</div> <p>Standard features included.</p> <button>Choose</button> </div> <div class="card" onclick="selectCard(this)"> <h3>Premium Plan</h3> <div class="price">$30/month</div> <p>All features included.</p> <button>Choose</button> </div> </div> <script> function selectCard(card) { // Remove 'selected' class from all cards const cards = document.querySelectorAll('.card'); cards.forEach(c => c.classList.remove('selected')); // Add 'selected' class to the clicked card card.classList.add('selected'); } </script> </body> </html>
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; } }
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