Trending December 2023 # Jsp Elements – Declaration, Syntax & Expression # Suggested January 2024 # Top 19 Popular

You are reading the article Jsp Elements – Declaration, Syntax & Expression updated in December 2023 on the website Cattuongwedding.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 Jsp Elements – Declaration, Syntax & Expression

JSP Declaration

A declaration tag is a piece of Java code for declaring variables, methods and classes. If we declare a variable or method inside declaration tag it means that the declaration is made inside the servlet class but outside the service method.

We can declare a static member, an instance variable (can declare a number or string) and methods inside the declaration tag.

Syntax of declaration tag:

Here Dec var is the method or a variable inside the declaration tag.

Example:

In this example, we are going to use the declaration tags

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

Explanation the code:

Code Line 10: Here we are using declaration tag for initializing a variable count to 10.

When you execute the above code you get the following output:

Output:

The variable which is declared in the declaration tag is printed as output.

JSP Scriptlet

Scriptlet tag allows to write Java code into JSP file.

JSP container moves statements in _jspservice() method while generating servlet from jsp.

For each request of the client, service method of the JSP gets invoked hence the code inside the Scriptlet executes for every request.

A Scriptlet contains java code that is executed every time JSP is invoked.

Syntax of Scriptlet tag:

Example:

In this example, we are taking Scriptlet tags which enclose java code.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" <% int num1=10; int num2=40; int num3 = num1+num2; out.println("Scriplet Number is " +num3);

Explanation of the code:

Code Line 10-14: In the Scriptlet tags where we are taking two variables num1 and num2 . Third variable num3 is taken which adds up as num1 and chúng tôi output is num3.

When you execute the code, you get the following output:

Output:

The output for the Scriptlet Number is 50 which is addition of num1 and num2.

JSP Expression

Expression tag evaluates the expression placed in it.

It accesses the data stored in stored application.

It allows create expressions like arithmetic and logical.

It produces scriptless JSP page.

Syntax:

Here the expression is the arithmetic or logical expression.

Example:

In this example, we are using expression tag

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

Explanation of the code:

Code Line 12: Here we are using expression tags where we are using an expression by multiplying two numbers i.e. num1 and num 2 and then adding the third number i.e. num3.

When you execute the above code, you get the following output:

Output:

The expression number is 120 where we are multiplying two numbers num1 and num2 and adding that number with the third number.

JSP Comments

Comments are the one when JSP container wants to ignore certain texts and statements.

Syntax:

Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

Explanation of the code:

When you execute the above code you get the following output:

Output:

We get the output that is printed in println method. Comments are ignored by container

Creating a simple JSP Page

A JSP page has an HTML body incorporated with Java code into it

Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

Explanation of the code:

Code Line 1: Here we are using directives like language, contentType and pageEncoding. Language is Java and content type is text/html with standard charset ISO 8859. Page encoding is standard charset.

Code Line 14: Here we are declaring variables num12 and num32 initializing with 12.

Code Line 15: Here we are using an expression where we are multiplying two numbers num12 and num32.

Code Line 16: Here we are fetching today’s date using date object.

When you execute the above code, you get the following output

Output:

We are printing overhere,

This is guru JSP example.

The number is num12*num32 (12*12).

Today’s date is the current date

How to run simple JSP Page

JSP can be run on web servers or application servers.

Here we will be using a webserver, and we can deploy it on the server enclosing it in a war application.

We can create JSP in an application (war).

This is an application which has following directory structure, and the application has to be build.

This application has to be built, and the following message will appear after the build is successful:

After the application is built then, the application has to be run on the server.

From the diagram, following points are explained:

There are two options either to choose a server or manually add the server to this application. In this case, we have already added JBoss server to the application hence, we select the existing server.

Once we select the server the server option is shown in point 2 which server we want to select. There can be multiple servers configured on this application. We can select one server from all those options

In the below screenshots, you can notice that our JSP program gets executed, and the test application is deployed in JBoss server marked in the red box.

Directory Structure of JSP

In directory structure, there is a root folder which has folder WEB-INF, which has all configuration files and library files.

JSP files are outside WEB-INF folder

Directory structure of JSP

Example:

In this example there is test application which has folder structure has following:

Summary:

In this article, we have learnt about syntactic elements like expression tags, Scriptlet tags which simplify code in JSP.

We have created a simple JSP page and made it run on the server.

You're reading Jsp Elements – Declaration, Syntax & Expression

Mariadb Tutorial: Learn Syntax, Commands With Examples

What is MariaDB?

MariaDB is a fork of the MySQL database management system. It is created by its original developers. This DBMS tool offers data processing capabilities for both small and enterprise tasks.

MariaDB is an improved version of MySQL. It comes with numerous inbuilt powerful features and many usabilities, security and performance improvements that you cannot find in MySQL.

Here are the features of MariaDB:

It operates under GPL, BSD or LGPL licenses.

MariaDB supports a popular and standard querying language.

It comes with many storage engines, including the high-performance ones that can be integrated with other relational database management systems.

It provides the Galera cluster technology.

MariaDB supports PHP, a popular language for web development.

MariaDB can run on different operating systems, and it supports numerous programming languages.

MariaDB comes with additional commands that are not available in MySQL. MySQL has features which have a negative impact on the performance of the DBMS. Such features have been replaced in MariaDB.

In this MariaDB tutorial, you will learn:

MariaDB vs. MySQL

Below are some key differences between MariaDB vs MySQL

Parameter MariaDB MySQL

More Options for Storage Engines MariaDB has 12 new storage engines that you won’t find in MySQL. It has fewer options for storage compared to MariaDB.

Speed Improvements MariaDB shows an improved speed when compared to MySQL. It comes with numerous features for optimizing speed. Such features include derived views/tables, subquery, execution control, disk access, and optimizer control. MySQL exhibits a slower speed when compared to MariaDB. It relies on only a few features for speed optimization, for example, hash indexes.

Faster cache/indexes With the Memory storage engine of MariaDB, an INSERT statement can be completed 24% than in the standard MySQL. The memory storage engine of MySQL is slower compared to that MariaDB.

Larger and Faster Connection Pool The thread pool provided by MySQL cannot support up to 200,000 connections per time.

Improved Replication In MariaDB, replication can be done safer and faster. Updates can also be done 2x faster compared to the traditional MySQL.

New Features/Extensions MariaDB comes with new features and extensions including the JSON, WITH and KILL statements. The new MariaDB features are not provided in MySQL.

Missing Features MariaDB lacks some of the features provided by the MySQL enterprise edition. To address this, it offers alternative open-source plugins. Hence, MariaDB users are able to enjoy the same functionalities as MySQL Enterprise Edition users. The Enterprise Edition of MySQL uses a proprietary code. Only users of MySQL Enterprise Edition have access to this.

How to install MariaDB Install as a Standalone Application

In order to use MariaDB, you have to install it on your computer.

The installation can be done by following the steps given below:

Once the download is complete, Open File

In the next window, you will be required to change the password for the root user.

Enter the password and confirm it by retyping the same password. If you want to permit access from remote machines, activate the necessary checkbox.

A progress bar showing the progress of the installation will be shown:

You now have MariaDB installed on your computer.

Working with Command Prompt

Now that you have MariaDB installed on your computer, it is time for you to launch it and begin to use it. This can be done via the MariaDB command prompt.

Follow the steps given below:

Step 2) Choose a MariaDB Command Prompt.

Step 3) The MariaDB command prompt will be started. It is now time to login. You should login as the root user and the password that you set during the installation of MariaDB. Type the following command on the command prompt:

MySQL -u root -p

Step 4) Enter the password and hit the return key. You should be logged in, as shown below:

You are now logged into MariaDB.

Data Types

MariaDB supports the following data types:

String data types

Numeric data types

Date/time data types

Large object data types

String Data Types

These include the following:

String Data Type Description

char(size) The size denotes the number of characters to be stored. It stores a maximum of 255 characters. Fixed-length strings.

varchar(size) The size denotes the number of characters to be stored. It stores a maximum of 255 characters. Variable-length strings.

text(size) The size denotes the number of characters to be stored. It stores a maximum of 255 characters. Fixed-length strings.

binary(size) The size denotes the number of characters to be stored. It stores a maximum of 255 characters. Fixed-size strings.

Numeric Data Types

They include the following:

Numeric Data Types Description

bit A very small integer value equivalent to tinyint(1). Signed values range between -128 and 127. Unsigned values range between 0 and 255.

int(m) A standard integer value. Signed values range between -2147483648 and 2147483647. Unsigned values range between 0 and 4294967295.

float(m, d) A floating point number with single precision.

double(m,d) A floating point number with double precision.

float(p) A floating point number.

Date/Time Data Types

These include the following:

Date/Time Data Type Description

Date Displayed in the form ‘yyyy-mm-dd.’ Values range between ‘1000-01-01’ and ‘9999-12-31’.

Datetime Displayed in the form ‘yyyy-mm-dd hh:mm:ss’. Values range between ‘1000-01-01 00:00:00’ and ‘9999-12-31 23:59:59’.

timestamp(m) Displayed in the form ‘yyyy-mm-dd hh:mm:ss’. Values range between ‘1970-01-01 00:00:01’ utc and ‘2038-01-19 03:14:07’ utc.

Time Displayed in the form ‘hh:mm:ss’. Values range between ‘-838:59:59’ and ‘838:59:59’.

Large Object Datatypes (LOB)

They include the following:

Large object Datatype Description

tinyblob Its maximum size is 255 bytes.

blob(size) Takes 65,535 bytes as the maximum size.

mediumblob Its maximum size is 16,777,215 bytes.

longtext It takes 4GB as the maximum size.

Create a Database and Tables

To create a new database in MariaDB, you should have special privileges which are only granted to the root user and admins.

To create a new database, you should use the CREATE DATABASE command which takes the following syntax:

CREATE DATABASE DatabaseName;

In this case, you need to create a database and give it the name Demo.

Start the MariaDB command prompt and login as the root user by typing the following command:

mysql -u root -p

Type the root password and hit the return key. You will be logged in.

Now, run the following command:

CREATE DATABASE Demo;

You have then created a database named Demo. It will be good for you to confirm whether the database was created successfully or not. You only have to show the list of the available databases by running the following command:

SHOW DATABASES;

The above output shows that the Demo database is part of the list, hence the database was created successfully.

MariaDB Select Database

For you to be able to use or work on a particular database, you have to select it from the list of the available databases. After selecting a database, you can perform tasks such as creating tables within the database.

To select a database, you should use the USE command. It takes the syntax given below:

USE database_name;

You need to use the Demo database. You can select it by running the following command:

USE Demo;

The above image shows that the MariaDB command prompt has changed from none to the name of the database that has been selected.

You can now go ahead and create tables within the Demo database.

MariaDB – Create Table

For you to be able to create a table, you must have selected a database. The table can be created using the CREATE TABLE statement. Here is the syntax for the command:

CREATE TABLE tableName (columnName columnType);

You can set one of the columns to be the primary key. This column should not allow null values.

We will create two tables within the Demo database, Book, and Price tables. Each table will have two columns.

Let’s begin by creating the Book table with two columns, id and name. Run the following command:

CREATE TABLE Book( id INT NOT NULL AUTO_INCREMENT, name VARCHAR(100) NOT NULL, PRIMARY KEY (id));

The PRIMARY KEY constraint has been used to set the id column as the primary key for the table. The AUTO_INCREMENT property will increment the values of the id column by 1 automatically for each new record inserted into the table. All the columns will not allow null values.

Now, create the second table, the Price table:

CREATE TABLE Price( id INT NOT NULL AUTO_INCREMENT, price float NOT NULL, PRIMARY KEY (id));

The id column has been set as the primary key for the table.

Showing Tables

Now that you have created the two tables, it will be good for you to conform whether the tables were created successfully or not. You can show the list of tables contained in a database by running the following command:

SHOW TABLES;

The above screenshot shows that the two tables were created successfully within the Demo database.

Showing Table Structure

To see the structure of any particular table, you can use the DESCRIBE command, commonly abbreviated as DESC. It takes the following syntax:

DESC TableName;

For example, to see the structure of the table named Book, you can run the following command;

DESC Book;

The table has two columns. To see the structure of the Price table, you can run the following command:

DESC Price;

CRUD and Clauses INSERT

To insert data into a MariaDB table, you should use the INSERT INTO statement. This command takes the syntax given below:

INSERT INTO tableName (column_1, column_2, ... ) VALUES (value1, value2, ... ), (value1, value2, ... ), ...;

The above syntax shows that you have to specify the table columns into which you want to insert data as well as the data that you need to insert.

Let us insert a record into the Book table:

INSERT INTO book (id, name) VALUES(1, 'MariaDB Book');

You have inserted a single record into the table. Insert a record into the Price table:

INSERT INTO price (id, price) VALUES(1, 200);

The record has been created.

SELECT

The SELECT statement helps us to view or see the contents of a database table. To see the contents of the Book table, for example, you need to run the following command:

SELECT * from book;

Now, view the contents of the Price table:

SELECT * from price;

Inserting Multiple Records

It is possible for us to insert multiple records into a MariaDB table at a go. To demonstrate this, run the following example:

INSERT INTO book (id, name) VALUES (2,'MariaDB Book2'), (3,'MariaDB Book3'), (4,'MariaDB Book4'), (5,'MariaDB Book5');

You can query the table to check whether the records were inserted successfully:

SELECT * FROM book;

The records were inserted successfully. Insert multiple records into the Price table by running this example:

INSERT INTO price (id, price) VALUES (2, 250), (3, 220), (4, 190), (5, 300);

Let’s confirm whether the records were created successfully:

SELECT * FROM price;

UPDATE

The UPDATE command helps us to change or modify the records that have already been inserted into a table. You can combine it with the WHERE clause to specify the record that is to be updated. Here is the syntax:

UPDATE tableName SET field=newValue, field2=newValue2,... [WHERE ...]

The UPDATE command can also be combined with clauses such as SET, WHERE, LIMIT, and ORDER BY. You will see this shortly:

Consider the table named Price with the following records:

Let’s change the price of the book with an id of 1 from 200 to 250:

UPDATE price SET price = 250 WHERE id = 1;

The command ran successfully. You can now query the table to see whether the change took place:

The above screenshot shows that the change has been implemented. Consider the table Book with the following records:

Let us change the name of the book named Book to MariaDB Book1. Notice that the book has an id of 1. Here is the command for this:

UPDATE book SET name = “MariaDB Book1” WHERE id = 1;

Check whether the change has been implemented:

The above screenshot shows that the change has been implemented successfully.

In the above examples, we have only changed one column at a time. However, it is possible for us to change multiple columns at a go. Let us demonstrate this using an example.

Let us use the Price table with the following data:

Let us change both the id and the price of the book with an id of 5. We will change its id to 6 and price to 6. Run the following command:

UPDATE price SET id = 6, price = 280 WHERE id = 5;

Now, query the table to check whether the change was made successfully:

The change was made successfully.

Delete

We use the DELETE command when we need to delete either one or many records from a table. Here is the syntax for the command:

DELETE FROM tableName [WHERE condition(s)] [LIMIT numberRows];

Consider the Price table with the following records:

We need to delete the last record from the table. It has an id of 6 and a price of 280. Let us delete the record:

DELETE FROM price WHERE id = 6;

The command ran successfully. Let us query the table to confirm whether the deletion was successful:

The output shows that the record was deleted successfully.

Where

The WHERE clause helps us to specify the exact location where we need to make a change. It is used together with statements such as INSERT, SELECT, UPDATE, and DELETE. Consider the Price table with the following data:

Suppose we need to see the records in which the price is less than 250. We can run the following command:

SELECT * FROM price WHERE price < 250;

All the records in which the price is below 250 have been returned.

The WHERE clause can be combined with the AND statement. Suppose we need to see all records in the Price table where the price is below 250 and id is above 3. We can run the following command:

SELECT * FROM price AND price < 250;

Only one record has been returned. The reason is that it has to meet all the conditions that have been specified, that is, id above 3 and price below 250. If any of these conditions is violated, then the record will not be returned.

The clause can also be combined with the OR command. Let us replace the AND in our previous command with OR and see the kind of output that we receive:

SELECT * FROM price OR price < 250;

We now get 2 records rather than 1. This is because, for a record of qualifying, it only has to meet one of the specified conditions.

Like

This clause is used to specify the data pattern when accessing table data in which an exact match is necessary. It can be combined with the INSERT, UPDATE, SELECT and DELETE statements.

You should pass the pattern of data you are looking for to the clause, and it will return either true or false. Here are the wildcard characters that can be used together with the clause:

%: for matching either 0 or more characters.

_: for matching a single character.

Here is the syntax for the LIKE clause:

SELECT field_1, field_2,... FROM tableName1, tableName2,... WHERE fieldName LIKE condition;

Let us demonstrate how to use the clause with the % wildcard character. Let us use the Book table with the following records:

We need to see all records in which the name begins with M. We can run the following command:

SELECT name FROM book WHERE name LIKE 'M%';

All records have been returned because their names begin with the letter M. To see all names that end with 4, you can run the following command:

SELECT name FROM book WHERE name LIKE '%4';

Only one name has been returned because it’s the only one meeting the condition.

We can also surround the search pattern by the wildcard:

SELECT name FROM book WHERE name LIKE '%DB%';

Other than the % wildcard, the LIKE clause can be used together with the _ wildcard. This is the underscore wildcard, and it will only look for a single character.

Let’s work with the Price table with the following records:

Let us check for the record in which the price is like 1_0. We run the following command:

SELECT * FROM price WHERE price LIKE '1_0';

It has returned the record in which the price is 190. We can also try another pattern:

SELECT * FROM price WHERE price LIKE '_2_';

It is possible for us to use the LIKE clause together with the NOT operator. This will return all the records that don’t meet the specified pattern. For example:

Let us use the Price table with the following records:

Let us find all the records where the price does not start with 2:

SELECT * FROM price WHERE price NOT LIKE '2%';

Only one record does not meet the specified pattern.

Order By

This clause helps us to sort out our records in either ascending or descending order. We use it with the SELECT statement, as shown below:

SELECT expression(s) FROM tables [WHERE condition(s)]

It is possible for us to use this clause without adding either the ASC or DESC part. For example:

We will use the Price table with the following records:

Run the following command against the table:

SELECT * FROM price WHERE price LIKE '2%.' ORDER BY price;

In the above command, we have ordered by the price. The records have been ordered with the prices in ascending order. That means that when we don’t specify the order, the sorting is done in ascending order by default.

Let us run the clause with the DESC option:

SELECT * FROM price WHERE price LIKE '2%' ORDER BY price DESC;

The records have been sorted with the price in descending order as we have specified.

Let us use the ORDER BY clause together with the ASC attribute:

SELECT * FROM price WHERE price LIKE '2%.' ORDER BY price ASC;

The records have been ordered but with the prices in ascending order. This is similar to when we use the ORDER BY clause without either ASC or DESC attributes.

DISTINCT

This clause helps us to do away with duplicates when selecting records from a table. This means that it helps us get unique records. Its syntax is given below:

SELECT DISTINCT expression(s) FROM tableName [WHERE condition(s)];

To demonstrate this, we will use the Price table with the following data:

When we select the price column from the table, we get the following result:

SELECT price FROM Price;

We have two records with a price of 250, creating a duplicate. We need to have only unique records. We can filter these by use of the DISTINCT clause as shown below:

SELECT DISTINCT price FROM Price;

We now don’t have any duplicates in the above output.

From

The FROM clause used for fetching data from a database table. It can also help when joining tables. Here is the syntax for the command:

SELECT columnNames FROM tableName;

To see the contents of the book table, run the following command:

SELECT * FROM price;

The clause can help you to fetch only a single column from a database table. For example:

SELECT price FROM Price;

Advanced Tasks Stored Procedure

A procedure is a MariaDB program that you can pass parameters to. A procedure doesn’t return values. To create a procedure, we use the CREATE PROCEDURE command.

To demonstrate how to create and call a procedure, we will create a procedure named myProcedure() that helps us select the name column from the book table. Here is the procedure:

DELIMITER $ CREATE PROCEDURE myProcedure() BEGIN SELECT name FROM book; END; ;

The procedure has been created. We have simply enclosed the SELECT statement within the BEGIN and END clauses of the procedure.

Now, we can call the procedure by its name as shown below:

CALL myProcedure();

The procedure returns the name column of the book table when called.

We can create a procedure that takes in a parameter. For example, we need to select the name of the book and filter using the book id. We can create the following procedure for this:

DELIMITER $ CREATE PROCEDURE myProcedure2(book_id int) BEGIN SELECT name FROM book WHERE id = book_id; END; ;

Above, we have created a procedure named myProcedure2(). This procedure takes one integer parameter named book_id which is the id of the book whose name we need to see. To see the name of the book with an id of 3, we can call the procedure as follows:

CALL myProcedure2(3);

Function

Unlike procedures, we must pass parameters to functions and a function must return a value. To create a function in MariaDB, we use the CREATE FUNCTION statement. The statement takes the following syntax:

CREATE FUNCTION function-name [(parameter datatype [, parameter datatype]) ] RETURNS datatype [LANGUAGE SQL BEGIN declaration-section executable-section END;

The above parameters are described below:

Parameter Description

DEFINER clause This parameter is optional. If you don’t specify it, the definer will become the user who created the function. If there is a need to specify a different definer, include the DEFINER clause in which the user_name will be the definer of the function.

function_name The name that is to be assigned to this function in the MariaDB.

parameter The parameter(s) passed to the function. During the creation of the function, all parameters are treated as IN parameters (rather than OUT/INOUT parameters).

return_datatype The data type of the return value of the function.

LANGUAGE SQL It affects the portability but not the function.

DETERMINISTIC The function will return one result only when given a number of parameters.

NOT DETERMINISTIC It is possible for the function to return a different result when given a number of parameters.

CONTAINS SQL Informs MariaDB that this function contains SQL. The database will not verify whether this is true.

NO SQL This clause is not used, and it has no impact on your function.

READS SQL DATA Tells MariaDB that this function will use SELECT statements to read data, but it won’t modify the data.

MODIFIES SQL DATA Tells MariaDB that this function will use INSERT, DELETE, UPDATE, and other DDL statements to modify SQL data.

declaration-section This is where local variables should be declared.

executable-section The function code should be added here.

Here is an example MariaDB function:

DELIMITER CREATE FUNCTION sumFunc (x INT ) RETURNS INT DETERMINISTIC BEGIN DECLARE sum INT; SET sum = 0; label1: WHILE sum <= 3000 DO SET sum = sum + x; END WHILE label1; RETURN sum; END; DELIMITER ;

We can then call the above function as follows:

select sumFunc(1000);

The command will return the following:

Once you are done with a function, it will be good for you to delete it. This is easy as you only have to call the DROP FUNCTION statement that takes the following syntax:

DROP FUNCTION function_name;

For example, to drop the function named myFunc, we can run the following command:

DROP FUNCTION myFunc; JOIN

When you need to retrieve data from more than one tables at a go, use MariaDB JOINS. This means that a JOIN works on two or more tables. The following three types of JOINS are supported in MariaDB:

INNER/SIMPLE JOIN

LEFT OUTER JOIN/LEFT JOIN

RIGHT OUTER JOIN/RIGHT JOIN

Let us discuss them one-by-one:

INNER JOIN

The inner join returns all rows from the tables in which the join condition is true. Its syntax is as follows:

SELECT columns FROM table-1 INNER JOIN table-2 ON table-1.column = table-2.column;

For example:

We will use our two tables, books, and book.

The book table has the following data:

The Price table has the following data:

The goal is to join the name column from the Book table and the price column from Price table into a single table. This is possible with an inner join, as demonstrated below:

SELECT book.name, price.price FROM book INNER JOIN price ON chúng tôi = chúng tôi

The command returns the following:

LEFT OUTER JOIN

This join returns all the rows from the left-hand table and only rows in which the join condition is true from the other table. Its syntax is as follows:

SELECT columns FROM table-1 LEFT [OUTER] JOIN table-2 ON table-1.column = table-2.column;

The OUTER keyword has been placed within square brackets because it is optional.

For example:

SELECT book.name, price.price FROM book LEFT JOIN price ON chúng tôi = chúng tôi

The command returns the following:

The last record in the above table has no matching value on the left. That is why it has been replaced with NULL.

RIGHT OUTER JOIN

This join returns all the rows from the right-hand table and only rows in which the join condition is true from the other table. Its syntax is as follows:

SELECT columns FROM table-1 RIGHT [OUTER] JOIN table-2 ON table-1.column = table-2.column;

The OUTER keyword has been placed within square brackets because it is optional.

For example:

SELECT book.name, price.price FROM book RIGHT JOIN price ON chúng tôi = chúng tôi

The command returns the following:

The reason is that all rows in the right-hand table were matched to those in the other table. If some of the rows did not match, we would have NULLs in the first column.

Vbscript Variable Declaration With Data Types: Dim, String, Boolean

Variables form the basis of programming. Variables are used to hold value or an expression. Whenever you have a piece of data to work with, you will have to declare a variable.

For example, if you have to store names of students or salaries of employees, you will be using variables named students or salaries.

Variables can also be used for holding expressions. Suppose you have stored the marks of a student in English and Mathematics using the variables markE and markM.

You want to find the total marks. Then, you can use a variable named markT and set its value to markE + markM. In other words, markT = markE + markM. Here, markT is a variable which holds an expression.

In this tutorial, you will learn-

Declaring Variables

Declaring variables is the same as creating variables because you are instructing the computer to reserve memory space. You can name the variable the way you want. It can be short names like x, y or z or more self-describing names like student, Name, salary etc. Providing clear and meaningful names to variables is considered a good programming practice.

There are certain rules for VBScript variable names.

Variable name must begin with a letter. Examples: salary, mark etc. Variables beginning with numbers or special characters are not allowed. Examples: 1stSchool, 3rdCar, _name etc.

Variable name cannot exceed 255 characters.

Variable name should not contain a period (.).

For declaring variables, you need to use the keyword Dim. Suppose you plan to use a variable named “salary” in your VBScript program, syntax

Dim salary;

Just declaring the VBS variables will not help you, use it. You will have to assign a value to it at some point or another and this process is known as initializing the variable. If you are planning to declare a variably named salary, then you can code like this:

Dim salary salary = 10000

The important thing you need to make sure is that you should not assign a value to the variable as and when you declare it. Suppose you write a statement like this:

Dim salary = 10000

If you try to output salary using document.write, it will not return any output.

Code Example

Step 1) Open your text editor and add the following lines of code.

Dim variable1 variable1=”John” document.write(variable1) ‘Dim variable2 = “Smith” ‘document.write(variable2)

Step 2) Save this file as chúng tôi in your preferred location and then open this in IE (following the steps specified in the previous chapter). Now, you will see the value John on the browser.

Again save the file and refresh the IE browser if it is already opened or open the file in the IE browser. You might be wondered to see nothing; neither John nor Smith. The problem here is that you tried to assign the value to the variable while declaring it which is not allowed.

Loose Binding

VBScript provides you the freedom to use variables without declaring it (called loose binding). For example, without having the statement Dim student, you can assign a value to the variable student like – student = “John”

But, it is not at all a good programming practice. If you use a variable without declaring it and misspell the same variable when you use it again, VBScript will not prompt you of the error.

So to make the code easier to read and to identify the errors, you should use the Option Explicit statement at the beginning of your code so that you will be forced to declare all your variables even if you forget to do so. To avoid variable type related issues, it is always good to specify the statement Option Explicit at the beginning of your VBScript code.

Code Example:

Step 1) Open your text editor and add the following lines of code.

Option Explicit ‘Dim markE, markM, markT markE=90 markM=86 markT=markE+markM document.write(“Your total marks is ” & markT & “.”)

Step 2) Save the file as chúng tôi in your preferred location. Now open the file in Internet Explorer and your screen is blank. Why ? because you have used option explicit but not declared variables before using them

Step 4) Save the chúng tôi file and refresh your browser. Now, your output will be like this:

Note – To concatenate two strings, you need to use “&”. In above example, its used inside document.write command. It is obvious that the calculation of total marks is wrong. Now just add the first statement Option Explicit at the beginning of VBScript code (without the Dim statement).

Save the file and see the output. You will get nothing as output which indicates that your code has some error. Here the error is you have not declared variables before using it even after specifying Option Explicit statement.

You can also declare variables using public and private keywords like a public student or private student. But, you have to be more careful while using these two keywords for declaring variables because it will change the scope of your variables.

You can also store multiple values in a single variable and such variables are known as VBScript array variables. Suppose, you want to store details like name, marks, address etc of 30 students. It will be really difficult to create and manage sets of 30 variables for names, marks, addresses and so on.

Instead, you can declare a single variable named students and store the names of all 30 students in this variable. In such case, you will declare the variable as Dim students(29) (array index starts from zero) and you will assign values as

students(0) = "John" students(1) = "Hannah" students(2) = "Kevin" ....... ....... students(28) = "Rose" students(29) = "Emma"

Similarly, you can create variables like marks, address etc to store the respective values of all 30 students. You can also create multidimensional arrays having up to 60 dimensions.

Code Example:

Open your text editor and add the following lines of code.

Option Explicit Dim students(19), marks(19) students(0) = “John” marks(0) = 95 students(1) = “Emma” marks(1) = “83” students(2) = “Kevin” marks(2) = 87

Here, we have stored details of only three students. You can add details of up to 20 students as we have set the size of the array as 20 (as index starts from 0).

VBScript Data Types

In the previous section, you might have noticed that we assigned different types of data to the chúng tôi have stored numbers (mark and salary), strings (name) etc in different variables.

These numbers, strings etc are known as data types. In fact, VBScript has only one data type called Variant. A variant is a special kind of data type which can hold different kinds of information.

If you use Variant in a numeric context, it behaves like a number and when you use it in a string context, it behaves as a string.

In other words, when you specify salary=10000, VBScript assumes that salary is a numeric data type. A Variant makes specific distinctions about the nature of the data. For example, you can use variant type to store Boolean values, currency, date and so on.

These different categories of information that can be contained in a Variant are called subtypes. Though most of the time, Variant behaves in such a way that is most appropriate for the data it contains, you should be aware of different subtypes.

Following is the list of VBScript Data Types.

Empty: A special subtype to represent a variable that has not been assigned with any value yet.

Null: A special subtype to represent a variable assigned with a null value.

Integer: Using 2 bytes to express signed integer in the range -32,768 to 32,767.

Long: Using 4 bytes to express signed integers ranging from -2,147,483,648 to 2,147,483,647.

Single: Using 4 bytes to express real numbers in floating-point format ranging from -3.402823e38 to -1.401298e-45 for negative values, and from 1.401298e-45 to 3.402823e38 for positive value.

Double: Using 8 bytes to express real numbers in floating-point format ranging from -1.79769313486232e308 to -4.94065645841247e-324 for negative values, and from 4.94065645841247e-324 to 1.79769313486232e308 for positive values.

Currency: Using 8 bytes to express real numbers in decimal format ranging from -922,337,293,685,477.5808 to 922,337,293,685,477.5807.

Date: Using 8 bytes to express dates ranging from January 1, 100 to December 31, 9999.

String: Using 1 byte per character to express a sequence of characters that can be up to approximately 2 billion characters.

Object: A special subtype to represent a reference to an object.

Error: A special subtype to represent an error number.

Boolean: Using 2 bytes to contain either True or False.

Byte: Using 1 byte to express integer in the range 0 to 255.

There are two built-in VBScript functions that help you know the subtype of a variable: “varType()” and “typeName()”.

The var type returns the numeric representation and typeName() returns the text representation of the subtype of the variable. Each subtype has a predefined numeric representation.

Code Example

Open your text editor and add the following lines of code.

Option Explicit Dim a a = Empty

Dim b b = Null

Dim c c = 4

Dim d d = -2100483648

Dim e e = -3.402823E38

Dim f f = “John”

Dim g g = True

Save the file as chúng tôi and open it in IE. Your output will look like this:

NOTE: You can also declare variables using public and private keywords like public student or private student. But, you have to be more careful while using these two keywords for declaring variables because it will change the scope of your variables.

Summary

Variables are used to hold value or an expression while programming. Variables are to be declared and initialized separately.

Though you can use variables without declaring, declaring variables before using them is considered as a good programming practice.

A variant is the only data type of VBScript and variant has different subtypes including String, Boolean, Integer, Currency etc.

Troubleshooting

In case you see a blank page after you run the code, do the following

Press F12 to open developer tools

In left toolbar scroll down until you see “Emulation” settings page

Change Document Mode from a default (“Edge”) to 10

Add the following code to the head

Comprehensive Guide To R Packages With Syntax & Code

Introduction to R Packages

R packages are a set of predefined functions as a library to be used while deploying the R program to care for reusability and less code approach R programs. R packages are externally developed and can be imported to the R environment in order to use the available function which belongs to that package. R packages are managed by the R community network known as CRAN for providing and provisioning with the R programming language. Apart from the standard R packages, there are several external packages available for use in the R program. One of the popular graphical packages in R is ggplot2.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Where do we Find Packages?

Packages are available on the internet through different sources. However, there are certain trusted repositories from where we can download the packages.

Here are the two important repositories that are available online.

CRAN(Comprehensive R Archive Network): This is the official R community with a network of FTP and webservers that contains the latest code and documentation of R. Before you post your packages online, it goes through a series of tests that adheres to CRAN policy.

GitHub: GitHub is another famous repository but not specific to chúng tôi online community can share their packages with other people, and it is used for version control as well. GitHub is open-source and doesn’t have any review process.

List of Useful R Packages

There are several packages in R and can be downloaded from CRAN or GitHub. Below are the packages that can be used for specific purposes.

1. Loading the Data from External Sources

DBI: To establish communication between the relational database and R.

RSQlite: It is used to read data from relational databases.

2. Data Manipulation

Dplyr: It is used for data manipulation like subsetting, provides shortcuts to access data and generates sql queries.

Tidyr – It is used to convert data into tiny formats.

stringr– manipulate string expressions and character strings.

lubridate- To work with data and time.

3. Data Visualization

Rgl: To work on 3D visualizations.

ggvis: To create and build grammar of graphics.

googlevis: To use google visualization tools in R.

4. Web-Based Packages

XML: To read and write XML documents in R.

Jsonlite: To read json data tables.

Obtaining R Packages

available.packages(): There are approximately 5200 packages available in the CRAN network.

CRAN has task views that group packages under a particular topic.

Installing R Packages

We can install packages directly through IDE or through commands. To install packages, we use the below function and specify the package name.

Syntax:

install.packages() 

Code:

install.packages(“ggplot2”)

The above code installs the ggplot2 package and its dependent packages, if any.

We can install several packages at a time by specifying the package’s names under a character vector.

Syntax:

install.packages(c(“package 1”,”package 2”,”package 3”))

Code:

install.packages(c(“ggplot2”,”slidify”,”deplyr”))

Installing using R Studio Loading R Packages

After installing the R package, we need to load them into R to start making use of the installed packages.

We use the below function to load the packages.

Syntax:

library(package name)

Note: The package name need not be given in quotes.

Code:

There are certain packages that display messages when loaded. Some of them don’t. We can see the details of the library installed with the help of the below code.

Code:

search()

Output:

“package:lattice”    “package:ggplot2”    “package:makeslides”

“package:knitr”      “package:slidify”    “tools:rstudio”

Creating Your own Package

Before we create our own package, we should keep the below checklist in our mind before we proceed to create a package.

Organizing the code is one of the most important things while writing code in the package. We lose half the time searching for the code location instead of improving the code. Put all the files in a folder that is easily accessible.

Documenting the code helps you understand the purpose of the code. When we don’t revisit the code often, we forget why we have written the code in a certain way. It can also help people to understand your code better when shared with them.

Sharing the scripts through email has become archaic. The easy way is to upload your code and distribute it on GitHub. It is possible you get feedback that can help you enhance the code.

To create your own package, we have to install the devtools package.

Code:

install.packages("devtools")

To help with the documentation, we can use the below package.

Code:

After installing the package devtools, you can create your own package.

Code:

devtools::create ("packagename")

In the place of “packagename”, you can give the name you wish. You can now add your functions under this package.

You can create the same filename as your function name.

Syntax:

Devtools:create(“firstpackage”)

Distributing Package

You can distribute your package on GitHub by using the devtools package.

We use the below code to distribute our package on Github.

Code:

devtools::install_github("yourusername/firstpackage")

You can give your github username and package name you have created above.

Here are the Required Files for a Package

Functions

Documentation

Data

Once we have all the above files, we are good to post them in the repository.

Recommended Articles

This is a guide to R Packages. Here we discuss the list of useful R packages, installing packages using R studio and creating your own package, etc. You may also look at the following articles to learn more –

Finding Unique Elements From Tuple In Python

In this article, we will learn a Python program to find unique elements from a tuple.

Methods Used

The following are the various methods to accomplish this task −

Using for loop and append() function

Using collections.Counter() function

Using set() function

Tuples are an immutable, unordered data type used to store collections in Python. It can store multiple values in it. Lists and tuples are similar in many ways, but a list has a variable length and is mutable in comparison to a tuple which has a fixed length and is immutable.

Method 1: Using for loop and append() function Algorithm (Steps)

Following are the Algorithms/steps to be followed to perform the desired task. −

Create a function(uniqueElements) that returns the unique elements in a tuple passed to it as an argument.

Create a new empty list for storing the resultant unique elements of the tuple.

Use the for loop to traverse through each element in a tuple.

Use the if conditional statement along with the not in operator to check whether the corresponding tuple element is not present in the above-defined new list.

Use the append() function(adds the element to the list at the end) to append the element to the new list if the condition is true.

Use the tuple() function to convert the list into a tuple.

Return the resultant tuple.

Create a variable to store the input tuple.

Call the above-defined uniqueElements function by passing an input tuple to it and print the resultant tuple.

Example

The following program returns unique elements in an input tuple using the for loop and append() function −

# function that returns the unique elements in a tuple passed to it def uniqueElements(inputTuple): # creating a new list for storing unique elements newList = [] # traversing through each element in a tuple for k in inputTuple: # appending that corresponding tuple element to the new list # if it is not present in it(i.e, storing all unique elements) if k not in newList: newList.append(k) # converting the list into a tuple resultTuple = tuple(newList) # returning the resultant tuple return resultTuple # input tuple inputTuple = (5, 1, 8, 7, 7, 3, 3, 6, 1, 6) # Printing input tuple print("The given Tuple is:", inputTuple) #calling the above-defined uniqueElements function by passing input tuple to it print("The Unique elements of the tuple are:", uniqueElements(inputTuple)) Output

On execution, the above program will generate the following output −

The given Tuple is: (5, 1, 8, 7, 7, 3, 3, 6, 1, 6) The Unique elements of the tuple are: (5, 1, 8, 7, 3, 6) Method 2: Using collections.Counter() function

Counter() function(a sub-class that counts the hashable objects. It implicitly creates a hash table of an iterable when called/invoked)

Algorithm (Steps)

Following are the Algorithms/steps to be followed to perform the desired task. −

Use the import keyword to import the Counter function from the collections module.

Create a function(uniqueElements) that returns the unique elements in a tuple passed to it as an argument.

Pass the given tuple as an argument to the Counter() function which stores all the unique tuple elements along with their frequencies as a dictionary.

Return the keys(unique tuple elements ) of the above frequency dictionary as a tuple using the keys() and tuple() functions.

Example

The following program returns unique elements in an input tuple using the Counter function of the collections module −

# importing Counter from the collections module from collections import Counter # function that returns the unique elements in a tuple passed to it def uniqueElements(inputTuple): #Getting all the unique tuple elements along with their frequencies frequency = Counter(inputTuple) # Returning all the unique tuple elements using the keys() function return tuple(frequency.keys()) # input tuple inputTuple = (5, 1, 8, 7, 7, 3, 3, 6, 1, 6) # Printing input tuple print("The given Tuple is:", inputTuple) #calling the above-defined uniqueElements function by passing input tuple to it print("The Unique elements of the tuple are:", uniqueElements(inputTuple)) Output

On execution, the above program will generate the following output −

The given Tuple is: (5, 1, 8, 7, 7, 3, 3, 6, 1, 6) The Unique elements of the tuple are: (5, 1, 8, 7, 3, 6) Method 3: Using the set() function

set() function- creates a set object. A set list will appear in random order because the items are not ordered. It removes all the duplicates)

Algorithm (Steps)

Following are the Algorithms/steps to be followed to perform the desired task. −

Create a function(uniqueElements) that returns the unique elements in a tuple passed to it as an argument.

Return all the unique elements from a tuple using the set() function and convert it into a tuple using the tuple() function(creates a tuple).

Example

The following program returns unique elements in an input tuple using the set() function −

# function that returns the unique elements in a tuple passed to it def uniqueElements(inputTuple): # Getting all the unique elements of the tuple using the set() function resultUnique = set(inputTuple) # returning unique elements as a tuple using the tuple() function return tuple(resultUnique) # input tuple inputTuple = (5, 1, 8, 'tutorialspoint', 7, 7, 'tutorialspoint', 3, 3, 6, 1, 6) # Printing input tuple print("The given Tuple is:", inputTuple) #calling the above-defined uniqueElements function by passing input tuple to it print("The Unique elements of the tuple are:", uniqueElements(inputTuple)) Output

On execution, the above program will generate the following output −

The given Tuple is: (5, 1, 8, 'tutorialspoint', 7, 7, 'tutorialspoint', 3, 3, 6, 1, 6) The Unique elements of the tuple are: (1, 3, 5, 6, 7, 8, 'tutorialspoint') Conclusion

We covered how to find unique elements of a tuple using three ways in this article. We also learned how to use the Counter() function to find not only frequencies but also unique elements in any iterable, such as a list, tuple, etc. The Counter() approach is the most efficient of the three because it uses a dictionary to store frequencies.

Delete Elements In A Slice In Golang

Slices in Golang are dynamically-sized sequences that provide a more powerful interface than arrays. They are commonly used for storing collections of related data. Sometimes, we may want to delete elements from a slice. In this article, we will discuss how to delete elements in a slice in Golang.

Deleting Elements in a Slice

In Golang, we can delete elements from a slice using the built-in append() function. Here’s how it works −

Example

Here’s an example of how to use the deleteElement() function to delete an element from a slice −

package main import "fmt" func deleteElement(slice []int, index int) []int { return append(slice[:index], slice[index+1:]...) } func main() { slice := []int{1, 2, 3, 4, 5} fmt.Println("Before deletion:", slice) slice = deleteElement(slice, 2) fmt.Println("After deletion:", slice) } Output Before deletion: [1 2 3 4 5] After deletion: [1 2 4 5]

In this example, we define a function deleteElement() that takes a slice slice and an index index as input. The function then returns a new slice that contains all the elements of the slice except the one at the specified index.

The append() function takes two or more slices as arguments and concatenates them into a single slice. In this case, we’re creating a new slice by concatenating the elements of slice before the specified index with the elements after the index.

Example

In this example, we create a slice of integers slice and specify the index of the element we want to delete. We then call the deleteElement() function and pass in the slice and index as arguments. The function returns a new slice with the specified element removed, which we assign back to slice.

package main import "fmt" func main() { slice := []int{1, 2, 3, 4, 5} index := 2 slice = deleteElement(slice, index) fmt.Println(slice) } func deleteElement(slice []int, index int) []int { return append(slice[:index], slice[index+1:]...) } Output [1 2 4 5]

We can also delete multiple elements from a slice by calling the deleteElement() function multiple times. However, this can be inefficient if we need to delete a large number of elements. In this case, we can use the append() function with the … operator to concatenate multiple slices.

Example

Here’s an example of how to delete multiple elements from a slice using the append() function −

package main import ( "fmt" "sort" ) func deleteElements(slice []int, indices []int) []int { sort.Sort(sort.Reverse(sort.IntSlice(indices))) for _, index := range indices { slice = append(slice[:index], slice[index+1:]...) } return slice } func main() { slice := []int{1, 2, 3, 4, 5} indices := []int{1, 3} slice = deleteElements(slice, indices) fmt.Println(slice) } Output [1 3 5]

In this example, we define a function deleteElements() that takes a slice and a slice of indices as input. The function first sorts the indices in descending order using the sort.Sort() function. This is necessary because deleting elements from a slice changes the indices of the remaining elements.

The function then loops over the indices in indices, calling the deleteElement() function with each index to delete the corresponding element from the slice. The resulting slice is returned by the function.

Example

Here’s an example of how to use the deleteElements() function to delete multiple elements from a slice −

package main import ( "fmt" "sort" ) func deleteElements(slice []int, indices []int) []int { sort.Sort(sort.Reverse(sort.IntSlice(indices))) for _, index := range indices { slice = append(slice[:index], slice[index+1:]...) } return slice } func main() { slice := []int{1, 2, 3, 4, 5} indices := []int{1, 3} slice = deleteElements(slice, indices) fmt.Println(slice) } Output [1 3 5]

In this example, we create a slice of integers slice and a slice of booleans boolSlice. We then remove elements at index 1 and 2 using the append() function and print the new slices.

Example package main import "fmt" func main() { slice := []int{1, 2, 3, 4, 5} slice = append(slice[:1], slice[3:]...) boolSlice := []bool{true, false, true, true} boolSlice = append(boolSlice[:2], boolSlice[3:]...) fmt.Println(slice) fmt.Println(boolSlice) } Output [1 4 5] [true false true]

In the first example, we remove the elements at index 1 and 2 using append() and the slice expression slice[:1] and slice[3:]. The … operator after slice[3:] is used to spread the elements in the slice. This means that instead of appending a slice to slice[:1], we append each individual element of slice[3:] to slice[:1]. This effectively removes the elements at index 1 and 2.

In the second example, we remove the element at index 2 using a similar approach. We use boolSlice[:2] to include the first two elements of the slice and boolSlice[3:] to include all the elements from index 3 to the end of the slice. The … operator is used again to spread the elements in the slice.

It’s important to note that the append() function creates a new slice with the updated elements. This means that we need to assign the result of append() back to the original slice variable. If we don’t do this, we’ll end up with the original slice and no elements removed.

Conclusion

Deleting elements from a slice in Golang is simple and can be done using the append() function and slice expressions. By using these techniques, we can efficiently remove elements from a slice without needing to create a new slice from scratch.

Update the detailed information about Jsp Elements – Declaration, Syntax & Expression on the Cattuongwedding.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!