Aiml Lab Mech
Aiml Lab Mech
KOMMADI, VISAKHAPATNAM
CERTIFICATE
is a student studying
10
11
12
.
.
EXPERIMENT 1A) AIM:
Types of Elements: HTML has several types of elements, including structural elements
(such as
<html>, <head>, and <body>), text-level elements (such as <p> and <span>), and
multimedia elements (such as <img>, <audio>, and <video>).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="description" content="IEKart's is an online shopping website that sells
goods in retail. This company deals with various categories like Electronics, Clothing,
Accessories etc.">
<title>IEKart's Shopping</title>
</head>
<body>
</body>
</html>
OUTPUT
:
1.b )
AIM:
Enhance the Homepage.html of IEKart's Shopping Application by adding appropriate
sectioning elements.
DESCRIPTION:
Sectioning elements in HTML are used to divide the content of a web page into logical
sections, making it easier for users to understand and navigate the content. These
elements include <header>, <nav>, <section>, <article>, <aside>, and <footer>. The
<header> element is used to identify the header section of a page, while the <nav>
element is used to define a set of navigation links.
PROGRAM:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<header>
<nav>
</nav>
<main>
<section>
<h1>Featured Products</h1>
</section>
<section>
<h1>Categories</h1>
</section>
<section>
</section>
</main>
<aside>
</aside>
<footer>
</footer>
</body>
</html>
OUTPUT
1.c )
AIM: Make use of appropriate grouping elements such as list items to "About Us"
page of IEKart's Shopping Application
Division and Span Elements: The <div> and <span> elements are used to group
elements and apply styles or classes to them. The <div> element is a block-level
element, while the <span> element is an inline-level element.
List Element: The <ul>, <ol>, and <li> elements are used to create lists in HTML. The
<ul> element creates an unordered list, the <ol> element creates an ordered list, and the
<li> element defines each item in the list.
PROGRAM:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>About Us</h1>
<p>We are IEKart's, an online shopping website that sells goods in retail.</p>
<h2>Our Team</h2>
<ul>
</ul>
<h2>Our Mission</h2>
<ul>
<li>To continuously innovate and improve our offerings to meet the changing needs of our
customers.</li>
</ul>
</body>
</html>
OUTPUT
1.d )
AIM:
Link "Login", "SignUp" and "Track order" to "Login.html", "SignUp.html" and
"Track.html" page respectively. Bookmark each category to its details of IEKart's
Shopping application.
DESCRIPTION:
The Link element (<link>) is an HTML element used to define a relationship between
the current document and an external resource. This element is commonly used to link
stylesheets to an HTML document, allowing the page to be styled with CSS.
PROGRAM:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<ul>
<li><a href="Homepage.html">Home</a></li>
<li><a href="Products.html">Products</a></li>
<li><a href="Login.html">Login</a></li>
</ul>
<h1>About Us</h1>
<p>...</p>
<h2>Categories</h2>
<ul>
<li><a href="#electronics">Electronics</a></li>
<li><a href="#clothing">Clothing</a></li>
<li><a href="#accessories">Accessories</a></li>
</ul>
<h2 id="electronics">Electronics</h2>
<p>...</p>
<h2 id="clothing">Clothing</h2>
<p>...</p>
<h2 id="accessories">Accessories</h2>
<p>...</p>
<footer>
</footer>
</body>
</html>
OUTPUT
1.e
)
AIM: Add the © symbol in the Home page footer of IEKart's Shopping application.
DESCRIPTION:
In HTML, character entities are special codes used to represent special characters that
are not part of the standard character set. These entities are defined by their unique
entity name or a numeric code and are used to display symbols, foreign characters,
mathematical symbols, and more. Examples of character entities include < for <, > for
>, and & for &.
PROGRAM:
<footer>
</footer>
OUTPUT
1.F) AIM:
Add the global attributes such as contenteditable, spellcheck, id etc. to enhance the
Signup Page functionality of IEKart's Shopping application.
DESCRIPTION:HTML5 Global Attributes are attributes that can be used on any
HTML element and are not limited to specific elements. These attributes can be used to
provide additional information about an element, such as defining the class or id,
setting styles, and assigning event handlers. Some commonly used global attributes
include "class", "id", "style", "title", and "data-*".
PROGRAM:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>Signup</h1>
<label for="username">Username:</label>
required contenteditable="true"><br><BR>
<label for="email">Email:</label>
<br><BR>
<label for="password">Password:</label>
<br><BR>
<label for="confirm_password">Confirm Password:</label>
required><br><BR>
</form>
</body>
</html>
OUTPUT
EXPERIMENT-2A)
<!DOCTYPE html>
<head><title>Product Details</title></head>
<body>
<div class="product-details">
<h1>Product Name</h1>
<tr>
<th>Model</th>
<th>Color</th>
<th>Storage</th>
<th>Price</th>
<th>Availability</th>
</tr>
<tr>
<td>Model A</td>
<td>Black</td>
<td>64GB</td>
<td>$699</td>
<td>In stock</td>
</tr>
<tr>
<td>Model A</td>
<td>White</td>
<td>128GB</td>
<td>$799</td>
<td>In stock</td>
</tr>
<tr>
<td>64GB</td>
<td>$799</td>
<td>Out of stock</td>
</tr>
<tr>
<td>Model B</td>
<td>White</td>
<td>128GB</td>
<td>$899</td>
<td>In stock</td>
</tr></table></div></body></html>
OUTPUT
2.b)
AIM: Using the form elements create Signup page for IEKart's Shopping application.
DESCRIPTION:Form elements in HTML are used to collect user input and can be
customized with various attributes such as input type, name, placeholder, and required.
The color and date pickers allow users to choose colors and dates from a graphical
interface, while select and datalist elements provide a dropdown menu for users to select
from a pre-defined list of options
PROGRAM:
<!DOCTYPE html>
<head>
</head>
<body>
<h1>Signup</h1>
<label for="name">Name:</label>
<label for="email">Email:</label>
<label for="password">Password:</label>
</form>
</body>
</html>
OUTPUT
2.c )
AIM:Enhance Signup page functionality of IEKart's Shopping application by
adding attributes to input elements
DESCRIPTION: elements in HTML are used to collect user input and can be
customized using various attributes such as type, name, value, placeholder, autofocus,
required, disabled, and readonly. These attributes provide additional functionality and
control over how users can interact with the input element. For example, the type
attribute can specify whether the input should be a text box, checkbox, radio button, or
other types of input. The required attribute can indicate that the user must provide input
in order to submit the form, while the readonly attribute can indicate that the user cannot
modify the input value
PROGRAM:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Signup</h1>
<label for="name">Name:</label>
<label for="email">Email:</label>
<label for="password">Password:</label>
title="Password must contain at least one lowercase letter, one uppercase letter,
one number, and be at least 8 characters long"><br>
{10}$" title="Phone number must be 10 digits long and contain only numbers"><br>
</form>
</body>
</html>
OUTPU
2.D)
AIM: Add media content in a frame using audio, video, iframe elements to the Home
pageofIEKart's Shopping application.
<h2>Featured Products</h2>
<p>Check out our latest products:</p>
<ul>
<li>Product 1</li>
<li>Product 2</li>
<li>Product 3</li>
</ul>
<h2>Product Video</h2>
<video width="400" height="300" controls>
<source src="product_video.mp4"
type="video/mp4"> Your browser does
not support the video tag.
</video>
<h2>Product Audio</h2>
<audio controls>
<source src="product_audio.mp3"
type="audio/mpeg"> Your browser does
not support the audio element.
</audio>
<h2>Related Article</h2>
<iframe width="400" height="300" src="https://www.example.com/article"
frameborder="0"></iframe></body></html>
OUTPUT
EXPERIMENT 3.a ) AIM:
Write a JavaScript program to find the area of a circle using radius (var and let -
reassign and observe the difference with var and let) and PI (const)
DESCRIPTION:
In JavaScript, there are three types of identifiers: variables, functions, and labels.
Variable identifiers are used to name variables, function identifiers are used to name
functions, and label identifiers are used to label statements. Identifiers must follow
certain naming conventions, such as starting with a letter or underscore, and can contain
letters, numbers, and underscores.
PROGRAM:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="result"></p>
document.getElementById("radius").value;
document.getElementById("result").innerHTM
</script>
</body>
</html>
OUTPUT
:
3.b )
AIM:
Write JavaScript code to display the movie details such as movie name, starring,
language, and ratings. Initialize the variables with values of appropriate types. Use
template literals wherever necessary.
DESCRIPTION:
Primitive data types are the building blocks of data and include undefined, null,
boolean, number, and string. They are called "primitive" because they are immutable
and have a fixed size in memory.
Non-primitive data types include objects and arrays, and are also known as reference
types. These data types can be of any size and can be changed dynamically. They are
called "reference" types because they are not stored directly
PROGRAM:
<!DOCTYPE html>
<html>
<head>
<title>Movie Details</title>
</head>
<body>
<h1>Movie Details</h1>
<div id="movieDetails"></div>
RottenTomatoes: 91,
Metacritic: 80,
};
constmovieDetailsDiv = document.getElementById("movieDetails");
movieDetailsDiv.innerHTML = `
<h2>${movieName}</h2>
<p>Language: ${language}</p>
<p>Ratings:</p>
<ul>
<li>IMDB: ${ratings.IMDB}</li>
</ul>
`;
</script>
</body>
</html>
OUTPUT
:
3.c )
AIM:
Write JavaScript code to book movie tickets online and calculate the total price,
considering the number of tickets and price per ticket as Rs. 150. Also, apply a
festive season discount of 10% and calculate the discounted amount.
DESCRIPTION:
PROGRAM:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<form>
readonly><br><br></form>
document.getElementById("num_tickets").value; constpricePerTicket =
document.getElementById("discounted_amount").value = discountedAmount;
}
</script>
</body>
</html>
OUTPUT
3.d )
AIM:
Write a JavaScript code to book movie tickets online and calculate the total price
based on the 3 conditions: (a) If seats to be booked are not more than 2, the cost per
ticket remains Rs.
150. (b) If seats are 6 or more, booking is not allowed.
DESCRIPTION:
In JavaScript, there are two main types of statements: non-conditional statements and
conditional statements. Non-conditional statements are executed in a sequential order,
whereas conditional statements allow us to execute code based on a certain condition.
The two main types of conditional statements are "if" statements and "switch"
statements. "If" statements are used to execute a block of code if a specified condition
is true, while "switch" statements are used to perform different actions based on
different conditions
PROGRAM:
<!DOCTYPE html>
<html>
<head>
cost document.getElementById("totalCost").innerHTML =
} else {
</script>
</head>
<body>
</body>
</html>
OUTPUT
3.e )
AIM:
Write a JavaScript code to book movie tickets online and calculate the total price
based on the 3 conditions: (a) If seats to be booked are not more than 2, the cost
per ticket remains Rs. 150. (b) If seats are 6 or more, booking is not allowed
DESCRIPTION:
In JavaScript, loops are used to execute a set of statements repeatedly until a certain
condition is met. There are three types of loops in JavaScript: for loop: This loop
executes a block of code for a specified number of times. for (initialization; condition;
increment/decrement) while loop: This loop executes a block of code as long as the
condition is TRUE
do-while loop: This loop executes a block of code once before checking the condition.
If the condition is true, the loop will repeat
PROGRAM:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<p id="price"></p>
parseInt(document.getElementById("numSeats").value); let
pricePerTicket
if (numSeats<= 2) { totalPrice
= numSeats * pricePerTicket;
return;
} else {
totalPrice += pricePerTicket;
} else {
</script>
</body>
</html>
OUTPUT:
4.a )
AIM:
Write a JavaScript code to book movie tickets online and calculate the total price
based on the 3 conditions: (a) If seats to be booked are not more than 2, the cost per
ticket remains Rs.
150. (b) If seats are 6 or more, booking is not allowed.
DESCRIPTION:
Functions are reusable blocks of code that perform a specific task. In JavaScript, there
are several types of functions, including:
Named Functions: These functions are defined using the function keyword, followed
by the function name, and a pair of parentheses. They can be invoked by calling their
name.
Anonymous Functions: These functions are defined without a name, and are often used
as callbacks or event listeners.
Arrow Functions: Introduced in ES6, arrow functions are a shorthand way of writing
anonymous functions.
Function Parameters: Functions can accept one or more parameters, which act as inputs to
the function.
Nested Functions: Functions can be defined inside other functions, creating a hierarchy
of functions.
Built-in Functions: JavaScript comes with several built-in functions, such as parseInt(),
parseFloat(), and Math.random().
Variable Scope in Functions: Variables declared inside a function have local scope, and
are not accessible outside of the function. Variables declared outside of a function have
global scope, and can be accessed anywhere in the code.
To declare a function in JavaScript, use the function keyword, followed by the function
name, and a pair of parentheses. The code inside the function is enclosed in curly braces.
To invoke the function, simply call its name, optionally passing in any required
parameters.
PROGRAM:
<!DOCTYPE html>
<html>
<head>
<title>Movie Ticket Booking</title>
</head>
<body>
<h1>Movie Ticket Booking</h1>
<form>
0; if (numOfSeats<= 2) {
totalPrice = calculateCost(numOfSeats,
costPerTicket);
} else {
document.getElementById("totalPrice").value = totalPrice;
}
function calculateCost(numOfSeats, costPerTicket)
}
</script>
</body>
</html>
OUTPUT
4.b )
AIM:
Create an Employee class extending from a base class Person. Hints: (i) Create a
class Person with name and age as attributes. (ii) Add a constructor to initialize the
values
(iii) Create a class Employee extending Person with additional attributes role
DESCRIPTION:
Working with classes in JavaScript involves creating and using objects that have a
defined set of properties and behaviors. Classes are used to define the structure and
behavior of objects, and can be created and instantiated using the class keyword.
Classes in JavaScript can also inherit properties and methods from other classes, which
is known as inheritance. Inheritance allows classes to reuse code and build on existing
functionality, which can lead to more efficient and organized code.
To create a class, the class keyword is used, followed by the name of the class and a set
of curly braces. Properties and methods are defined within the class using constructor
functions and prototype methods.
To inherit from a class, the extends keyword is used to specify the class being inherited
from. Inherited properties and methods can be accessed using the super keyword
PROGRAM:
<!DOCTYPE html>
<html>
<head>
<title>Employee Information</title>
</head>
<body>
<h2>Employee Information</h2>
<div id="employee"></div>
<script> // Person
constructor(name, age)
{ this.name =
name; this.age =
age;
}
// Employee class extending from Person
this.role = role;
document.getElementById("employee").innerHTML = `Name: $
{emp.name}<br>
Age: ${emp.age}<br>
Role: ${emp.role}`;
</script></body></html>
OUTPUT:
4.c )
AIM:
Write a JavaScript code to book movie tickets online and calculate the total price
based on the 3 conditions: (a) If seats to be booked are not more than 2, the cost per
ticket remains Rs.
150. (b) If seats are 6 or more, booking is not allowed
DESCRIPTION:
In-built events are predefined actions or occurrences that can be triggered by user
actions or system events such as clicks, mouse movements, keypresses, and form
submissions. Handlers are functions that are executed in response to events.
PROGRAM:
<!DOCTYPE html>
<html>
<head>
let numOfSeats =
document.getElementById("seats").value;
at a time!");
} else {
}
document.getElementById("totalPrice").innerHTML = `Total Price: Rs.
${totalPrice}`;
}
</script>
</head>
<body>
<p id="totalPrice"></p>
</body>
</html>
OUTPUT
4.d )
AIM:
If a user clicks on the given link, they should see an empty cone, a different
heading, and a different message and a different background color. If user clicks
again, they should see a re-filled cone, a different heading, a different message,
DESCRIPTION:
Working with Objects:
Objects are one of the fundamental concepts in JavaScript, and they are used to store
and manipulate data. There are several types of objects in JavaScript, including built-in
objects, custom objects, and host objects.
Types of Objects:
Built-in Objects: These are the objects that are built into the JavaScript language, such as
Array, Date, Math, and RegExp.
Custom Objects: These are the objects that you create in your JavaScript code.
Host Objects: These are the objects that are provided by the browser or environment in
which your JavaScript code is running, such as window, document, and
XMLHttpRequest
PROGRAM:
<!DOCTYPE html>
<html>
<head>
} h1 { font-
#333;
.cone { margin:
background-color: white;
border-
radius: 50% / 100%;
position: relative;
bottom: -90px;
0.5);
.empty:after
{ content: ""
width: 160px;
height: 160px;
background-color:
white;
position: absolute;
top:
100px; left:
20px; borderradius:
50%;
box-shadow: 0 0
0 5px #ccc;
}
</style>
</head>
<body>
cone = document.querySelector(".cone");
cone.addEventListener("click", () =>
{ isFilled = !isFilled;
cone.classList.toggle("empty");
document.querySelector("h1").textContent = "Enjoy
"body"
).style.backgroundColor = "lightblue";
} else { cone.style.backgroundColor =
"white";
document.querySelector("h1").textContent
"body"
).style.backgroundColor = "#f2f2f2";
});
</script>
</body>
</html>
OUTPUT
5.a )
AIM:Create an array of objects having movie details. The object should include the
movie name, starring, language, and ratings. Render the details of movies on the page
using the array.
DESCRIPTION:
Array Methods: JavaScript provides a number of built-in methods for working with
arrays. Some of the most commonly used methods include:
push(): Adds one or more elements to the end of an array.
pop(): Removes the last element from an array and returns it.
shift(): Removes the first element from an array and returns it.
unshift(): Adds one or more elements to the beginning of an
array.
concat(): Joins two or more arrays together. slice():
PROGRAM:
<!DOCTYPE html>
<html>
<head>
<title>Movie Details</title>
</head>
<body>
<h1>Movie Details</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>Starring</th>
<th>Language</th>
<th>Ratings</th>
</tr>
</thead>
<tbody id="movie-details">
</tbody>
</table>
<script>
let movies = [
ratings: 9.3,
},
},
9.0,
},
},
];
document.createElement("tr");
let nameCell =
document.createElement("td");
nameCell.textContent = movie.name;
document.createElement("td");
starringCell.textContent = movie.starring;
= document.createElement("td");
languageCell.textContent = movie.language;
= document.createElement("td");
ratingsCell.textContent = movie.ratings;
row.appendChild(ratingsCell);
movieTable.appendChild(row);
});
</script>
</body>
</html>
OUTPUT
:
5.b )
AIM:Simulate a periodic stock price change and display on the console. Hints: (i) Create a
method which returns a random number - use Math.random, floor and other methods to
return a rounded value. (ii) Invoke the method for every three seconds and stop when
DESCRIPTION:
Introduction to Asynchronous Programming: Asynchronous programming is a programming
paradigm that allows multiple tasks to run concurrently. This means that a program can
perform multiple tasks simultaneously without blocking the execution of other tasks. In
JavaScript, asynchronous programming is essential for handling long-running operations,
such as network requests or file operations, without freezing the user interface.
Async and Await: Async/await is a newer syntax introduced in ES2017 that allows you
to write asynchronous code that looks synchronous. It is built on top of promises and
provides a simpler and more concise way to handle asynchronous operations. Async
functions always return a promise, and the await keyword can be used to wait for the
resolution of a promise.
Executing Network Requests using Fetch API: The Fetch API is a modern API for
making network requests in JavaScript. It provides a simple and concise way to make
HTTP requests and handle their responses. The Fetch API returns a promise that resolves
to a response object. The response object contains information about the response, such as
the status code and headers.
You can then use the methods provided by the response object to extract the data from the
PROGRAM:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
min + 1) + min);
let intervalId;
= getRandomPrice(50, 150);
console.log(`Stock price: $$
{price}`);
}, 3000);
}
function stopSimulation() {
clearInterval(intervalId);
console.log("Simulation stopped.");
</script>
</body>
</html>
OUTPUT
Stock price:
$112 Stock
price: $134
...
The simulation will continue to generate and display stock prices every three seconds until
you
stop it by calling the stopSimulation() function or closing the browser tab.
5.c )
AIM:
Validate the user by creating a login module. Hints: (i) Create a file login.js with a
User class. (ii) Create a validate method with username and password as arguments.
(iii) If the username and password are equal it will return "Login Successful"
DESCRIPTION:In JavaScript, you can create a module by defining an object or
expor
impor
t
function in a separate file and exporting it using the keyword. You can then
import the module into another file using the keyword.
Consuming modules means using the exported functions, objects, or variables from the
module in other parts of the program. To consume a module, you need to import it into
the file where you want to use it and then use the imported functions or objects as
PROGRAM:
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h1>Login Page</h1>
<form>
<label for="username">Username:</label>
<label for="password">Password:</label>
</form>
{ constructor(username,
password) { this.username =
username; this.password =
password;
}
validate() { if (this.username
Successful";
} else {
= document.getElementById("password").value;
user.validate();
alert(validationMsg);
</script>
</body>
</html>
OUTPUT
:
6.a )
AIM:
DESCRIPTION:
file for your project, which will contain the project's metadata andnpm install
dependencies.
dependencies
package.json
Deploy your application to a web server or hosting platform to make it available to the public.
PROGRAM:
To execute different functions successfully in the Node.js platform, you can follow these
general steps:
1. Create a new file with the .js extension, and give it a meaningful name related to the function(s)
it will contain.
2. Open the file in your preferred code editor, such as VS Code, Atom, or Sublime Text.
3. Begin by defining any required dependencies or modules at the top of the file using the
require() method. For example, if you need to use the built-in fs module to interact with the file
system,
you can require it like this:
const fs = require('fs');
4. Define your function(s) within the file. You can use the module.exports object to make your
function(s) available to other files that require them. For example:
function sayHello() { console.log('Hello, world!'); } module.exports = { sayHello: sayHello };
5. In a separate file where you want to use the function(s), require the file that contains them using
the require() method. For example:
const myFunctions = require('./my-functions.js');
6. Call the function(s) using the object you exported from the file. For example:
myFunctions.sayHello();
7. Save both files and run your Node.js application using the node command followed by the
filename. For example:
node app.js
This will execute your application and call your function(s) as expected.
Note that these are general steps, and the specific implementation may vary depending on the
nature of the functions you are working with.
6.b )AIM:
Write a program to show the workflow of JavaScript code executable by creating
web server in Node.js.
DESCRIPTION:
This code will start the server on port 3000 and log a message to the console to confirm that the
server is running.
6. Save your file and start the server by running the following command in your terminal:
node server.js
This will start your server, and it will be ready to receive incoming requests.
Note that this is a very basic example of how to create a web server in Node.js, and there are
many other modules and libraries you can use to create more advanced servers with features such
as routing, middleware, and database integration.
PROGRAM:
res.end('Hello, world!');
} else {
});
function executeCode() {
const code = `
function add(a, b)
{ return a + b;
result;
`;
result;
}
const port = 3000; server.listen(port, () =>
6.c )AIM:
Write a Node.js module to show the workflow of Modularization of Node application.
DESCRIPTION:
Node.js makes it easy to create modular programs by providing a built-in module object that can
be used to define and export modules. To define a module in Node.js, you simply create a new
JavaScript file and define one or more functions or objects that you want to export using the
module.exports object.
PROGRAM:
Sure! Here's an example Node.js module that demonstrates how to modularize a Node
application:
// math.js
function add (a, b ) { return a + b; }
function subtrac ( a, ) { return a - b; }
modul . exports = { add, subtract };
add() and subtract(), and export them as properties of
In this module, we define two functi ns, ject. These functions can be used in other parts of
an object using the module.exports our
application by importing this
module.
// app.js
const math = requir ( './math' ); consol . log (math. add ( 2 , 3 )); / 5
e
console .log (math subtract ( 5 , )); //
3
unction and call its add()
module using the require()
In this example, we import the math.js
and subtract() functions. output:
53
rization can help organize ou
ation. By defining common f
orting it as needed, we can keep our
ntainable
6.d )AIM:
Write a program to show the workflow of restarting a Node
application DESCRIPTION:
There are several ways to restart a Node.js application, depending on the circumstances.
If you are running your Node application using the node command in your terminal, you can ctrl
simply stop the current instance of the application b + c and then start a
new instance by running the node command again.
require('http');
const server = http.createServer((req, res) =>
});
at http://localhost:3000/');
});
});
});
});
});
In this program, we create a simple HTTP server that listens on port 3000 and returns a
"Hello, world!" message when a request is received. We also define two event listeners
for the SIGTERM and SIGINT signals, which are sent when the process is terminated
or interrupted, respectively.
To use pm2 to manage our Node.js process, we need to install it globally using
Once pm2 is installed, we can start our Node.js application using the following command:
This will start the application as a background process and give it the name "my-app".
We can then use the following command to view information about the process:
If we need to restart the application for any reason, we can use the following command:
Javascript code
Server running at http://localhost:3000/
This indicates that the HTTP server has started and is listening for incoming requests on port
3000.
If you want to test the HTTP server, you can open a web browser and navigate to
http://localhost:3000/, or you can use a tool like curl to make a request from the command line:
curl http://localhost:3000/
If you need to restart the Node.js application using pm2, you can use the following command:
This will gracefully shut down the current instance of the application and start a new instance in
its place. You should see output in the console indicating that the application has restarted:
code
[PM2] Restarting app... [PM2] App [my-app] restarted
Once the application has restarted, you can test it again to ensure that it is working correctly.
6.e )AIM:
Create a text file src.txt and add the following data to it. Mongo, Express, Angular, Node.
DESCRIPTION:
In Node.js, file operations refer to any operation that involves reading from or writing to files
on the file system. Some common file operations include:
Reading from a file: This involves opening a file, reading its contents, and then closing the
file. This can be useful for loading configuration files or reading data from a database.
Writing to a file: This involves opening a file, writing data to it, and then closing the file. This
can be useful for logging data or saving user input to a file.
Appending to a file: This involves opening a file in "append mode", which allows you to add
new data to the end of the file without overwriting any existing data.
Deleting a file: This involves deleting a file from the file system. This can be useful for
cleaning up temporary files or removing files that are no longer needed.
Node.js provides several built-in modules for performing file operations, including the fs
module, which provides a simple and consistent API for working with files. With the fs module,
you can perform operations like reading, writing, appending, and deleting files, as well as
creating and renaming directories.
It's important to note that file operations can be synchronous or asynchronous. Synchrono
file operations block the execution of the program until the operation is complete, while
asynchronous file operations allow the program to continue executing while the operation
progress. Asynchronous file operations are generally preferred in Node.js, as they can he
improve the performance and responsiveness of the program.
To create a text file calle src.txt and add the data "Mongo, Express, Angular, Node" to it,
can use the you
followin steps:
The output of the above process would be a text file src.tx containing the text "Mongo,
named Express, Angular, Node".
You can verify that the file has been created and contains the correct text by opening the
file in a text editor or using a command in the terminal or command prompt to view the
contents of the type
file. For example, in Windows Command Prompt, you can use the src.txt command
the contents of the file in the command prompt to view
7.a)
AIM:
Implement routing for the AdventureTrails application by embedding the necessary
code in the routes/route.js file.
DESCRIPTION:
Defining a route:
Handling routes:
When a request is made to a defined route, the corresponding handler function will be called.
The handler function takes two parameters: req (the request object) and s (the response object).
PROGRAM:
});
});
});
});
location:
req.body.location, difficulty:
req.body.difficulty,
length:
req.body.length,
});
});
});
// Update an existing trail
router.put('/trails/:id', (req, res) =>
{
Trail.findByIdAndUpdate(req.params.id, req.body, { new: true }, (err,
trail) => { if (err) { console.error(err);
res.status(500).send('Error updating trail');
} else if (!trail) {
res.status(404).send('Trail not found');
} else {
res.json(trail);
}
});
});
// Delete an existing trail
router.delete('/trails/:id', (req, res)
=> {
Trail.findByIdAndDelete(req.params.id, (err, trail)
=> { if (err) {
console.error(err);
res.status(500).send('Error deleting trail');
} else if (!trail) {
res.status(404).send('Trail not found');
} else {
res.json(trail);
}
});
});
module.exports = router;
Note that we are using the Trail model from the models/trail.js file to interact with the
ser middleware to pars file: database.
OUTPUT: [
{
"_id": "60e34e8aa522c0246c5cf6fa",
"name": "Hiking Trail",
"location": "Mountain Range",
"difficulty": "Intermediate",
"length": "5 miles",
" ": 0
},
"_id": "60e34f0a82b19017c2a35611",
"name": "Biking Trail",
"location": "Coastal
Region", "difficulty":
"Advanced", "length": "10
miles",
" ": 0
}
]
7.b )AIM:
In myNotes application: (i) we want to handle POST submissions. (ii) display
customized error messages. (iii) perform logging.
DESCRIPTION:
Middleware is a function that can be executed before the final request handler is called. It
can intercept the request, perform some operation on it, and pass it on to the next
middleware or to the final request handler.
When a middleware is called, it receives three arguments: req, res, and next. req represents
the request object, res represents the response object, and next is a function that is called to
pass control to the next middleware in the stack.
});
In the above code, we first use the built-in express.json() middleware to parse the JSON body of
POST requests. Then we define a middleware function to handle POST submissions. This
middleware function first extracts the note object from the request body and then validates it.
If the note is invalid, it sends a customized error message to the client. If the note is valid, it
logs it to the console and passes control to the next middleware.
We then define route handlers for displaying all notes and a single note by ID. In the handler
for displaying a single note, we first find the note by ID and then check if it exists. If the note is
found, we send it to the client. If the note is not found, we send a customized error message
OUTPUT:
A specific output for the myNotes application without knowing the complete code of the
application. However, the output of the code snippet I provided in the previous message would
be as follows:
When a POST request is made to /notes with a valid JSON body, the note object would be
logged to the console and the response status would be set to 200 with no response body.
When a POST request is made to /notes with an invalid JSON body, the response status would
be set to 400 and the response body would be the string "Title and body are required."
When a GET request is made to /notes, the response body would be an array of all the notes in
the notes array.
When a GET request is made to /notes/:id with a valid ID, the response body would be the note
object with the matching ID.
When a GET request is made to /notes/:id with an invalid ID, the response status would be set
to 404 and the response body would be the string "Note not found."
7.c )AIM:
Write a Mongoose schema to connect with MongoDB.
DESCRIPTION:
Connecting to MongoDB with Mongoose: Mongoose is an Object Data Modeling (ODM)
library for MongoDB and it provides a simple way to connect to a MongoDB database
using Mongoose.connect() method. To establish a connection, you need to pass the
database URL and
options (if any) as parameters to the Mongoose.connect() method.
Validation Types: Mongoose provides a set of built-in validators that can be used to validate data
before it is saved to the database. These validators include required, min, max, enum, match, and
more. To use a validator, you need to define it as a property of the schema field
Defaults: Mongoose also allows you to set default values for fields in a schema. You can define a
default value for a field by setting the default property of the field.
PROGRAM:
createdOn: {
type: Date,
default: Date.now
},
updatedOn: {
type: Date,
default: Date.now
}
});
newNote.save((err, note)
=> { if (err) {
console.error(err);
} else {
console.log('Note created successfully:', note);
}
});
});
});
// Update a note by ID
Note.updateOne({ _id: '603dc404bf62f4a4d91a92af' }, { title: 'Updated title' }, (err,
result) => { if (err) {
console.error(err);
} else {
console.log('Note updated successfully:', result);
}
});
// Delete a note by ID
Note.deleteOne({ _id: '603dc404bf62f4a4d91a92af' }, (err, result)
=> { if (err) {
console.error(err);
} else {
console.log('Note deleted successfully:', result);
}
});
This code connects to a MongoDB database using Mongoose, defines the Note schema, and
performs various operations on the Note model using Mongoose methods such as .save()
.find(), .findById(), .updateOne(), and .deleteOne(). The output of the code will depend on the
7.d )AIM:
Write a program to wrap the Schema into a Model object.
DESCRIPTION:
In the context of an Express application, models are typically used to represent data and
define
the interactions with a database. A model typically corresponds to a database table and
is
responsible for defining the schema and providing methods for interacting with the
data.
PROGRAM:
const mongoose = require('mongoose');
});
OUTPUT:
The output of the program will depend on the specific database operations being
performed. Here's an example of the output you might see when running a program
that retrieves all
users from the database using the find() method of the User }
model o users) => { e
if (err) { l
console.error(err);
se { ject: User.find({}, (err,
console.log(users
);
}
});
Assuming there are three users in the database, the output might look something like this:
This output shows an array of three user objects, each with an ID, name, age, and email.
8.a )AIM:
Write a program to perform various CRUD (Create-Read-Update-Delete) operations
using Mongoose library functions.
DESCRIPTION:
CRUD (Create, Read, Update, Delete) operations are common operations used in web
development. In Express.js, we can perform CRUD operations using HTTP methods
like GET, POST, PUT, and DELETE.
PROGRAM:
mongoose.connect('mongodb://localhost:27017/myapp', {
useNewUrlParser: true, useUnifiedTopology: true });
String,
});
mongoose.model('User',
userSchema);
// Create a new user const user = new User({ name: 'John',
{ if (err)
console.error(err);
console.log(users);
});
'60519d4b4c4b5e5b5ca5e5d5';
console.log(user);
});
// Update user
});
// Delete user
User.findByIdAndDelete(id, (err)
console.log('User deleted
successfully');
});
OUTPUT:
User created
successfully [
_id: 60519d3c5da7cb5b37c358a7,
name: 'John',
email:
',
v: 0
_id: 60519d3c5da7cb5b37c358a7,
v: 0
_id: 60519d3c5da7cb5b37c358a7,
'[email protected]',
v: 0
8.b )AIM:
In the myNotes application, include APIs based on the requirements provided. (i)
API should fetch the details of the notes based on a notesID which is provided in
the URL. Test URL - http://localhost:3000/notes/7555 (ii) API should update the
details
DESCRIPTION:
API development in Express.js involves creating API endpoints that can handle
incoming HTTP requests, process them, and send back appropriate responses. The API
endpoints can be used by clients to access and manipulate data or perform other
operations.
PROGRAM:
express();
});
// start the server app.listen(3000, () => {
}); OUTPUT:
As this code is meant to be run on a server, there won't be any visible output on the
console. However, we can test the API using a tool like Postman or a web browser.
Assuming that the API is running on localhost:3000, we can send a GET request to the
endpoint
/notes/7555 by visiting the URL http://localhost:3000/notes/7555 in a web browser or
using Postman.
If a note with ID 7555 exists in the database, its details will be returned as a JSON
response. For example:
"_id": "6159078f7b9ca2d3fcf3b2c8",
"createdAt": "2021-10-
03T10:34:23.950Z", "updatedAt":
}If a note with ID 7555 doesn't exist in the database, a 404 status code will be returned
8.c )AIM:
Write a program to explain session management using cookies.
DESCRIPTION:
Session management and cookies are important concepts in web development for maintaining
user state and improving user experience.
Sessions are used to maintain user state across multiple requests. When a user logs in to a
website, a session is created on the server, and a unique session ID is generated and stored in a
cookie on the user's browser. This session ID is used to identify the user's session on
subsequent requests, allowing the server to retrieve session data and maintain user state.
Cookies are small text files that are stored on the user's browser. They are used to store
userspecific data such as login credentials, user preferences, and session IDs. Cookies can be set
by the server or by client-side scripts, and they are sent to the server with each request.
Cookies can also be used to store information about the user's activity on the website, such as
the pages they have visited, the items they have added to their cart, etc.
PROGRAM:
cookieParser = require('cookie-parser');
parsing app.use(cookieParser());
}));
// Set up a simple login page
res.send(`
<h1>Login</h1>
<label for="username">Username:</label>
<label for="password">Password:</label>
<button type="submit">Submit</button>
</form>
`);
});
user's ID req.session.userId = 1;
res.send('<p>Login successful!</p>');
} else { res.send('<p>Invalid username
or password.</p>');
});
req.session.userId;
${userId}!</p>`);
this page.</p>');
});
{ req.session.destroy(); res.send('<p>You
});
// Start the server app.listen(port, () =>
{port}`);
});
OUTPUT:
8.d )AIM:
Write a program to explain session management using sessions.
DESCRIPTION:
In web development, a session is a way to store and persist user data across multiple
requests from the same user. Sessions allow a web application to keep track of user state
and information, such as login credentials, shopping cart contents, and user preferences.
When a user logs in or interacts with a web application, the server creates a unique
session for that user, which is associated with a session ID. The session ID is then
stored as a cookie in the user's browser, and the server can use it to retrieve the
corresponding session data for that user on subsequent requests.
PROGRAM:
session');
app.use(session({ sec
ret: 'mysecretkey',
resave: false,
saveUninitialized:
true
}));
app.get('/', (req, res) => {
const sessionData =
req.session; if
(sessionData.views) {
sessionData.views++;
res.setHeader('Content-Type',
'text/html');
res.write('<p>Number of
views: '
+ sessionData.views +
'</p>'); res.write('<p>Session
'</p>'); res.write('<p><a
href="/logout">Logout</a></p
>'
); res.end(); } else
{ sessionData.views = 1;
res.send('Welcome to the
count.');
});
app.get('/logout', (req, res) =>
{ req.session.destroy((err) => {
if (err) {
console.log(err);
} else {
res.redirect('/'
);
});
});
app.listen(3000, () =>
3000');
});
OUTPUT:
Welcome to the session demo! Refresh the page to increase the view
count. When we refresh the page, we see the view count increase:
Number of views: 2
Logout
8.e )AIM:
Implement security features in myNotes application
DESCRIPTION:
Security is a critical concern for any web application, and it is essential to ensure that the
application is protected against common web vulnerabilities such as cross-site scripting (XSS),
cross-site request forgery (CSRF), and other attacks. In addition, it is important to ensure that
sensitive user data is encrypted in transit and at rest, and that the application is protected
against attacks like SQL injection.
One of the ways to enhance the security of an Express.js application is by using middleware.
Middleware functions are functions that have access to the request and response objects, and
can modify them or perform other actions based on the needs of the application.
PROGRAM:
1. Authentication: Implement a user authentication system to ensure that only authorized users can
access and modify their notes. This can be done using third-party authentication services like
OAuth or by creating a custom authentication system.
Here's an example of a custom authentication system using Passport.js middleware:
passport.use(new
LocalStrategy( function(username,
password, done) {
} if (!user.verifyPassword(password)) { return
});
}
));
app.post('/login', passport.authenticate('local', { failureRedirect: '/login' }), function(req, res)
{ res.redirect('/notes');
});
2. Authorization: Once the user is authenticated, implement an authorization system to ensure that
users can only access and modify their own notes. This can be done using role-based access
control or by associating notes with specific users in the database.
Here's an example of associating notes with specific users in MongoDB:
});
module.exports = Note;
3. Encryption: Ensure that user data is encrypted both in transit and at rest. This can be
done using SSL/TLS encryption for in-transit data and data encryption at the database
Here's an example of enabling SSL/TLS encryption in an Express.js application:
certificate};
4. Helmet middleware: Finally, use the Helmet middleware to implement additional security
measures like setting various HTTP headers to protect against attacks such as XSS and CSRF.
app.use(helmet());
app.listen(3000);
9.a )
AIM:
On the page, display the price of the mobile-based in three
different colors. Instead ofusing the number in our code, represent
them by string values like GoldPlatinum,PinkGold,
SilverTitanium.
DESCRIPTION:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
</div>
</body>
</html>
OUTPUT:
GoldPlatinum: ${{mobilePrice}} (displayed in gold color)PinkGold: $
{{mobilePrice}} (displayed in deep pink color)SilverTitanium: ${{mobilePrice}}
(displayed in silver color)
9.b )
AIM:
Define an arrow function inside the event handler to filter the
product array with theselected product object using the
productId received by the function. Pass the selectedproduct
object to the next screen.
DESCRIPTION:
In TypeScript, functions are first-class citizens, which means that they can be treated like
any other value or variable. This allows for greater flexibility and expressiveness when
defining functions in TypeScript.
To define a function in TypeScript, you use the function keyword, followed by the
name and a set of parentheses that contain any parameters function
that the function takes. The
function body is then enclosed in curly braces, and the return type is specified after the
closing parenthesis of the parameter list, using a colon followed by the return type
PROGRAM:
interface Product {
productId:
number; name:
string; price:
number;
}
const products: Product[] = [
},
];
?? null);
// Navigate to the product details screen with the selected product object
return (
<div>
<h1>Product List</h1>
<ul>
{products.map((product) => (
<li key={product.productId}>
</button>
</li>
))}
</ul>
{selectedProduct && (
<div>
<h2>Selected Product</h2>
<p>{selectedProduct.name} (${selectedProduct.price})</p>
</button>
</div>
)}
</div>
);
OUTPUT:
Product List
- Product 1 ($10)
- Product 2 ($20) - Product 3 ($30)
Selected Product
Product 2 ($20)
[View Details]
9.c )
AIM:
interface Mobile
{ brand: string;
model:
string; price:
number;
];
function getMobileByVendor(vendor: string): Mobile[] {
9.d )AIM:
Consider that developer needs to declare a manufacturer's
array holding 4 objects with id and price as a parameter and
needs to implement an arrow function - myfunction to
populate the id parameter of manufacturers array whose price
is greater than
DESCRIPTION:
Arrow functions are a shorthand syntax for writing functions in TypeScript (and JavaScript).
Arrow functions provide a concise way to define functions using the => syntax. Arrow functions
have a number of advantages over traditional function syntax. They a re more concise, making
code easier to read and write. They also have a lexical
this binding, which means that this
the
value inside the function is the same as this }
the PROGRAM:
interface Manufacturer {
{ id: 1, price: 10 },
price: number;
value outside the function.
{ id: 2, price: 15 },
{ id: 3, price: 20 },
{ id: 4, price: 25 }
];
console.log(filteredIds);
Output: [3, 4]
9.e)
AI
M:
Declare a function - getMobileByManufacturer with two parameters namely
manufacturer and id, where manufacturer value should passed as Samsung and
id parameter should be optional while invoking the function, if id is passed as
101 then this function
DESCRIPTION:
Optional and default parameters are features in TypeScript (and JavaScript) that allow
developers to define function parameters with optional or default values.Optional
parameters are indicated by adding a question mark (?) after the parameter name in the
function declaration. Optional parameters can be omitted when calling the function, and
undefine
will be assigned the value if
not provide Default.Parameters are indicated by assigning a default value to the
parameter in the function declaration. Default parameters will be assigned the default
value if no value is provided when calling the function
PROGRAM:
number;
manufacturer: string;
model: string;
];
if (id) {
} else { return
filteredMobiles;
}
console.log(getMobileByManufacturer('Samsung')); // Output: [{ id: 101,
manufacturer: 'Samsung', model: 'Galaxy S21' }]
AIM:
PROGRAM:
Output:
10.b )
AIM:
Declare an interface named - Product with two properties like
productId and productName with a number and string datatype
and need to implement logic to populate the Product details.
DESCRIPTION:
To create an interface in TypeScript, you can use the interface keyword, followed by the name of
the interface and its properties and methods.
PROGRAM:
interface Product
{ productId: number;
productName: string;
}; addProduct(newProduct);
10.c )
AIM:
Duck typing is a concept in TypeScript (and other programming languages) that refers to
checking for the presence of certain properties or methods in an object, rather than its actual
type or class. The term "duck typing" comes from the saying, "If it looks like a duck, swims like
a duck, and quacks like a duck, then it probably is a duck."
object, you can check if it has the necessary properties or methods to fulfill the requirements of
a
PROGRAM:
interface Product {
productId: number;
productName: string;
}
addProduct(newProduct); Output:
Added product Laptop with ID 123
10.d )
AIM:Declare an interface with function type and access its
value.
DESCRIPTION:
, whereparam1 ,
param2 parameter types, and
PROGRAM:
); Output: 5
11.a ) AIM:
Declare a productList interface which extends properties from
two other declared interfaces like Category,Product as well as
implementation to create a
variable of this interface type.
DESCRIPTION:
In TypeScript, interfaces can be extended by other interfaces using t extends keyword. This
create new interfaces that inherit the properties and methods of an e
while also adding new properties and methods of their own.
To extend an interface, simply define a new interface and use the extends keyword to specify the
parent interface that it inherits from
PROGRAM:
interface Category
{ id: number;
name: string;
}
interface Product
{ id: number;
name: string;
price: number;
}
interface ProductList extends Category, Product {
quantity: number;
}
console.log(myProductList); Output:
{ id: 1, name: 'T-Shirt', price: 19.99, quantity: 10 }
11.
b)
AI
M:
Consider the Mobile Cart application, Create objects of the Product class and place
them into the productlist array.
DESCRIPTION:
In TypeScript, classes are used to define object blueprints with properties and methods.
They provide a way to create objects that have the same structure and behavior, making it
easier to manage and manipulate complex data.
To define a class in TypeScript, you use the class keyword followed by the name of the class.
PROGRAM:
class Product {
name: string; price:
number;
constructor(name:
string, price:
number)
{ this.name
= name;
this.price = price;
}
}
console.log(productList);
Output:
[Product { name: 'iPhone X', price: 999 }, Product { name: 'Samsung Galaxy S21',
price: 799 }, Product { name: 'Google Pixel 5', price: 699 }]
11.c
)
AI
M:
Declare a class named - Product with the below-mentioned declarations: (i)
productId as number property (ii) Constructor to initialize this value (iii)
getProductId method to return the message "Product id is <<id value>>".
DESCRIPTION:
In TypeScript, the constructor method is a special method that is used to create and initialize
objects created from a class. It is called automatically when a new object is created using the
new keyword and can be used to set initial values for object
PROGRAM:
class Product {
productId: number;
constructor(productId: number) {
this.productId = productId;
}
getProductId() {
return `Product id is ${this.productId}`;
}
}
Output:
Product id is 123
11.d )AIM:
Create a Product class with 4 properties namely productId, productName,
productPrice, productCategory with private, public, static, and protected access
modifiers and accessing them through Gadget class and its methods.
DESCRIPTION:
In TypeScript, access modifiers are used to control the accessibility of class members
(properties and methods). There are three access modifiers available: public, private, and
protected.
public members are accessible from anywhere, both within and outside of the
class.private members are only accessible within the class that defines them.protected
PROGRAM:
class Gadget {
constructor(private product: Product) {}
getProductCategory() {
return Product.productCategory;
}
getProductDetails() {
return this.product.getProductDetails();
}
12.a )AIM:
Create a Product class with 4 properties namely productId and
methods to setProductId() and getProductId().
DESCRIPTION:
In TypeScript, properties and methods are used to define the state and behavior of a class.
Properties represent the state of an object and are used to store data. They can be declared with
different access modifiers (public, private, protected) to control their visibility and accessibility.
Methods represent the behavior of an object and are used to perform operations on the object's
data. They can be declared with different access modifiers to control their visibility and
accessibility, and can also accept parameters and return values.
Properties and methods are accessed using the dot notation, where the property or method name
PROGRAM:
class Product {
private productId: number;
constructor(productId: number)
{ this.setProductId(productId);
}
setProductId(productId: number) {
this.productId = productId;
}
getProductId() {
return
this.productId;
}
product1.setProductId(456);
console.log(product1.getProductId()); // Output: 456
12.b )AIM:
Create a namespace called ProductUtility and place the Product
class definition in it. Import the Product class inside productlist
file and use it.
DESCRIPTION:
In TypeScript, namespaces are used to group related code into a single container to avoid
naming
For example, suppose we have a set of utility functions for working with arrays. We can
PROGRAM:
constructor(productId: number)
{ this.setProductId(productId);
}
setProductId(productId: number) {
this.productId = productId;
}
getProductId() {
return
this.productId;
}
}
product1.setProductId(456);
console.log(product1.getProductId()); Output:
456
12.c )AIM:
Consider the Mobile Cart application which is designed as part
of the functions in a module to calculate the total price of the
product using the quantity and price values and assign it to a
totalPrice variable.
DESCRIPTION:
In TypeScript, modules are used to organize code into reusable and maintainable units. A module
can contain variables, functions, classes, interfaces, and other declarations, and can be used in
other modules or applications.
To create a module in TypeScript, you can use the export keyword to export variables,
functions, or classes from a file. For example, to export a function add from a file math.ts
PROGRAM:
12.d )AIM:
Create a generic array and function to sort numbers as well as
string values.
DESCRIPTION:
Generics in TypeScript is a powerful feature that allows you to create reusable components
that can work with a variety of data types. It allows you to write more flexible and type-safe
code, while still providing the flexibility to work with different data types.
Generic Functions: Generic functions are functions that are defined with one or more type
parameters. These type parameters can be used in the function's signature, allowing the
function
Generic Constraints: Generic constraints are used to restrict the types that a type parameter can
be replaced with. This is useful when you want to enforce certain properties on the data type
being used
PROGRAM:
productUtils.ts
mobileCart.ts
import { calculateTotalPrice } from './productUtils';
class Product {
constructor(private productId: number, private productName: string, private
productPrice: number) {}
getProductDetails() {
return `Product ID: ${this.productId}\nProduct Name: ${this.productName}\nProduct
Price:
$${this.productPrice}\n`;
}
getTotalPrice(quantity: number) {
return calculateTotalPrice(quantity, this.productPrice);
}
{totalPrice2}\n`); OUTPUT:
Product ID: 1
Product
Name: iPhone
Product Price:
$999
Quantity: 2
Total Price: $1998
Product ID: 2
Product Name:
Samsung Galaxy
Product Price: $799
Quantity: 3
Total Price: $2397
And some tulips:
tulips = list(data_dir.glob('tulips/*'))
PIL.Image.open(str(tulips[0]))
PIL.Image.open(str(tulips[1]))
It's good practice to use a validation split when developing your model. Use 80% of the images
for training and 20% for validation.
train_ds = tf.keras.utils.image_dataset_from_directory(
data_dir,
validation_split=0.2,
subset="training",
seed=123,
image_size=(img_height, img_width),
batch_size=batch_size)
You can find the class names in the class_names attribute on these datasets. These correspond
to the directory names in alphabetical order.
class_names = train_ds.class_names
print(class_names)
Here are the first nine images from the training dataset:
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 10))
for images, labels in train_ds.take(1):
for i in range(9):
ax = plt.subplot(3, 3, i + 1)
plt.imshow(images[i].numpy().astype("uint8"))
plt.title(class_names[labels[i]])
plt.axis("off")
You will pass these datasets to the Keras Model.fit method for training later in this tutorial. If
you like, you can also manually iterate over the dataset and retrieve batches of images:
for image_batch, labels_batch in train_ds:
print(image_batch.shape)
print(labels_batch.shape)
break
(32,)
The image_batch is a tensor of the shape (32, 180, 180, 3). This is a batch of 32 images of
shape 180x180x3 (the last dimension refers to color channels RGB). The label_batch is a
tensor of the shape (32,), these are corresponding labels to the 32 images.
You can call .numpy() on the image_batch and labels_batch tensors to convert them to
a numpy.ndarray.
Make sure to use buffered prefetching, so you can yield data from disk without having I/O
become blocking. These are two important methods you should use when loading data:
Dataset.cache keeps the images in memory after they're loaded off disk during the first epoch.
This will ensure the dataset does not become a bottleneck while training your model. If your
dataset is too large to fit into memory, you can also use this method to create a performant on-
disk cache.
Dataset.prefetch overlaps data preprocessing and model execution while training.
Interested readers can learn more about both methods, as well as how to cache data to disk in
the Prefetching section of the Better performance with the tf.data API guide.
AUTOTUNE = tf.data.AUTOTUNE
train_ds =
train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)
val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)
The RGB channel values are in the [0, 255] range. This is not ideal for a neural network; in
general you should seek to make your input values small.
Here, you will standardize values to be in the [0, 1] range by
using tf.keras.layers.Rescaling:
normalization_layer = layers.Rescaling(1./255)
There are two ways to use this layer. You can apply it to the dataset by calling Dataset.map:
normalized_ds = train_ds.map(lambda x, y: (normalization_layer(x), y))
image_batch, labels_batch = next(iter(normalized_ds))
first_image = image_batch[0]
# Notice the pixel values are now in `[0,1]`.
print(np.min(first_image), np.max(first_image))
WARNING:tensorflow:From
/tmpfs/src/tf_docs_env/lib/python3.9/site-packages/tensorflow/python/autograph/pyct/
static_analysis/liveness.py:83: Analyzer.lamba_check (from
tensorflow.python.autograph.pyct.static_analysis.liveness) is deprecated and will be removed
after 2023-09-23.
Or, you can include the layer inside your model definition, which can simplify deployment. Use
the second approach here.
Note: You previously resized images using the image_size argument
of tf.keras.utils.image_dataset_from_directory. If you want to include the resizing logic in
your model as well, you can use the tf.keras.layers.Resizing layer.
model = Sequential([
layers.Rescaling(1./255, input_shape=(img_height, img_width, 3)),
layers.Conv2D(16, 3, padding='same', activation='relu'),
layers.MaxPooling2D(),
layers.Conv2D(32, 3, padding='same', activation='relu'),
layers.MaxPooling2D(),
layers.Conv2D(64, 3, padding='same', activation='relu'),
layers.MaxPooling2D(),
layers.Flatten(),
layers.Dense(128, activation='relu'),
layers.Dense(num_classes)
])
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
Experiment 8:
import requests
import cv2
import json
print("Age:", face["faceAttributes"]["age"])
print("Emotion:", face["faceAttributes"]["emotion"])
else: