title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Most efficient way to create HTML elements using jQuery | 05 Mar, 2021
In this article, we will look at 4 jQuery techniques that can be used to create an HTML element, and we will be testing out the code for the creation of an element by different methods.
Approach: One of the easier ways is to just use $ (‘<div></div>’) which is great for readability but technically the piece of code will create an <div> element, but it will not add it to your HTML DOM. You need to use some other methods like append(), prepend(), etc.
It is recommended to run and test the code below and check out the fastest technique for creating an element, as the time taken by the code varies depending upon the web browser.
For the below code, you must incorporate jQuery into your code. One of the easiest ways to do this is to just copy and paste the jQuery CDN into your HTML header tag.
CDN link used:
https://code.jquery.com/jquery-3.5.1.min.js
Method 1: In the following example, the document.createElement() method creates the HTML “div” element node. The date.getTime() method is used to return the number of milliseconds since 1 January 1970. Run the code below to find out its performance.
Syntax:
$((document.createElement('div')));
HTML
<!DOCTYPE html><html><head> <!-- Embedding jQuery using jQuery CDN --> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"> </script></head><body> <script> // returns time in milliseconds var start = new Date().getTime(); for (i = 0; i < 1000000; ++i) { var e = $((document.createElement('div'))); } var end = new Date().getTime(); alert(end - start); </script></body></html>
Output:
875
Method 2:
Syntax:
$(('<div>'));
HTML
<!DOCTYPE html><html><head> <!-- Embedding jQuery using jQuery CDN --> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"> </script></head><body> <script> // returns time in milliseconds var start = new Date().getTime(); for (i = 0; i < 1000000; ++i) { var e = $(('<div>')); } var end = new Date().getTime(); alert(end - start); </script></body></html>
Output:
1538
Method 3:
Syntax:
$(('<div></div>'));
HTML
<!DOCTYPE html><html><head> <!-- Embedding jQuery using jQuery CDN --> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script></head><body> <script> // returns time in milliseconds var start = new Date().getTime(); for (i = 0; i < 1000000; ++i) { var e = $(('<div></div>')); } var end = new Date().getTime(); alert(end - start); </script></body></html>
Output:
2097
Method 4:
Syntax:
$(('<div/>'));
HTML
<!DOCTYPE html><html><head> <!-- Embedding jQuery using jQuery CDN --> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"> </script></head><body> <script> // returns time in milliseconds var start = new Date().getTime(); for (i = 0; i < 1000000; ++i) { var e = $(('<div/>')); } var end = new Date().getTime(); alert(end - start); </script></body></html>
Output:
2037
For better understanding, try running benchmarks on JavaScript engines.
Conclusion: The $(document.createElement(‘div’)); is the fastest method, even the benchmarking supports, this is the fastest technique to create an HTML element using jQuery.
Reason: It is because jQuery doesn’t have to identify it as an element and create the element itself.
Alternate way: Using just document.createElement(‘div’) without jQuery will increase the efficiency a lot and will also append the element to DOM automatically.
jQuery-HTML/CSS
Picked
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Mar, 2021"
},
{
"code": null,
"e": 214,
"s": 28,
"text": "In this article, we will look at 4 jQuery techniques that can be used to create an HTML element, and we will be testing out the code for the creation of an element by different methods."
},
{
"code": null,
"e": 482,
"s": 214,
"text": "Approach: One of the easier ways is to just use $ (‘<div></div>’) which is great for readability but technically the piece of code will create an <div> element, but it will not add it to your HTML DOM. You need to use some other methods like append(), prepend(), etc."
},
{
"code": null,
"e": 662,
"s": 482,
"text": "It is recommended to run and test the code below and check out the fastest technique for creating an element, as the time taken by the code varies depending upon the web browser. "
},
{
"code": null,
"e": 830,
"s": 662,
"text": "For the below code, you must incorporate jQuery into your code. One of the easiest ways to do this is to just copy and paste the jQuery CDN into your HTML header tag. "
},
{
"code": null,
"e": 845,
"s": 830,
"text": "CDN link used:"
},
{
"code": null,
"e": 889,
"s": 845,
"text": "https://code.jquery.com/jquery-3.5.1.min.js"
},
{
"code": null,
"e": 1141,
"s": 889,
"text": "Method 1: In the following example, the document.createElement() method creates the HTML “div” element node. The date.getTime() method is used to return the number of milliseconds since 1 January 1970. Run the code below to find out its performance."
},
{
"code": null,
"e": 1150,
"s": 1141,
"text": "Syntax: "
},
{
"code": null,
"e": 1186,
"s": 1150,
"text": "$((document.createElement('div')));"
},
{
"code": null,
"e": 1191,
"s": 1186,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <!-- Embedding jQuery using jQuery CDN --> <script src=\"https://code.jquery.com/jquery-3.5.1.min.js\" integrity=\"sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=\" crossorigin=\"anonymous\"> </script></head><body> <script> // returns time in milliseconds var start = new Date().getTime(); for (i = 0; i < 1000000; ++i) { var e = $((document.createElement('div'))); } var end = new Date().getTime(); alert(end - start); </script></body></html>",
"e": 1765,
"s": 1191,
"text": null
},
{
"code": null,
"e": 1773,
"s": 1765,
"text": "Output:"
},
{
"code": null,
"e": 1777,
"s": 1773,
"text": "875"
},
{
"code": null,
"e": 1787,
"s": 1777,
"text": "Method 2:"
},
{
"code": null,
"e": 1796,
"s": 1787,
"text": "Syntax: "
},
{
"code": null,
"e": 1810,
"s": 1796,
"text": "$(('<div>'));"
},
{
"code": null,
"e": 1815,
"s": 1810,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <!-- Embedding jQuery using jQuery CDN --> <script src=\"https://code.jquery.com/jquery-3.5.1.min.js\" integrity=\"sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=\" crossorigin=\"anonymous\"> </script></head><body> <script> // returns time in milliseconds var start = new Date().getTime(); for (i = 0; i < 1000000; ++i) { var e = $(('<div>')); } var end = new Date().getTime(); alert(end - start); </script></body></html>",
"e": 2357,
"s": 1815,
"text": null
},
{
"code": null,
"e": 2365,
"s": 2357,
"text": "Output:"
},
{
"code": null,
"e": 2370,
"s": 2365,
"text": "1538"
},
{
"code": null,
"e": 2380,
"s": 2370,
"text": "Method 3:"
},
{
"code": null,
"e": 2388,
"s": 2380,
"text": "Syntax:"
},
{
"code": null,
"e": 2408,
"s": 2388,
"text": "$(('<div></div>'));"
},
{
"code": null,
"e": 2413,
"s": 2408,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <!-- Embedding jQuery using jQuery CDN --> <script src=\"https://code.jquery.com/jquery-3.5.1.min.js\" integrity=\"sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=\" crossorigin=\"anonymous\"></script></head><body> <script> // returns time in milliseconds var start = new Date().getTime(); for (i = 0; i < 1000000; ++i) { var e = $(('<div></div>')); } var end = new Date().getTime(); alert(end - start); </script></body></html>",
"e": 2957,
"s": 2413,
"text": null
},
{
"code": null,
"e": 2965,
"s": 2957,
"text": "Output:"
},
{
"code": null,
"e": 2970,
"s": 2965,
"text": "2097"
},
{
"code": null,
"e": 2980,
"s": 2970,
"text": "Method 4:"
},
{
"code": null,
"e": 2988,
"s": 2980,
"text": "Syntax:"
},
{
"code": null,
"e": 3003,
"s": 2988,
"text": "$(('<div/>'));"
},
{
"code": null,
"e": 3008,
"s": 3003,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <!-- Embedding jQuery using jQuery CDN --> <script src=\"https://code.jquery.com/jquery-3.5.1.min.js\" integrity=\"sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=\" crossorigin=\"anonymous\"> </script></head><body> <script> // returns time in milliseconds var start = new Date().getTime(); for (i = 0; i < 1000000; ++i) { var e = $(('<div/>')); } var end = new Date().getTime(); alert(end - start); </script></body></html>",
"e": 3541,
"s": 3008,
"text": null
},
{
"code": null,
"e": 3549,
"s": 3541,
"text": "Output:"
},
{
"code": null,
"e": 3554,
"s": 3549,
"text": "2037"
},
{
"code": null,
"e": 3626,
"s": 3554,
"text": "For better understanding, try running benchmarks on JavaScript engines."
},
{
"code": null,
"e": 3802,
"s": 3626,
"text": "Conclusion: The $(document.createElement(‘div’)); is the fastest method, even the benchmarking supports, this is the fastest technique to create an HTML element using jQuery. "
},
{
"code": null,
"e": 3904,
"s": 3802,
"text": "Reason: It is because jQuery doesn’t have to identify it as an element and create the element itself."
},
{
"code": null,
"e": 4065,
"s": 3904,
"text": "Alternate way: Using just document.createElement(‘div’) without jQuery will increase the efficiency a lot and will also append the element to DOM automatically."
},
{
"code": null,
"e": 4081,
"s": 4065,
"text": "jQuery-HTML/CSS"
},
{
"code": null,
"e": 4088,
"s": 4081,
"text": "Picked"
},
{
"code": null,
"e": 4093,
"s": 4088,
"text": "HTML"
},
{
"code": null,
"e": 4100,
"s": 4093,
"text": "JQuery"
},
{
"code": null,
"e": 4117,
"s": 4100,
"text": "Web Technologies"
},
{
"code": null,
"e": 4122,
"s": 4117,
"text": "HTML"
}
] |
SQL Query to get information of employee where employee Is Not Assigned to the Department | 01 Apr, 2021
In this article, we will discuss the overview of SQL query and our main focus will be on how to get information of employee where employee Is Not Assigned to the Department in SQL. Let’s discuss it step by step.
Introduction :Queries help us to interact with the database for various operations of data retrieval, updating, deletion, and inserting. In this article let us see a query to get the information of an employee where the employee is not assigned to any department. When in a table if any attribute is not assigned with any value it would be the NULL so let us execute the query on a table in the database company.
Step-1: Creating a database –Creating a database company by using the following SQL query as follows.
CREATE DATABASE company;
Output :
Step-2: Using the database –Using the database company using the following SQL query as follows.
USE company;
Output :
Step-3: Creating a table –Creating a table employee with 5 columns using the following SQL query as follows.
CREATE TABLE employee
(
emp_id varchar(20),
emp_name varchar(20),
emp_dept varchar(20),
emp_age INT,
emp_sex varchar(8)
);
Output :
Step-4: Verifying the database –To view the description of the database using the following SQL query as follows.
DESCRIBE employee;
Output :
Step-5: Inserting data into the table –Inserting rows into employee table using the following SQL query as follows.
INSERT INTO employee VALUES('E00001','JHONNY','BACKEND DEVELOPER',26,'male');
INSERT INTO employee VALUES('E00002','DARSHI',NULL,27,'male');
INSERT INTO employee VALUES('E00003','JASMINE',NULL,37,'female');
INSERT INTO employee VALUES('E00004','LILLY',NULL,47,'female');
INSERT INTO employee VALUES('E00005','RONALD','UI DEVELOPER',26,'male');
Output :
Step-6: Verifying the inserted data –Viewing the table employee after inserting rows by using the following SQL query as follows.
SELECT* FROM employee;
Output :
Query to find the employees whose departments are not assigned :Here, we will see how to query to find the employees whose departments are not assigned by using the following SQL query as follows.
Syntax :
SELECT*
FROM table_name
WHERE column_name IS NULL;
Selecting Data Query –
SELECT*
FROM employee
WHERE emp_dept IS NULL;
Output :In this table, all the employee records whose department is NULL value are obtained.
Query to find the employees whose departments are assigned :Here, we will see how to query to find the employees whose departments are assigned using the following SQL as follows.
Syntax :
SELECT *
FROM table_name
WHERE column_name IS NOT NULL;
Selecting Query –
SELECT *
FROM employee
WHERE emp_dept IS NOT NULL;
Output :All the records of an employee whose department is assigned are obtained.
DBMS-SQL
Picked
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 Apr, 2021"
},
{
"code": null,
"e": 266,
"s": 54,
"text": "In this article, we will discuss the overview of SQL query and our main focus will be on how to get information of employee where employee Is Not Assigned to the Department in SQL. Let’s discuss it step by step."
},
{
"code": null,
"e": 679,
"s": 266,
"text": "Introduction :Queries help us to interact with the database for various operations of data retrieval, updating, deletion, and inserting. In this article let us see a query to get the information of an employee where the employee is not assigned to any department. When in a table if any attribute is not assigned with any value it would be the NULL so let us execute the query on a table in the database company."
},
{
"code": null,
"e": 781,
"s": 679,
"text": "Step-1: Creating a database –Creating a database company by using the following SQL query as follows."
},
{
"code": null,
"e": 806,
"s": 781,
"text": "CREATE DATABASE company;"
},
{
"code": null,
"e": 815,
"s": 806,
"text": "Output :"
},
{
"code": null,
"e": 912,
"s": 815,
"text": "Step-2: Using the database –Using the database company using the following SQL query as follows."
},
{
"code": null,
"e": 925,
"s": 912,
"text": "USE company;"
},
{
"code": null,
"e": 934,
"s": 925,
"text": "Output :"
},
{
"code": null,
"e": 1043,
"s": 934,
"text": "Step-3: Creating a table –Creating a table employee with 5 columns using the following SQL query as follows."
},
{
"code": null,
"e": 1166,
"s": 1043,
"text": "CREATE TABLE employee\n(\nemp_id varchar(20),\nemp_name varchar(20),\nemp_dept varchar(20),\nemp_age INT,\nemp_sex varchar(8)\n);"
},
{
"code": null,
"e": 1175,
"s": 1166,
"text": "Output :"
},
{
"code": null,
"e": 1289,
"s": 1175,
"text": "Step-4: Verifying the database –To view the description of the database using the following SQL query as follows."
},
{
"code": null,
"e": 1308,
"s": 1289,
"text": "DESCRIBE employee;"
},
{
"code": null,
"e": 1317,
"s": 1308,
"text": "Output :"
},
{
"code": null,
"e": 1433,
"s": 1317,
"text": "Step-5: Inserting data into the table –Inserting rows into employee table using the following SQL query as follows."
},
{
"code": null,
"e": 1783,
"s": 1433,
"text": " INSERT INTO employee VALUES('E00001','JHONNY','BACKEND DEVELOPER',26,'male');\n INSERT INTO employee VALUES('E00002','DARSHI',NULL,27,'male');\n INSERT INTO employee VALUES('E00003','JASMINE',NULL,37,'female');\n INSERT INTO employee VALUES('E00004','LILLY',NULL,47,'female');\n INSERT INTO employee VALUES('E00005','RONALD','UI DEVELOPER',26,'male'); "
},
{
"code": null,
"e": 1792,
"s": 1783,
"text": "Output :"
},
{
"code": null,
"e": 1922,
"s": 1792,
"text": "Step-6: Verifying the inserted data –Viewing the table employee after inserting rows by using the following SQL query as follows."
},
{
"code": null,
"e": 1945,
"s": 1922,
"text": "SELECT* FROM employee;"
},
{
"code": null,
"e": 1954,
"s": 1945,
"text": "Output :"
},
{
"code": null,
"e": 2151,
"s": 1954,
"text": "Query to find the employees whose departments are not assigned :Here, we will see how to query to find the employees whose departments are not assigned by using the following SQL query as follows."
},
{
"code": null,
"e": 2160,
"s": 2151,
"text": "Syntax :"
},
{
"code": null,
"e": 2212,
"s": 2160,
"text": "SELECT*\nFROM table_name\nWHERE column_name IS NULL;"
},
{
"code": null,
"e": 2235,
"s": 2212,
"text": "Selecting Data Query –"
},
{
"code": null,
"e": 2284,
"s": 2235,
"text": " SELECT*\n FROM employee\n WHERE emp_dept IS NULL;"
},
{
"code": null,
"e": 2378,
"s": 2284,
"text": "Output :In this table, all the employee records whose department is NULL value are obtained. "
},
{
"code": null,
"e": 2558,
"s": 2378,
"text": "Query to find the employees whose departments are assigned :Here, we will see how to query to find the employees whose departments are assigned using the following SQL as follows."
},
{
"code": null,
"e": 2567,
"s": 2558,
"text": "Syntax :"
},
{
"code": null,
"e": 2623,
"s": 2567,
"text": "SELECT *\nFROM table_name\nWHERE column_name IS NOT NULL;"
},
{
"code": null,
"e": 2641,
"s": 2623,
"text": "Selecting Query –"
},
{
"code": null,
"e": 2692,
"s": 2641,
"text": "SELECT *\nFROM employee\nWHERE emp_dept IS NOT NULL;"
},
{
"code": null,
"e": 2774,
"s": 2692,
"text": "Output :All the records of an employee whose department is assigned are obtained."
},
{
"code": null,
"e": 2787,
"s": 2778,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 2794,
"s": 2787,
"text": "Picked"
},
{
"code": null,
"e": 2798,
"s": 2794,
"text": "SQL"
},
{
"code": null,
"e": 2802,
"s": 2798,
"text": "SQL"
}
] |
Getting Started with PyPy. Up-and-running with PyPy, an... | by Ahmed Gad | Towards Data Science | The Python programming language is an interface that can be implemented in many ways. Some examples include CPython which uses the C language, Jython that is implemented using Java, and so on.
Despite being the most popular, CPython is not the fastest. PyPy is an alternate Python implementation that is both compliant and fast. PyPy depends on just-in-time (JIT) compilation that dramatically reduces the execution time for long-running operations.
In this tutorial, PyPy will be introduced for beginners to highlight how it is different from CPython. We’ll also cover its advantages and limitations. Then we’ll take a look at how to download and use PyPy to execute a simple Python script. PyPy supports hundreds of Python libraries, including NumPy.
Specifically, this tutorial covers the following:
A quick overview of CPython
Introduction to PyPy and its features
PyPy limitations
Running PyPy on Ubuntu
Execution time of PyPy vs CPython
Let’s get started.
Before discussing PyPy, it is important to know how CPython works. My previous tutorial titled Boosting Python Scripts With Cython gave a longer introduction to how CPython works, but it won’t hurt to have a quick recap here about the important points. Below you can see a visualization of the execution pipeline of a Python script implemented using CPython.
Given a Python .py script, the source code is first compiled using the CPython compiler into bytecode. The bytecode is generated and saved in a file with a .pyc extension. The bytecode is then executed using the CPython interpreter within a virtual environment.
There are benefits to using the compiler to convert the source code into bytecode. If no compiler is used, then the interpreter will work directly on the source code by translating it line by line into machine code. The disadvantage of doing this is that some processes have to be applied for translating each line of source code into machine code, and such processes will be repeated for each line. For example, syntax analysis will be applied to each line independently from the other lines, and thus the interpreter takes a lot of time to translate the code. The compiler solves this issue as it is able to process all of the code at once, and thus syntax analysis will be applied only once rather than to each line of code. The generated bytecode from the compiler will thus be interpreted easily. Note that compiling the entire source code might not be helpful in some cases, and we’ll see a clear example of this when discussing PyPy.
After the bytecode is generated, it is executed by the interpreter running in the virtual machine. The virtual environment is beneficial, as it isolates the CPython bytecode from the machine, and thus makes Python cross-platform.
Unfortunately, just using a compiler to generate the bytecode is not enough to speed up the execution of CPython. The interpreter works by translating the code, each time it is executed, into machine code. Thus, if a line L takes X seconds to be executed, then executing it 10 times will have a cost of X*10 seconds. For long-running operations, this is too costly in its execution time.
Based on the drawbacks of CPython, let’s now take a look at PyPy.
PyPy is a Python implementation similar to CPython that is both compliant and fast. “Compliant” means that PyPy is compatible with CPython, as you can use nearly all CPython syntax in PyPy. There are some compatibility differences, as mentioned here. The most powerful advantage of PyPy is its speed. PyPy is much faster than CPython; we’ll see tests later on where PyPy performs about 7 times faster. In some cases it might even be tens or hundreds of times faster than CPython. So how does PyPy achieve its speed?
PyPy uses a just-in-time (JIT) compiler that is able to dramatically increase the speed of Python scripts. The type of compilation used in CPython is ahead-of-time (AOT), meaning that all of the code will be translated into bytecode before being executed. JIT just translates the code at runtime, only when it is needed.
The source code might contain code blocks that are not executed at all, but which are still being translated using the AOT compiler. This leads to slower processing times. When the source code is large and contains thousands of lines, using a JIT makes a big difference. For AOT, the entire source code will be translated and thus take a lot of time. For JIT, just the needed parts of the code will be executed, making it a lot faster.
After PyPy translates a part of the code, it then gets cached. This means the code is translated only once, and then the translation is used later. The CPython interpreter repeats the translation each time the code is executed, an additional cause for its slowness.
PyPy is not the only way to boost the performance of Python scripts — but it is the easiest way. For example, Cython could be used to increase the speed of assigning C types to the variables. The problem is that Cython asks the developer to manually inspect the source code and optimize it. This is tiresome, and the complexity increases as the code size increases. When PyPy is used, you just run the regular Python code much faster without any effort at all.
Standard Python uses the C stack. This stack stores the sequence of functions that are called from each other (recursion). Because the stack size is limited, you are limited in the number of function calls.
PyPy uses Stackless Python, a Python implementation that does not use the C stack. Instead, it stores the function calls in the heap alongside the objects. The heap size is greater than the stack size, and thus you can do more function calls.
Stackless Python also supports microthreads, which are better than regular Python threads. Within the single Stackless Python thread you can run thousands of tasks, called “tasklets,” with all of them running on the same thread.
Using tasklets allows running concurrent tasks. Concurrency means that two tasks work simultaneously by sharing the same resources. One task runs for some time, then stops to make room for the second task to be executed. Note that this is different from parallelism, which involves running the two tasks separately but at the same time.
Using tasklets reduces the number of threads created, and thus reduces the overhead of managing all these threads by the OS. As a result, speeding up the execution by swapping between two threads is more time-intensive than swapping between two tasklets.
Using Stackless Python also opened the door for implementing continuations. Continuations allow us to save the state of a task and restore it later to continue its job. Note that Stackless Python is not different from Standard Python; it just adds more functionalities. Everything available in Standard Python will be available in Stackless Python, too.
After discussing the benefits of PyPy, let’s talk about its limitations in the next section.
While you can use CPython on any machine and any CPU architecture, PyPy has comparably limited support.
Here are the CPU architectures supported and maintained by PyPy (source):
x86 (IA-32) and x86_64
ARM platforms (ARMv6 or ARMv7, with VFPv3)
AArch64
PowerPC 64bit, both little and big endian
System Z (s390x)
PyPy cannot work on all Linux distributions, so you have to take care to use one that’s supported. Running PyPy Linux binary on an unsupported distribution will return an error. PyPy only supports one version of Python 2 and Python 3, which are PyPy 2.7 and PyPy 3.6.
If the code that is executed in PyPy is pure Python, then the speed offered by PyPy is usually noticeable. But if the code contains C extensions, such as NumPy, then PyPy might actually increase the time. The PyPy project is actively developed and thus may offer better support for C extensions in the future.
PyPy is not supported by a number of popular Python frameworks, such as Kivy. Kivy allows CPython to run on all platforms, including Android and iOS. This means that PyPy cannot run on mobile devices.
Now that we’ve seen the benefits and limitations of PyPy, let’s cover how to run PyPy on Ubuntu.
You can run PyPy on either Mac, Linux, or Windows, but we are going to discuss running it on Ubuntu. It is very important to mention again that PyPy Linux binaries are only supported on specific Linux distributions. You can check the available PyPy binaries and their supported distributions on this page. For example, PyPy (either Python 2.7 or Python 3.6) is only supported for three versions of Ubuntu: 18.04, 16.04 and 14.04. If you have the newest version of Ubuntu up to this date (19.10), then you cannot run PyPy on it. Trying to run PyPy on an unsupported distribution will return this error:
pypy: error while loading shared libraries ...
I simply use a virtual machine to run Ubuntu 18.04.
The PyPy binaries come as compressed files. All you need to do is to decompress the file you downloaded. Inside the decompressed directory there is a folder named bin, in which the PyPy executable file can be found. I am using Python 3.6 and thus the file is named pypy3. For Python 2.7, it's just called pypy.
For CPython, if you would like to run Python 3 from the terminal, you simply enter the command python3. To run PyPy, simply issue the command pypy3.
Entering the pypy3 command in the terminal might return the Command 'pypy3' not found message, as shown in the next figure. The reason is that the path of PyPy is not added to the PATH environment variable. The command that actually works is ./pypy3, taking into regard that the current path of the terminal is inside the bin directory of PyPy. The dot . refers to the current directory, and / is added to access something within the current directory. Issuing the ./pypy3 command runs Python successfully as given below.
You can now work with Python as usual, taking advantage of the benefits of PyPy. For example, we can create a simple Python script that sums 1,000 numbers and execute it using PyPy. The code is as follows.
nums = range(1000) sum = 0 for k in nums: sum = sum + kprint("Sum of 1,000 numbers is : ", sum)
If this script is named test.py, then you can simply run it using the following command (assuming that the Python file is located inside the bin folder of PyPy, which is the same location of the pypy3 command).
./pypy3 test.py
The next figure shows the result of executing the previous code.
To compare the runtime of PyPy and CPython for summing 1,000 numbers, the code is changed to measure the time as follows.
import timet1 = time.time()nums = range(1000)sum = 0for k in nums: sum = sum + kprint("Sum of 1,000 numbers is : ", sum)t2 = time.time()t = t2 - t1print("Elapsed time is : ", t, " seconds")
For PyPy the time is nearly 0.00045 seconds, compared to 0.0002 seconds for CPython (I ran the code on my Core i7-6500U machine @ 2.5GHz). In this case CPython takes less time compared to PyPy, which is to be expected since this task is not really a long-running task. If the code is changed to add 1 million numbers, rather than 1 thousand, then PyPy would end up winning. In this case it takes 0.00035 seconds for Pypy and 0.1 seconds for CPython. The benefit of PyPy is now obvious. This should give you an idea of how much slower CPython is for executing long-running tasks.
This article was originally published on the Paperspace blog. You can run the code for my tutorials for free on Gradient.
This tutorial introduced PyPy, the fastest Python implementation. The major benefit of PyPy is its just-in-time (JIT) compilation, which offers caching of the compiled machine code to avoid executing it again. The limitations of PyPy are also highlighted, the major one being that it works well for pure Python code but is not efficient for C extensions.
We also saw how to run PyPy on Ubuntu and compared the runtime of both CPython and PyPy, highlighting PyPy’s efficiency for long-running tasks. Meanwhile, CPython might still beat out PyPy for short-running tasks. In future articles we’ll explore more comparisons between PyPy, CPython, and Cython. | [
{
"code": null,
"e": 365,
"s": 172,
"text": "The Python programming language is an interface that can be implemented in many ways. Some examples include CPython which uses the C language, Jython that is implemented using Java, and so on."
},
{
"code": null,
"e": 622,
"s": 365,
"text": "Despite being the most popular, CPython is not the fastest. PyPy is an alternate Python implementation that is both compliant and fast. PyPy depends on just-in-time (JIT) compilation that dramatically reduces the execution time for long-running operations."
},
{
"code": null,
"e": 925,
"s": 622,
"text": "In this tutorial, PyPy will be introduced for beginners to highlight how it is different from CPython. We’ll also cover its advantages and limitations. Then we’ll take a look at how to download and use PyPy to execute a simple Python script. PyPy supports hundreds of Python libraries, including NumPy."
},
{
"code": null,
"e": 975,
"s": 925,
"text": "Specifically, this tutorial covers the following:"
},
{
"code": null,
"e": 1003,
"s": 975,
"text": "A quick overview of CPython"
},
{
"code": null,
"e": 1041,
"s": 1003,
"text": "Introduction to PyPy and its features"
},
{
"code": null,
"e": 1058,
"s": 1041,
"text": "PyPy limitations"
},
{
"code": null,
"e": 1081,
"s": 1058,
"text": "Running PyPy on Ubuntu"
},
{
"code": null,
"e": 1115,
"s": 1081,
"text": "Execution time of PyPy vs CPython"
},
{
"code": null,
"e": 1134,
"s": 1115,
"text": "Let’s get started."
},
{
"code": null,
"e": 1493,
"s": 1134,
"text": "Before discussing PyPy, it is important to know how CPython works. My previous tutorial titled Boosting Python Scripts With Cython gave a longer introduction to how CPython works, but it won’t hurt to have a quick recap here about the important points. Below you can see a visualization of the execution pipeline of a Python script implemented using CPython."
},
{
"code": null,
"e": 1755,
"s": 1493,
"text": "Given a Python .py script, the source code is first compiled using the CPython compiler into bytecode. The bytecode is generated and saved in a file with a .pyc extension. The bytecode is then executed using the CPython interpreter within a virtual environment."
},
{
"code": null,
"e": 2696,
"s": 1755,
"text": "There are benefits to using the compiler to convert the source code into bytecode. If no compiler is used, then the interpreter will work directly on the source code by translating it line by line into machine code. The disadvantage of doing this is that some processes have to be applied for translating each line of source code into machine code, and such processes will be repeated for each line. For example, syntax analysis will be applied to each line independently from the other lines, and thus the interpreter takes a lot of time to translate the code. The compiler solves this issue as it is able to process all of the code at once, and thus syntax analysis will be applied only once rather than to each line of code. The generated bytecode from the compiler will thus be interpreted easily. Note that compiling the entire source code might not be helpful in some cases, and we’ll see a clear example of this when discussing PyPy."
},
{
"code": null,
"e": 2926,
"s": 2696,
"text": "After the bytecode is generated, it is executed by the interpreter running in the virtual machine. The virtual environment is beneficial, as it isolates the CPython bytecode from the machine, and thus makes Python cross-platform."
},
{
"code": null,
"e": 3314,
"s": 2926,
"text": "Unfortunately, just using a compiler to generate the bytecode is not enough to speed up the execution of CPython. The interpreter works by translating the code, each time it is executed, into machine code. Thus, if a line L takes X seconds to be executed, then executing it 10 times will have a cost of X*10 seconds. For long-running operations, this is too costly in its execution time."
},
{
"code": null,
"e": 3380,
"s": 3314,
"text": "Based on the drawbacks of CPython, let’s now take a look at PyPy."
},
{
"code": null,
"e": 3896,
"s": 3380,
"text": "PyPy is a Python implementation similar to CPython that is both compliant and fast. “Compliant” means that PyPy is compatible with CPython, as you can use nearly all CPython syntax in PyPy. There are some compatibility differences, as mentioned here. The most powerful advantage of PyPy is its speed. PyPy is much faster than CPython; we’ll see tests later on where PyPy performs about 7 times faster. In some cases it might even be tens or hundreds of times faster than CPython. So how does PyPy achieve its speed?"
},
{
"code": null,
"e": 4217,
"s": 3896,
"text": "PyPy uses a just-in-time (JIT) compiler that is able to dramatically increase the speed of Python scripts. The type of compilation used in CPython is ahead-of-time (AOT), meaning that all of the code will be translated into bytecode before being executed. JIT just translates the code at runtime, only when it is needed."
},
{
"code": null,
"e": 4653,
"s": 4217,
"text": "The source code might contain code blocks that are not executed at all, but which are still being translated using the AOT compiler. This leads to slower processing times. When the source code is large and contains thousands of lines, using a JIT makes a big difference. For AOT, the entire source code will be translated and thus take a lot of time. For JIT, just the needed parts of the code will be executed, making it a lot faster."
},
{
"code": null,
"e": 4919,
"s": 4653,
"text": "After PyPy translates a part of the code, it then gets cached. This means the code is translated only once, and then the translation is used later. The CPython interpreter repeats the translation each time the code is executed, an additional cause for its slowness."
},
{
"code": null,
"e": 5380,
"s": 4919,
"text": "PyPy is not the only way to boost the performance of Python scripts — but it is the easiest way. For example, Cython could be used to increase the speed of assigning C types to the variables. The problem is that Cython asks the developer to manually inspect the source code and optimize it. This is tiresome, and the complexity increases as the code size increases. When PyPy is used, you just run the regular Python code much faster without any effort at all."
},
{
"code": null,
"e": 5587,
"s": 5380,
"text": "Standard Python uses the C stack. This stack stores the sequence of functions that are called from each other (recursion). Because the stack size is limited, you are limited in the number of function calls."
},
{
"code": null,
"e": 5830,
"s": 5587,
"text": "PyPy uses Stackless Python, a Python implementation that does not use the C stack. Instead, it stores the function calls in the heap alongside the objects. The heap size is greater than the stack size, and thus you can do more function calls."
},
{
"code": null,
"e": 6059,
"s": 5830,
"text": "Stackless Python also supports microthreads, which are better than regular Python threads. Within the single Stackless Python thread you can run thousands of tasks, called “tasklets,” with all of them running on the same thread."
},
{
"code": null,
"e": 6396,
"s": 6059,
"text": "Using tasklets allows running concurrent tasks. Concurrency means that two tasks work simultaneously by sharing the same resources. One task runs for some time, then stops to make room for the second task to be executed. Note that this is different from parallelism, which involves running the two tasks separately but at the same time."
},
{
"code": null,
"e": 6651,
"s": 6396,
"text": "Using tasklets reduces the number of threads created, and thus reduces the overhead of managing all these threads by the OS. As a result, speeding up the execution by swapping between two threads is more time-intensive than swapping between two tasklets."
},
{
"code": null,
"e": 7005,
"s": 6651,
"text": "Using Stackless Python also opened the door for implementing continuations. Continuations allow us to save the state of a task and restore it later to continue its job. Note that Stackless Python is not different from Standard Python; it just adds more functionalities. Everything available in Standard Python will be available in Stackless Python, too."
},
{
"code": null,
"e": 7098,
"s": 7005,
"text": "After discussing the benefits of PyPy, let’s talk about its limitations in the next section."
},
{
"code": null,
"e": 7202,
"s": 7098,
"text": "While you can use CPython on any machine and any CPU architecture, PyPy has comparably limited support."
},
{
"code": null,
"e": 7276,
"s": 7202,
"text": "Here are the CPU architectures supported and maintained by PyPy (source):"
},
{
"code": null,
"e": 7299,
"s": 7276,
"text": "x86 (IA-32) and x86_64"
},
{
"code": null,
"e": 7342,
"s": 7299,
"text": "ARM platforms (ARMv6 or ARMv7, with VFPv3)"
},
{
"code": null,
"e": 7350,
"s": 7342,
"text": "AArch64"
},
{
"code": null,
"e": 7392,
"s": 7350,
"text": "PowerPC 64bit, both little and big endian"
},
{
"code": null,
"e": 7409,
"s": 7392,
"text": "System Z (s390x)"
},
{
"code": null,
"e": 7677,
"s": 7409,
"text": "PyPy cannot work on all Linux distributions, so you have to take care to use one that’s supported. Running PyPy Linux binary on an unsupported distribution will return an error. PyPy only supports one version of Python 2 and Python 3, which are PyPy 2.7 and PyPy 3.6."
},
{
"code": null,
"e": 7987,
"s": 7677,
"text": "If the code that is executed in PyPy is pure Python, then the speed offered by PyPy is usually noticeable. But if the code contains C extensions, such as NumPy, then PyPy might actually increase the time. The PyPy project is actively developed and thus may offer better support for C extensions in the future."
},
{
"code": null,
"e": 8188,
"s": 7987,
"text": "PyPy is not supported by a number of popular Python frameworks, such as Kivy. Kivy allows CPython to run on all platforms, including Android and iOS. This means that PyPy cannot run on mobile devices."
},
{
"code": null,
"e": 8285,
"s": 8188,
"text": "Now that we’ve seen the benefits and limitations of PyPy, let’s cover how to run PyPy on Ubuntu."
},
{
"code": null,
"e": 8887,
"s": 8285,
"text": "You can run PyPy on either Mac, Linux, or Windows, but we are going to discuss running it on Ubuntu. It is very important to mention again that PyPy Linux binaries are only supported on specific Linux distributions. You can check the available PyPy binaries and their supported distributions on this page. For example, PyPy (either Python 2.7 or Python 3.6) is only supported for three versions of Ubuntu: 18.04, 16.04 and 14.04. If you have the newest version of Ubuntu up to this date (19.10), then you cannot run PyPy on it. Trying to run PyPy on an unsupported distribution will return this error:"
},
{
"code": null,
"e": 8934,
"s": 8887,
"text": "pypy: error while loading shared libraries ..."
},
{
"code": null,
"e": 8986,
"s": 8934,
"text": "I simply use a virtual machine to run Ubuntu 18.04."
},
{
"code": null,
"e": 9297,
"s": 8986,
"text": "The PyPy binaries come as compressed files. All you need to do is to decompress the file you downloaded. Inside the decompressed directory there is a folder named bin, in which the PyPy executable file can be found. I am using Python 3.6 and thus the file is named pypy3. For Python 2.7, it's just called pypy."
},
{
"code": null,
"e": 9446,
"s": 9297,
"text": "For CPython, if you would like to run Python 3 from the terminal, you simply enter the command python3. To run PyPy, simply issue the command pypy3."
},
{
"code": null,
"e": 9968,
"s": 9446,
"text": "Entering the pypy3 command in the terminal might return the Command 'pypy3' not found message, as shown in the next figure. The reason is that the path of PyPy is not added to the PATH environment variable. The command that actually works is ./pypy3, taking into regard that the current path of the terminal is inside the bin directory of PyPy. The dot . refers to the current directory, and / is added to access something within the current directory. Issuing the ./pypy3 command runs Python successfully as given below."
},
{
"code": null,
"e": 10174,
"s": 9968,
"text": "You can now work with Python as usual, taking advantage of the benefits of PyPy. For example, we can create a simple Python script that sums 1,000 numbers and execute it using PyPy. The code is as follows."
},
{
"code": null,
"e": 10273,
"s": 10174,
"text": "nums = range(1000) sum = 0 for k in nums: sum = sum + kprint(\"Sum of 1,000 numbers is : \", sum)"
},
{
"code": null,
"e": 10484,
"s": 10273,
"text": "If this script is named test.py, then you can simply run it using the following command (assuming that the Python file is located inside the bin folder of PyPy, which is the same location of the pypy3 command)."
},
{
"code": null,
"e": 10500,
"s": 10484,
"text": "./pypy3 test.py"
},
{
"code": null,
"e": 10565,
"s": 10500,
"text": "The next figure shows the result of executing the previous code."
},
{
"code": null,
"e": 10687,
"s": 10565,
"text": "To compare the runtime of PyPy and CPython for summing 1,000 numbers, the code is changed to measure the time as follows."
},
{
"code": null,
"e": 10880,
"s": 10687,
"text": "import timet1 = time.time()nums = range(1000)sum = 0for k in nums: sum = sum + kprint(\"Sum of 1,000 numbers is : \", sum)t2 = time.time()t = t2 - t1print(\"Elapsed time is : \", t, \" seconds\")"
},
{
"code": null,
"e": 11459,
"s": 10880,
"text": "For PyPy the time is nearly 0.00045 seconds, compared to 0.0002 seconds for CPython (I ran the code on my Core i7-6500U machine @ 2.5GHz). In this case CPython takes less time compared to PyPy, which is to be expected since this task is not really a long-running task. If the code is changed to add 1 million numbers, rather than 1 thousand, then PyPy would end up winning. In this case it takes 0.00035 seconds for Pypy and 0.1 seconds for CPython. The benefit of PyPy is now obvious. This should give you an idea of how much slower CPython is for executing long-running tasks."
},
{
"code": null,
"e": 11581,
"s": 11459,
"text": "This article was originally published on the Paperspace blog. You can run the code for my tutorials for free on Gradient."
},
{
"code": null,
"e": 11936,
"s": 11581,
"text": "This tutorial introduced PyPy, the fastest Python implementation. The major benefit of PyPy is its just-in-time (JIT) compilation, which offers caching of the compiled machine code to avoid executing it again. The limitations of PyPy are also highlighted, the major one being that it works well for pure Python code but is not efficient for C extensions."
}
] |
Difference between Private and Protected in C++ with Example - GeeksforGeeks | 03 Jan, 2022
Protected
Protected access modifier is similar to that of private access modifiers, the difference is that the class member declared as Protected are inaccessible outside the class but they can be accessed by any subclass(derived class) of that class.Example:
CPP
// C++ program to demonstrate// protected access modifier #include <bits/stdc++.h>using namespace std; // base classclass Parent { // protected data membersprotected: int id_protected;}; // sub class or derived classclass Child : public Parent { public: void setId(int id) { // Child class is able to access the inherited // protected data members of the base class id_protected = id; } void displayId() { cout << "id_protected is: " << id_protected << endl; }}; // main functionint main(){ Child obj1; // member function of the derived class can // access the protected data members of the base class obj1.setId(81); obj1.displayId(); return 0;}
id_protected is: 81
Private
The class members declared as private can be accessed only by the functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of a class.Example:
CPP
// C++ program to demonstrate private// access modifier #include <iostream>using namespace std; class Circle { // private data memberprivate: double radius; // public member functionpublic: void compute_area(double r) { // member function can access private // data member radius radius = r; double area = 3.14 * radius * radius; cout << "Radius is: " << radius << endl; cout << "Area is: " << area; }}; // main functionint main(){ // creating object of the class Circle obj; // trying to access private data member // directly outside the class obj.compute_area(1.5); return 0;}
Radius is: 1.5
Area is: 7.065
Difference between Private and Protected
itskawal2000
access modifiers
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Map in C++ Standard Template Library (STL)
Bitwise Operators in C/C++
Socket Programming in C/C++
Operator Overloading in C++
Multidimensional Arrays in C / C++
Templates in C++ with Examples
vector erase() and clear() in C++
rand() and srand() in C/C++
unordered_map in C++ STL
Object Oriented Programming in C++ | [
{
"code": null,
"e": 23792,
"s": 23764,
"text": "\n03 Jan, 2022"
},
{
"code": null,
"e": 23802,
"s": 23792,
"text": "Protected"
},
{
"code": null,
"e": 24054,
"s": 23802,
"text": "Protected access modifier is similar to that of private access modifiers, the difference is that the class member declared as Protected are inaccessible outside the class but they can be accessed by any subclass(derived class) of that class.Example: "
},
{
"code": null,
"e": 24058,
"s": 24054,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate// protected access modifier #include <bits/stdc++.h>using namespace std; // base classclass Parent { // protected data membersprotected: int id_protected;}; // sub class or derived classclass Child : public Parent { public: void setId(int id) { // Child class is able to access the inherited // protected data members of the base class id_protected = id; } void displayId() { cout << \"id_protected is: \" << id_protected << endl; }}; // main functionint main(){ Child obj1; // member function of the derived class can // access the protected data members of the base class obj1.setId(81); obj1.displayId(); return 0;}",
"e": 24794,
"s": 24058,
"text": null
},
{
"code": null,
"e": 24814,
"s": 24794,
"text": "id_protected is: 81"
},
{
"code": null,
"e": 24824,
"s": 24816,
"text": "Private"
},
{
"code": null,
"e": 25126,
"s": 24824,
"text": "The class members declared as private can be accessed only by the functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of a class.Example: "
},
{
"code": null,
"e": 25130,
"s": 25126,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate private// access modifier #include <iostream>using namespace std; class Circle { // private data memberprivate: double radius; // public member functionpublic: void compute_area(double r) { // member function can access private // data member radius radius = r; double area = 3.14 * radius * radius; cout << \"Radius is: \" << radius << endl; cout << \"Area is: \" << area; }}; // main functionint main(){ // creating object of the class Circle obj; // trying to access private data member // directly outside the class obj.compute_area(1.5); return 0;}",
"e": 25794,
"s": 25130,
"text": null
},
{
"code": null,
"e": 25824,
"s": 25794,
"text": "Radius is: 1.5\nArea is: 7.065"
},
{
"code": null,
"e": 25867,
"s": 25826,
"text": "Difference between Private and Protected"
},
{
"code": null,
"e": 25880,
"s": 25867,
"text": "itskawal2000"
},
{
"code": null,
"e": 25897,
"s": 25880,
"text": "access modifiers"
},
{
"code": null,
"e": 25901,
"s": 25897,
"text": "C++"
},
{
"code": null,
"e": 25905,
"s": 25901,
"text": "CPP"
},
{
"code": null,
"e": 26003,
"s": 25905,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26012,
"s": 26003,
"text": "Comments"
},
{
"code": null,
"e": 26025,
"s": 26012,
"text": "Old Comments"
},
{
"code": null,
"e": 26068,
"s": 26025,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 26095,
"s": 26068,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 26123,
"s": 26095,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 26151,
"s": 26123,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 26186,
"s": 26151,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 26217,
"s": 26186,
"text": "Templates in C++ with Examples"
},
{
"code": null,
"e": 26251,
"s": 26217,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 26279,
"s": 26251,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 26304,
"s": 26279,
"text": "unordered_map in C++ STL"
}
] |
Should you learn Julia?. Is the high performing lovechild of... | by Alexander Bailey | Towards Data Science | Julia is the newest ‘it’ language of the moment, so I thought I’d give it a try. The question is, is it something worth adding to a data scientist's arsenal?
The first thing to know about Julia is that it was easy to download and use (on Mac anyway, good luck Windows users). It was also a breeze to install the kernel to allow it to work within Jupyter notebooks.
Julia isn’t an object-oriented language like Python, so to get writing we need to let go of some (but not all) of those tidy ‘Pythonic’ ways of doing things.
Classes don’t exist in Julia, so we have to make do with structures like we would with MATLAB. Again, like MATLAB, Julia adopts excellent syntax for linear algebra, which is built natively into the language. This replaces the need for modules like NumPy, in favour of more intuitive syntax like A*x , x' and ./ for multiplication, complex conjugate and pointwise division.
The other thing that users should be wary of, and have to get used to with Julia, is ending functions and loops with theend keyword. However, you’ll be pleased to hear that the reason for this is because Julia isn’t a whitespace sensitive language so you’ll never see an “inconsistent use of tabs and spaces in indentation” error again!
Julia is still technically a dynamically typed language, meaning that you don’t need to tell it which variable has which type — similar to how Python works.
However, Julia does support typing which can enforce a variable to be a specific type, unlike Python. This is pretty handy for two reasons:
It allows Julia code to run faster than a fully dynamic language, if a variable is typed then it doesn’t need to check what type it is before performing the calculation.Debugging is easier when dealing with typed variables, as variables can’t be accidentally assigned to a different type without you explicitly doing it. To get the same effect in Python you have to spend a lot of time implementing assert statements on each function input and even then, things can still go wrong!
It allows Julia code to run faster than a fully dynamic language, if a variable is typed then it doesn’t need to check what type it is before performing the calculation.
Debugging is easier when dealing with typed variables, as variables can’t be accidentally assigned to a different type without you explicitly doing it. To get the same effect in Python you have to spend a lot of time implementing assert statements on each function input and even then, things can still go wrong!
This is one of Julia’s niftiest features...
When implementing mathematical expressions in MATLAB or Python, we can often be met with variables like x_hat or sigma . However, in Julia, we can use the Unicode characters as variables instead of giving us x̂, and σ!
“Well how am I supposed to remember the keyboard combination for x̂and σ? I’m not googling it every time I want to use it!”
It’s a valid concern, but not to fear as the core developers of Julia are one step ahead of us. For x̂, just write x\hat ⇥ and forσ , write\sigma ⇥ , similar to how you would in LaTex.
Whilst the cynics may think this is a gimmicky feature, I think it allows for much more readable code and as the Zen of Python says, “Readability counts”.
In my last article, we implemented a logistic regression model from scratch but what does that look like in Julia?
function σ(x::Array{Float64,2}) return 1.0 ./ (1.0 .+ exp.(-x))endfunction fit( X::Array{Float64,2}, y::Array{Float64,1}, epochs::Int64=100, μ::Float64=0.0001 ) ε::Float64 = 0.00001 loss = [] X = vcat(X, ones(1,size(X)[end])) dims, n_data_points = size(X) w = randn(1,dims) for i in 1:epochs X̂ = w*X ŷ = σ(X̂) cost = -sum(y'.*log.(ŷ .+ ε) .+ (1 .- y').*log.(1 .- ŷ .+ ε)) dc_dw = -sum((y' .- ŷ).*X,dims=2)' w = w .- dc_dw * μ append!(loss,cost) end return w,lossendfunction predict(X::Array{Float64,2},w::Array{Float64,1}) X = vcat(X, ones(1,size(X)[end])) X̂ = w*X ŷ = σ(X̂) return ŷend
In this implementation, we can see a perfect example of how Julia’s Unicode characters can make code more readable. The native linear algebra support further simplifies the code by removing np. every time we want to perform multiplication or summation. We have also typed the function inputs to ensure that both the type and dimensionality of the inputs are valid.
Julia’s C based pedigree and typing allow for some pretty nice speed improvements over its sluggish Python parent. This can all be done without making any major improvements to the efficiency of the code.
Let’s calculate the first 10,000 prime numbers with this simple Python function:
def n_primes(n:int)->list: primes = [] i = 2 while len(primes) < n: prime_bool = True for j in range(2,i//2+1): if i%j == 0: prime_bool = False if prime_bool == True: primes.append(i) i += 1 return primes
Which takes 2 min 42s. Let’s compare that to Julia when we use typing:
function n_primes(n::Int64) primes = Int64[] i::Int64 = 2 while size(primes)[1] < n prime_bool::Bool = true for j = 2:i÷2 if i%j == 0 prime_bool = false end end if prime_bool == true append!(primes,i) end i += 1 end return primesend>> @time n_primes(10000)
This took just 7.55 seconds!
For the intrepid amongst us who want to deploy code in the wild, then compiling to a binary is a useful tool to have.
Python developers are no strangers with the issue of defining dependencies, and wrestling with pip to ensure all packages remain interoperable. Julia’s nifty solution to this is to compile to a single binary. Not only does this mean that deployment can be as simple as putting that binary in a Docker container and launching your service, but it also means that this comes with the same security improvements that come with using languages like Go.
Then don’t let Julia stop you, there is a Python interpreter built directly into Julia so using Python is as simple as using Pycall.
using Pycallpackagename = pyimport(“packagename”)
It really is as easy as that! Pycall allows the use of all built-in Python namespace functions and feature (even use context managers).
Debugging isn’t quite as easy as it is in Python; this could be that I’m just familiar with Python’s traceback errors, or that Python just has a more descriptive way of telling you where your mistake is.
Here’s a quick example to try and illustrate in Python:
... and in Julia:
I think one of these is a lot clearer than the other...
The only other issue with Julia is the lack of support for machine learning libraries. This may be a product of its relative youth, but it remains a frustrating feature. Julia has wrappers for Pandas, TensorFlow and Sklearn but this doesn’t help us if we want to grab a pre-trained ResNet 50 or a Bert model as the chances are they will be written in Python.
Having said that, the Julia community is growing and more native libraries are being built on an almost daily basis like Lathe and MLJ, so there’s hope for us yet!
The lack of class-based objects in Julia can also make using some of those libraries somewhat unwieldy when used outside of Python. For example Pandas’ df.loc[] becomesloc!(df, ).
Finally, there are too many functions in the basis namespace of Julia. In some ways, this is convenient and allows for a MATLAB-like level of usability and ease of writing code. However, it makes the readability of Julia code worse, with it often being hard to tell if a function is there by default, if it’s user-defined or if it’s been imported from another module.
I say yes! What’s the harm anyway? Writing production code in Julia is going to be tough at the moment given the lack of supported libraries available. But, Julia does offer easy to learn syntax, blazing fast code execution, a built-in Python interpreter and host of other potential improvements to a data scientist’s workflow. Given its growing popularity, there might just be a reason to switch over in the future or, maybe your next project has some pretty tough performance constraints? Julia might just be the answer. | [
{
"code": null,
"e": 330,
"s": 172,
"text": "Julia is the newest ‘it’ language of the moment, so I thought I’d give it a try. The question is, is it something worth adding to a data scientist's arsenal?"
},
{
"code": null,
"e": 537,
"s": 330,
"text": "The first thing to know about Julia is that it was easy to download and use (on Mac anyway, good luck Windows users). It was also a breeze to install the kernel to allow it to work within Jupyter notebooks."
},
{
"code": null,
"e": 695,
"s": 537,
"text": "Julia isn’t an object-oriented language like Python, so to get writing we need to let go of some (but not all) of those tidy ‘Pythonic’ ways of doing things."
},
{
"code": null,
"e": 1068,
"s": 695,
"text": "Classes don’t exist in Julia, so we have to make do with structures like we would with MATLAB. Again, like MATLAB, Julia adopts excellent syntax for linear algebra, which is built natively into the language. This replaces the need for modules like NumPy, in favour of more intuitive syntax like A*x , x' and ./ for multiplication, complex conjugate and pointwise division."
},
{
"code": null,
"e": 1405,
"s": 1068,
"text": "The other thing that users should be wary of, and have to get used to with Julia, is ending functions and loops with theend keyword. However, you’ll be pleased to hear that the reason for this is because Julia isn’t a whitespace sensitive language so you’ll never see an “inconsistent use of tabs and spaces in indentation” error again!"
},
{
"code": null,
"e": 1562,
"s": 1405,
"text": "Julia is still technically a dynamically typed language, meaning that you don’t need to tell it which variable has which type — similar to how Python works."
},
{
"code": null,
"e": 1702,
"s": 1562,
"text": "However, Julia does support typing which can enforce a variable to be a specific type, unlike Python. This is pretty handy for two reasons:"
},
{
"code": null,
"e": 2184,
"s": 1702,
"text": "It allows Julia code to run faster than a fully dynamic language, if a variable is typed then it doesn’t need to check what type it is before performing the calculation.Debugging is easier when dealing with typed variables, as variables can’t be accidentally assigned to a different type without you explicitly doing it. To get the same effect in Python you have to spend a lot of time implementing assert statements on each function input and even then, things can still go wrong!"
},
{
"code": null,
"e": 2354,
"s": 2184,
"text": "It allows Julia code to run faster than a fully dynamic language, if a variable is typed then it doesn’t need to check what type it is before performing the calculation."
},
{
"code": null,
"e": 2667,
"s": 2354,
"text": "Debugging is easier when dealing with typed variables, as variables can’t be accidentally assigned to a different type without you explicitly doing it. To get the same effect in Python you have to spend a lot of time implementing assert statements on each function input and even then, things can still go wrong!"
},
{
"code": null,
"e": 2711,
"s": 2667,
"text": "This is one of Julia’s niftiest features..."
},
{
"code": null,
"e": 2930,
"s": 2711,
"text": "When implementing mathematical expressions in MATLAB or Python, we can often be met with variables like x_hat or sigma . However, in Julia, we can use the Unicode characters as variables instead of giving us x̂, and σ!"
},
{
"code": null,
"e": 3054,
"s": 2930,
"text": "“Well how am I supposed to remember the keyboard combination for x̂and σ? I’m not googling it every time I want to use it!”"
},
{
"code": null,
"e": 3239,
"s": 3054,
"text": "It’s a valid concern, but not to fear as the core developers of Julia are one step ahead of us. For x̂, just write x\\hat ⇥ and forσ , write\\sigma ⇥ , similar to how you would in LaTex."
},
{
"code": null,
"e": 3394,
"s": 3239,
"text": "Whilst the cynics may think this is a gimmicky feature, I think it allows for much more readable code and as the Zen of Python says, “Readability counts”."
},
{
"code": null,
"e": 3509,
"s": 3394,
"text": "In my last article, we implemented a logistic regression model from scratch but what does that look like in Julia?"
},
{
"code": null,
"e": 4236,
"s": 3509,
"text": "function σ(x::Array{Float64,2}) return 1.0 ./ (1.0 .+ exp.(-x))endfunction fit( X::Array{Float64,2}, y::Array{Float64,1}, epochs::Int64=100, μ::Float64=0.0001 ) ε::Float64 = 0.00001 loss = [] X = vcat(X, ones(1,size(X)[end])) dims, n_data_points = size(X) w = randn(1,dims) for i in 1:epochs X̂ = w*X ŷ = σ(X̂) cost = -sum(y'.*log.(ŷ .+ ε) .+ (1 .- y').*log.(1 .- ŷ .+ ε)) dc_dw = -sum((y' .- ŷ).*X,dims=2)' w = w .- dc_dw * μ append!(loss,cost) end return w,lossendfunction predict(X::Array{Float64,2},w::Array{Float64,1}) X = vcat(X, ones(1,size(X)[end])) X̂ = w*X ŷ = σ(X̂) return ŷend"
},
{
"code": null,
"e": 4601,
"s": 4236,
"text": "In this implementation, we can see a perfect example of how Julia’s Unicode characters can make code more readable. The native linear algebra support further simplifies the code by removing np. every time we want to perform multiplication or summation. We have also typed the function inputs to ensure that both the type and dimensionality of the inputs are valid."
},
{
"code": null,
"e": 4806,
"s": 4601,
"text": "Julia’s C based pedigree and typing allow for some pretty nice speed improvements over its sluggish Python parent. This can all be done without making any major improvements to the efficiency of the code."
},
{
"code": null,
"e": 4887,
"s": 4806,
"text": "Let’s calculate the first 10,000 prime numbers with this simple Python function:"
},
{
"code": null,
"e": 5171,
"s": 4887,
"text": "def n_primes(n:int)->list: primes = [] i = 2 while len(primes) < n: prime_bool = True for j in range(2,i//2+1): if i%j == 0: prime_bool = False if prime_bool == True: primes.append(i) i += 1 return primes"
},
{
"code": null,
"e": 5242,
"s": 5171,
"text": "Which takes 2 min 42s. Let’s compare that to Julia when we use typing:"
},
{
"code": null,
"e": 5606,
"s": 5242,
"text": "function n_primes(n::Int64) primes = Int64[] i::Int64 = 2 while size(primes)[1] < n prime_bool::Bool = true for j = 2:i÷2 if i%j == 0 prime_bool = false end end if prime_bool == true append!(primes,i) end i += 1 end return primesend>> @time n_primes(10000)"
},
{
"code": null,
"e": 5635,
"s": 5606,
"text": "This took just 7.55 seconds!"
},
{
"code": null,
"e": 5753,
"s": 5635,
"text": "For the intrepid amongst us who want to deploy code in the wild, then compiling to a binary is a useful tool to have."
},
{
"code": null,
"e": 6202,
"s": 5753,
"text": "Python developers are no strangers with the issue of defining dependencies, and wrestling with pip to ensure all packages remain interoperable. Julia’s nifty solution to this is to compile to a single binary. Not only does this mean that deployment can be as simple as putting that binary in a Docker container and launching your service, but it also means that this comes with the same security improvements that come with using languages like Go."
},
{
"code": null,
"e": 6335,
"s": 6202,
"text": "Then don’t let Julia stop you, there is a Python interpreter built directly into Julia so using Python is as simple as using Pycall."
},
{
"code": null,
"e": 6385,
"s": 6335,
"text": "using Pycallpackagename = pyimport(“packagename”)"
},
{
"code": null,
"e": 6521,
"s": 6385,
"text": "It really is as easy as that! Pycall allows the use of all built-in Python namespace functions and feature (even use context managers)."
},
{
"code": null,
"e": 6725,
"s": 6521,
"text": "Debugging isn’t quite as easy as it is in Python; this could be that I’m just familiar with Python’s traceback errors, or that Python just has a more descriptive way of telling you where your mistake is."
},
{
"code": null,
"e": 6781,
"s": 6725,
"text": "Here’s a quick example to try and illustrate in Python:"
},
{
"code": null,
"e": 6799,
"s": 6781,
"text": "... and in Julia:"
},
{
"code": null,
"e": 6855,
"s": 6799,
"text": "I think one of these is a lot clearer than the other..."
},
{
"code": null,
"e": 7214,
"s": 6855,
"text": "The only other issue with Julia is the lack of support for machine learning libraries. This may be a product of its relative youth, but it remains a frustrating feature. Julia has wrappers for Pandas, TensorFlow and Sklearn but this doesn’t help us if we want to grab a pre-trained ResNet 50 or a Bert model as the chances are they will be written in Python."
},
{
"code": null,
"e": 7378,
"s": 7214,
"text": "Having said that, the Julia community is growing and more native libraries are being built on an almost daily basis like Lathe and MLJ, so there’s hope for us yet!"
},
{
"code": null,
"e": 7558,
"s": 7378,
"text": "The lack of class-based objects in Julia can also make using some of those libraries somewhat unwieldy when used outside of Python. For example Pandas’ df.loc[] becomesloc!(df, )."
},
{
"code": null,
"e": 7926,
"s": 7558,
"text": "Finally, there are too many functions in the basis namespace of Julia. In some ways, this is convenient and allows for a MATLAB-like level of usability and ease of writing code. However, it makes the readability of Julia code worse, with it often being hard to tell if a function is there by default, if it’s user-defined or if it’s been imported from another module."
}
] |
How to multiply only one column in an R data frame with a number? | To multiply only one column with a number, we can simply use the multiplication operator * but need to replace the original column with the new values. For example, if we have a data frame called df that contains three columns x1, x2, and x3, and we want to multiply the second column x2 with 2 then it can be done as dfx2<−dfx2*2.
Live Demo
Consider the below data frame −
set.seed(212)
x1<−rpois(20,2)
x2<−rpois(20,5)
x3<−rpois(20,2)
df1<−data.frame(x1,x2,x3)
df1
x1 x2 x3
1 1 5 3
2 3 5 1
3 3 6 4
4 1 0 2
5 0 3 1
6 0 7 4
7 4 10 4
8 4 8 3
9 1 7 0
10 2 2 0
11 2 1 1
12 2 7 1
13 3 2 1
14 1 3 3
15 1 3 2
16 3 5 2
17 3 2 1
18 1 4 1
19 2 5 2
20 4 6 2
Replacing the column x2 by multiplying the values in it with 2 −
df1$x2<−df1$x2*2
df1
x1 x2 x3
1 1 10 3
2 3 10 1
3 3 12 4
4 1 0 2
5 0 6 1
6 0 14 4
7 4 20 4
8 4 16 3
9 1 14 0
10 2 4 0
11 2 2 1
12 2 14 1
13 3 4 1
14 1 6 3
15 1 6 2
16 3 10 2
17 3 4 1
18 1 8 1
19 2 10 2
20 4 12 2
Live Demo
y1<−rnorm(20)
y2<−rnorm(20)
y3<−rnorm(20)
y4<−rnorm(20)
df2<−data.frame(y1,y2,y3,y4)
df2
y1 y2 y3 y4
1 0.17051839 −1.07371818 0.717652086 −0.6692174
2 0.26654381 −0.82881794 1.144774784 1.0708255
3 1.17587680 −0.03197159 −0.257318856 −0.2734330
4 0.79978274 1.14677652 −1.052941918 0.8212265
5 0.36352605 0.95455643 0.002662389 0.8991729
6 −0.52918622 −1.19824723 1.121770768 −0.1345990
7 −1.30278723 0.90339625 −1.637918585 −0.3986243
8 −2.01380274 −0.61700004 1.319289169 1.4223520
9 −0.10499300 −0.99640769 1.508072921 −0.8711021
10 −0.57019817 0.23396114 0.371342290 −0.5071846
11 −0.92964644 −2.82593133 −0.191162636 0.2482026
12 −0.62824719 1.39458991 −0.250602510 −0.5094344
13 −1.16899182 0.48402510 0.849597620 0.5386604
14 −0.12800221 −1.01570468 −1.370769300 0.3641254
15 1.60649960 1.00993852 −0.181644717 0.7057080
16 −0.09581029 −0.40099838 0.392519844 −1.6369244
17 −0.43375271 −0.29316467 −0.233208374 0.1270293
18 −0.96182839 0.54334525 1.550101688 2.0853380
19 −1.50775746 −0.89573880 0.366389303 0.3372866
20 1.90255916 −1.41836692 0.428073142 −0.1576013
Replacing the column y1 by multiplying the values in it with *1 −
df2$y1<−df2$y1*(−1)
df2
y1 y2 y3 y4
1 −0.17051839 −1.07371818 0.717652086 −0.6692174
2 −0.26654381 −0.82881794 1.144774784 1.0708255
3 −1.17587680 −0.03197159 −0.257318856 −0.2734330
4 −0.79978274 1.14677652 −1.052941918 0.8212265
5 −0.36352605 0.95455643 0.002662389 0.8991729
6 0.52918622 −1.19824723 1.121770768 −0.1345990
7 1.30278723 0.90339625 −1.637918585 −0.3986243
8 2.01380274 −0.61700004 1.319289169 1.4223520
9 0.10499300 −0.99640769 1.508072921 −0.8711021
10 0.57019817 0.23396114 0.371342290 −0.5071846
11 0.92964644 −2.82593133 −0.191162636 0.2482026
12 0.62824719 1.39458991 −0.250602510 −0.5094344
13 1.16899182 0.48402510 0.849597620 0.5386604
14 0.12800221 −1.01570468 −1.370769300 0.3641254
15 −1.60649960 1.00993852 −0.181644717 0.7057080
16 0.09581029 −0.40099838 0.392519844 −1.6369244
17 0.43375271 −0.29316467 −0.233208374 0.1270293
18 0.96182839 0.54334525 1.550101688 2.0853380
19 1.50775746 −0.89573880 0.366389303 0.3372866
20 −1.90255916 −1.41836692 0.428073142 −0.1576013 | [
{
"code": null,
"e": 1394,
"s": 1062,
"text": "To multiply only one column with a number, we can simply use the multiplication operator * but need to replace the original column with the new values. For example, if we have a data frame called df that contains three columns x1, x2, and x3, and we want to multiply the second column x2 with 2 then it can be done as dfx2<−dfx2*2."
},
{
"code": null,
"e": 1405,
"s": 1394,
"text": " Live Demo"
},
{
"code": null,
"e": 1437,
"s": 1405,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1529,
"s": 1437,
"text": "set.seed(212)\nx1<−rpois(20,2)\nx2<−rpois(20,5)\nx3<−rpois(20,2)\ndf1<−data.frame(x1,x2,x3)\ndf1"
},
{
"code": null,
"e": 1710,
"s": 1529,
"text": "x1 x2 x3\n1 1 5 3\n2 3 5 1\n3 3 6 4\n4 1 0 2\n5 0 3 1\n6 0 7 4\n7 4 10 4\n8 4 8 3\n9 1 7 0\n10 2 2 0\n11 2 1 1\n12 2 7 1\n13 3 2 1\n14 1 3 3\n15 1 3 2\n16 3 5 2\n17 3 2 1\n18 1 4 1\n19 2 5 2\n20 4 6 2"
},
{
"code": null,
"e": 1775,
"s": 1710,
"text": "Replacing the column x2 by multiplying the values in it with 2 −"
},
{
"code": null,
"e": 1796,
"s": 1775,
"text": "df1$x2<−df1$x2*2\ndf1"
},
{
"code": null,
"e": 1987,
"s": 1796,
"text": "x1 x2 x3\n1 1 10 3\n2 3 10 1\n3 3 12 4\n4 1 0 2\n5 0 6 1\n6 0 14 4\n7 4 20 4\n8 4 16 3\n9 1 14 0\n10 2 4 0\n11 2 2 1\n12 2 14 1\n13 3 4 1\n14 1 6 3\n15 1 6 2\n16 3 10 2\n17 3 4 1\n18 1 8 1\n19 2 10 2\n20 4 12 2"
},
{
"code": null,
"e": 1998,
"s": 1987,
"text": " Live Demo"
},
{
"code": null,
"e": 2087,
"s": 1998,
"text": "y1<−rnorm(20)\ny2<−rnorm(20)\ny3<−rnorm(20)\ny4<−rnorm(20)\ndf2<−data.frame(y1,y2,y3,y4)\ndf2"
},
{
"code": null,
"e": 3072,
"s": 2087,
"text": "y1 y2 y3 y4\n1 0.17051839 −1.07371818 0.717652086 −0.6692174\n2 0.26654381 −0.82881794 1.144774784 1.0708255\n3 1.17587680 −0.03197159 −0.257318856 −0.2734330\n4 0.79978274 1.14677652 −1.052941918 0.8212265\n5 0.36352605 0.95455643 0.002662389 0.8991729\n6 −0.52918622 −1.19824723 1.121770768 −0.1345990\n7 −1.30278723 0.90339625 −1.637918585 −0.3986243\n8 −2.01380274 −0.61700004 1.319289169 1.4223520\n9 −0.10499300 −0.99640769 1.508072921 −0.8711021\n10 −0.57019817 0.23396114 0.371342290 −0.5071846\n11 −0.92964644 −2.82593133 −0.191162636 0.2482026\n12 −0.62824719 1.39458991 −0.250602510 −0.5094344\n13 −1.16899182 0.48402510 0.849597620 0.5386604\n14 −0.12800221 −1.01570468 −1.370769300 0.3641254\n15 1.60649960 1.00993852 −0.181644717 0.7057080\n16 −0.09581029 −0.40099838 0.392519844 −1.6369244\n17 −0.43375271 −0.29316467 −0.233208374 0.1270293\n18 −0.96182839 0.54334525 1.550101688 2.0853380\n19 −1.50775746 −0.89573880 0.366389303 0.3372866\n20 1.90255916 −1.41836692 0.428073142 −0.1576013"
},
{
"code": null,
"e": 3138,
"s": 3072,
"text": "Replacing the column y1 by multiplying the values in it with *1 −"
},
{
"code": null,
"e": 3162,
"s": 3138,
"text": "df2$y1<−df2$y1*(−1)\ndf2"
},
{
"code": null,
"e": 4141,
"s": 3162,
"text": "y1 y2 y3 y4\n1 −0.17051839 −1.07371818 0.717652086 −0.6692174\n2 −0.26654381 −0.82881794 1.144774784 1.0708255\n3 −1.17587680 −0.03197159 −0.257318856 −0.2734330\n4 −0.79978274 1.14677652 −1.052941918 0.8212265\n5 −0.36352605 0.95455643 0.002662389 0.8991729\n6 0.52918622 −1.19824723 1.121770768 −0.1345990\n7 1.30278723 0.90339625 −1.637918585 −0.3986243\n8 2.01380274 −0.61700004 1.319289169 1.4223520\n9 0.10499300 −0.99640769 1.508072921 −0.8711021\n10 0.57019817 0.23396114 0.371342290 −0.5071846\n11 0.92964644 −2.82593133 −0.191162636 0.2482026\n12 0.62824719 1.39458991 −0.250602510 −0.5094344\n13 1.16899182 0.48402510 0.849597620 0.5386604\n14 0.12800221 −1.01570468 −1.370769300 0.3641254\n15 −1.60649960 1.00993852 −0.181644717 0.7057080\n16 0.09581029 −0.40099838 0.392519844 −1.6369244\n17 0.43375271 −0.29316467 −0.233208374 0.1270293\n18 0.96182839 0.54334525 1.550101688 2.0853380\n19 1.50775746 −0.89573880 0.366389303 0.3372866\n20 −1.90255916 −1.41836692 0.428073142 −0.1576013"
}
] |
C# Program to make a copy of an existing file | Use File.Copy method to make copy of an existing file.
Add the path of the file you want to copy.
String myPath = @"D:\one.txt";
Now copy the above file to the following file −
String myPath = @"D:\one.txt";
Use the File.Copy method with both the source and destination file.
File.Copy(myPath,newpath);
using System;
using System.IO;
public class Program {
public static void Main() {
String myPath = @"D:\one.txt";
// the file will get copied here
String newpath = @"D:\two.txt";
// copying file
File.Copy(myPath,newpath);
}
} | [
{
"code": null,
"e": 1117,
"s": 1062,
"text": "Use File.Copy method to make copy of an existing file."
},
{
"code": null,
"e": 1160,
"s": 1117,
"text": "Add the path of the file you want to copy."
},
{
"code": null,
"e": 1191,
"s": 1160,
"text": "String myPath = @\"D:\\one.txt\";"
},
{
"code": null,
"e": 1239,
"s": 1191,
"text": "Now copy the above file to the following file −"
},
{
"code": null,
"e": 1270,
"s": 1239,
"text": "String myPath = @\"D:\\one.txt\";"
},
{
"code": null,
"e": 1338,
"s": 1270,
"text": "Use the File.Copy method with both the source and destination file."
},
{
"code": null,
"e": 1365,
"s": 1338,
"text": "File.Copy(myPath,newpath);"
},
{
"code": null,
"e": 1626,
"s": 1365,
"text": "using System;\nusing System.IO;\npublic class Program {\n public static void Main() {\n String myPath = @\"D:\\one.txt\";\n // the file will get copied here\n String newpath = @\"D:\\two.txt\";\n // copying file\n File.Copy(myPath,newpath);\n }\n}"
}
] |
Descriptive Statistics: Expectations vs. Reality (Exploratory Data Analysis) | by Gonçalo Guimarães Gomes | Towards Data Science | An easy descriptive statistics approach to summarize the numeric and categoric data variables through the Measures of Central Tendency and Measures of Spread for every Exploratory Data Analysis process.
EDA is the first step in the data analysis process. It allows us to understand the data we are dealing with by describing and summarizing the dataset’s main characteristics, often through visual methods like bar and pie charts, histograms, boxplots, scatterplots, heatmaps, and many more.
Maximize insight into a dataset (be able to listen to your data)
Uncover underlying structure/patterns
Detect outliers and anomalies
Extract and select important variables
Increase computational effenciency
Test underlying assumptions (e.g. business intuiton)
Moreover, to be capable of exploring and explain the dataset’s features with all its attributes getting insights and efficient numeric summaries of the data, we need help from Descriptive Statistics.
Statistics is divided into two major areas:
Descriptive statistics: describe and summarize data;
Inferential statistics: methods for using sample data to make general conclusions (inferences) about populations.
This tutorial focuses on descriptive statistics of both numerical and categorical variables and is divided into two parts:
Measures of central tendency;
Measures of spread.
Also named Univariate Analysis (one feature analysis at a time), descriptive statistics, in short, help describe and understand the features of a specific dataset, by giving short numeric summaries about the sample and measures of the data.
Descriptive statistics are mere exploration as they do not allows us to make conclusions beyond the data we have analysed or reach conclusions regarding any hypotheses we might have made.
Numerical and categorical variables, as we will see shortly, have different descriptive statistics approaches.
Let’s review the type of variables:
Numerical continuous: The values are not countable and have an infinite number of possibilities (Someone’s age: 25 years, 4 days, 11 hours, 24 minutes, 5 seconds and so on to the infinite).
Numerical discrete: The values are countable and have an finite number of possibilities (It is impossible to count 27.52 countries in the EU).
Categorical ordinal: There is an order implied in the levels (January comes always before February and after December).
Categorical nominal: There is no order implied in the levels (Female/male, or the wind direction: north, south, east, west).
Measures of central tendency: Mean, median
Measures of spread: Standard deviation, variance, percentiles, maximum, minimum, skewness, kurtosis
Others: Size, unique, number of uniques
One approach to display the data is through a boxplot. It gives you the 5-basic-stats, such as the minimum, the 1st quartile (25th percentile), the median, the 3rd quartile (75th percentile), and the maximum.
Measures of central tendency: Mode (most common)
Measures of spread: Number of uniques
Others: Size, % Highest unique
Understanding:
Mean (average): The total sum of values divided by the total observations. The mean is highly sensitive to the outliers.
Median (center value): The total count of an ordered sequence of numbers divided by 2. The median is not affected by the outliers.
Mode (most common): The values most frequently observed. There can be more than one modal value in the same variable.
Variance (variability from the mean): The square of the standard deviation. It is also affected by outliers.
Standard deviation (concentrated around the mean): The standard amount of deviation (distance) from the mean. The std is affected by the outliers. It is the square root of the variance.
Percentiles: The value below which a percentage of data falls. The 0th percentile is the minimum value, the 100th is the maximum, the 50th is the median.
Minimum: The smallest or lowest value.
Maximum: The greatest or highest value.
The number of uniques (total distinct): The total amount of distinct observations.
Uniques (distinct): The distinct values or groups of values observed.
Skewness (symmetric): How much a distribution derives from the normal distribution. >> Explained Skew concept in the next section.
Kurtosis (volume of outliers): How long are the tails and how sharp is the peak of the distribution.>> Explained Kurtosis concept in the next section.
Count (size): The total sum of observations. Counting is also necessary for calculating the mean, median, and mode.
% highest unique (relativity): The proportion of the highest unique observation regarding all the unique values or group of values.
In a perfect world, the data’s distribution assumes the form of a bell curve (Gaussian or normally distributed), but in the real world, data distributions usually are not symmetric (= skewed).
Therefore, the skewness indicates how much our distribution derives from the normal distribution (with the skewness value of zero or very close).
There are three generic types of distributions:
Symmetrical [median = mean]: In a normal distribution, the mean (average) divides the data symmetrically at the median value or close.
Positive skew [median < mean]: The distribution is asymmetrical, the tail is skewed/longer towards the right-hand side of the curve. In this type, the majority of the observations are concentrated on the left tail, and the value of skewness is positive.
Negative skew [median > mean]: The distribution is asymmetrical and the tail is skewed/longer towards the left-hand side of the curve. In this type of distribution, the majority of the observations are concentrated on the right tail, and the value of skewness is negative.
Rule of thumbs:
Symmetric distribution: values between -0.5 to 0.5.
Moderate skew: values between -1 and -0.5 and 0.5 and 1.
High skew: values <-1 or >1.
kurtosis is another useful tool when it comes to quantify the shape of a distribution. It measures both how long are the tails, but most important, and how sharp is the peak of the distributions.
If the distribution has a sharper and taller peak and shorter tails, then it has a higher kurtosis while a low kurtosis can be observed when the peak of the distribution is flatter with thinner tails. There are three types of kurtosis:
Leptokurtic: The distribution is tall and thin. The value of a leptokurtic must be > 3.
Mesokurtic: This distribution looks the same or very similar to a normal distribution. The value of a “normal” mesokurtic is = 3.
Platykurtic: The distributions have a flatter and wider peak and thinner tails, meaning that the data is moderately spread out. The value of a platykurtic must be < 3.
Kurtosis is calculated by raising the average of the standardized data to the fourth power. If we raise any standardized number (less than 1) to the 4th power, the result would be a very small number, somewhere close to zero. Such a small value would not contribute much to the kurtosis. The conclusion is that the values that would make a difference to the kurtosis would be the ones far away from the region of the peak, put it in other words, the outliers.
In this section, we will be giving short numeric stats summaries concerning the different measures of central tendency and dispersion of the dataset.
let’s work on some practical examples through a descriptive statistics environment in Pandas.
> Repo code here.
Start by importing the required libraries:
import pandas as pdimport numpy as npimport scipyimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inline
Load the dataset:df = pd.read_csv("sample.csv", sep=";")
Print the data:df.head()
Before any stats calculus, let’s just take a quick look at the data:df.info
The dataset consists of 310 observations and 2 columns. One of the attributes is numerical, and the other categorical. Both columns have no missing values.
The numerical variable we are going to analyze is age. First step is to visually observe the variable. So let's plot an histogram and a boxplot.
plt.hist(df.age, bins=20)plt.xlabel(“Age”)plt.ylabel(“Absolute Frequency”)plt.show()
sns.boxplot(x=age, data=df, orient="h").set(xlabel="Age", title="Numeric variable 'Age'");
It is also possible to visually observe the variable with both a histogram and a boxplot combined. I find it a useful graphical combination and use it a lot in my reports.
age = df.agef, (ax_box, ax_hist) = plt.subplots(2, sharex=True, gridspec_kw= {"height_ratios": (0.8, 1.2)})mean=np.array(age).mean()median=np.median(age)sns.boxplot(age, ax=ax_box)ax_box.axvline(mean, color='r', linestyle='--')ax_box.axvline(median, color='g', linestyle='-')sns.distplot(age, ax=ax_hist)ax_hist.axvline(mean, color='r', linestyle='--')ax_hist.axvline(median, color='g', linestyle='-')plt.legend({'Mean':mean,'Median':median})plt.title("'Age' histogram + boxplot")ax_box.set(xlabel='')plt.show()
1. Mean:df.age.mean()
35.564516129032256
2. Median:df.age.median()
32.0
3. Standard deviation:df.age.std()
18.824363618000913
4. Variance:df.age.var()
354.3566656227164
5. a) Percentiles 25%:df.age.quantile(0.25)
23.0
b) Percentile 75%:df.age.quantile(0.75)
45.0
c) In one go:df.age.quantile(q=[.25, .75)
0.25 23.00.75 45.0Name: age, dtype: float64
6. Minimum and maximum:df.age.min(), df.age.max()
(3, 98)
7. Skewness (with scipy):scipy.stats.skew(df.age)
0.9085582496839909
8. Kurtosis (with scipy):scipy.stats.kurtosis(df.age)
0.7254158742250474
9. Size (number of rows):df.age.count()
310
10. Number of uniques (total distinct)df.age.nunique()
74
11. Uniques (distinct):df.age.unique()
array([46, 22, 54, 33, 69, 35, 11, 97, 50, 34, 67, 43, 21, 12, 23, 45, 89, 76, 5, 55, 65, 24, 27, 57, 38, 28, 36, 60, 56, 53, 26, 25, 42, 83, 16, 51, 90, 10, 70, 44, 20, 31, 47, 30, 91, 7, 6, 41, 66, 61, 96, 32, 58, 17, 52, 29, 75, 86, 98, 48, 40, 13, 4, 68, 62, 9, 18, 39, 15, 19, 8, 71, 3, 37])
The categorical variable we are going to analyze is city. Let’s plot a bar chart and get a visual observation of the variable.
df.city.value_counts().plot.bar()plt.xlabel("City")plt.ylabel("Absolute Frequency")plt.title("Categoric variable 'City'")plt.show()
1. Mode:df.city.mode()[0]
'Paris'
2. Number of uniques:df.city.nunique()
6
3. Uniques (distinct):df.city.unique()
array(['Lisbon', 'Paris', 'Madrid', 'London', 'Luxembourg', 'Berlin'], dtype=object)
4. Most frequent unique (value count):df.city.value_counts().head(1)
Paris 67Name: city, dtype: int64
5. Size (number of rows):df.city.count()
310
6. % of the highest unique (fraction of the most common unique in regards to all the others):p = df.city.value_counts(normalize=True)[0] print(f"{p:.1%}")
21.6%
The describe() method shows the descriptive statistics gathered in one table. By default, stats for numeric data. The result is represented as a pandas dataframe.df.describe()
Adding other non-standard values, for instance, the ‘variance’.describe_var = data.describe()describe_var.append(pd.Series(data.var(), name='variance'))
Displaying categorical data.df.describe(include=["O"])<=> df.describe(exclude=['float64','int64'])<=> df.describe(include=[np.object])
By passing the parameter include='all', displays both numeric and categoric variables at once.df.describe(include='all')
These are the basics of descriptive statistics when developing an exploratory data analysis project with the help of Pandas, Numpy, Scipy, Matplolib and/or Seaborn. When well performed, these stats help us to understand and transform the data for further processing.
Remember always be a skeptic. Look at the data with your own eyes (don’t fully rely on statistics), and graphically visualize the variables (use and abuse of the visuals).
> Repo code here.
Check out other articles you might also like to read:
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
Linkedin
Twitter
Medium
GitHub
Kaggle
Email
Good readings, great codings! | [
{
"code": null,
"e": 374,
"s": 171,
"text": "An easy descriptive statistics approach to summarize the numeric and categoric data variables through the Measures of Central Tendency and Measures of Spread for every Exploratory Data Analysis process."
},
{
"code": null,
"e": 663,
"s": 374,
"text": "EDA is the first step in the data analysis process. It allows us to understand the data we are dealing with by describing and summarizing the dataset’s main characteristics, often through visual methods like bar and pie charts, histograms, boxplots, scatterplots, heatmaps, and many more."
},
{
"code": null,
"e": 728,
"s": 663,
"text": "Maximize insight into a dataset (be able to listen to your data)"
},
{
"code": null,
"e": 766,
"s": 728,
"text": "Uncover underlying structure/patterns"
},
{
"code": null,
"e": 796,
"s": 766,
"text": "Detect outliers and anomalies"
},
{
"code": null,
"e": 835,
"s": 796,
"text": "Extract and select important variables"
},
{
"code": null,
"e": 870,
"s": 835,
"text": "Increase computational effenciency"
},
{
"code": null,
"e": 923,
"s": 870,
"text": "Test underlying assumptions (e.g. business intuiton)"
},
{
"code": null,
"e": 1123,
"s": 923,
"text": "Moreover, to be capable of exploring and explain the dataset’s features with all its attributes getting insights and efficient numeric summaries of the data, we need help from Descriptive Statistics."
},
{
"code": null,
"e": 1167,
"s": 1123,
"text": "Statistics is divided into two major areas:"
},
{
"code": null,
"e": 1220,
"s": 1167,
"text": "Descriptive statistics: describe and summarize data;"
},
{
"code": null,
"e": 1334,
"s": 1220,
"text": "Inferential statistics: methods for using sample data to make general conclusions (inferences) about populations."
},
{
"code": null,
"e": 1457,
"s": 1334,
"text": "This tutorial focuses on descriptive statistics of both numerical and categorical variables and is divided into two parts:"
},
{
"code": null,
"e": 1487,
"s": 1457,
"text": "Measures of central tendency;"
},
{
"code": null,
"e": 1507,
"s": 1487,
"text": "Measures of spread."
},
{
"code": null,
"e": 1748,
"s": 1507,
"text": "Also named Univariate Analysis (one feature analysis at a time), descriptive statistics, in short, help describe and understand the features of a specific dataset, by giving short numeric summaries about the sample and measures of the data."
},
{
"code": null,
"e": 1936,
"s": 1748,
"text": "Descriptive statistics are mere exploration as they do not allows us to make conclusions beyond the data we have analysed or reach conclusions regarding any hypotheses we might have made."
},
{
"code": null,
"e": 2047,
"s": 1936,
"text": "Numerical and categorical variables, as we will see shortly, have different descriptive statistics approaches."
},
{
"code": null,
"e": 2083,
"s": 2047,
"text": "Let’s review the type of variables:"
},
{
"code": null,
"e": 2273,
"s": 2083,
"text": "Numerical continuous: The values are not countable and have an infinite number of possibilities (Someone’s age: 25 years, 4 days, 11 hours, 24 minutes, 5 seconds and so on to the infinite)."
},
{
"code": null,
"e": 2416,
"s": 2273,
"text": "Numerical discrete: The values are countable and have an finite number of possibilities (It is impossible to count 27.52 countries in the EU)."
},
{
"code": null,
"e": 2536,
"s": 2416,
"text": "Categorical ordinal: There is an order implied in the levels (January comes always before February and after December)."
},
{
"code": null,
"e": 2661,
"s": 2536,
"text": "Categorical nominal: There is no order implied in the levels (Female/male, or the wind direction: north, south, east, west)."
},
{
"code": null,
"e": 2704,
"s": 2661,
"text": "Measures of central tendency: Mean, median"
},
{
"code": null,
"e": 2804,
"s": 2704,
"text": "Measures of spread: Standard deviation, variance, percentiles, maximum, minimum, skewness, kurtosis"
},
{
"code": null,
"e": 2844,
"s": 2804,
"text": "Others: Size, unique, number of uniques"
},
{
"code": null,
"e": 3053,
"s": 2844,
"text": "One approach to display the data is through a boxplot. It gives you the 5-basic-stats, such as the minimum, the 1st quartile (25th percentile), the median, the 3rd quartile (75th percentile), and the maximum."
},
{
"code": null,
"e": 3102,
"s": 3053,
"text": "Measures of central tendency: Mode (most common)"
},
{
"code": null,
"e": 3140,
"s": 3102,
"text": "Measures of spread: Number of uniques"
},
{
"code": null,
"e": 3171,
"s": 3140,
"text": "Others: Size, % Highest unique"
},
{
"code": null,
"e": 3186,
"s": 3171,
"text": "Understanding:"
},
{
"code": null,
"e": 3307,
"s": 3186,
"text": "Mean (average): The total sum of values divided by the total observations. The mean is highly sensitive to the outliers."
},
{
"code": null,
"e": 3438,
"s": 3307,
"text": "Median (center value): The total count of an ordered sequence of numbers divided by 2. The median is not affected by the outliers."
},
{
"code": null,
"e": 3556,
"s": 3438,
"text": "Mode (most common): The values most frequently observed. There can be more than one modal value in the same variable."
},
{
"code": null,
"e": 3665,
"s": 3556,
"text": "Variance (variability from the mean): The square of the standard deviation. It is also affected by outliers."
},
{
"code": null,
"e": 3851,
"s": 3665,
"text": "Standard deviation (concentrated around the mean): The standard amount of deviation (distance) from the mean. The std is affected by the outliers. It is the square root of the variance."
},
{
"code": null,
"e": 4005,
"s": 3851,
"text": "Percentiles: The value below which a percentage of data falls. The 0th percentile is the minimum value, the 100th is the maximum, the 50th is the median."
},
{
"code": null,
"e": 4044,
"s": 4005,
"text": "Minimum: The smallest or lowest value."
},
{
"code": null,
"e": 4084,
"s": 4044,
"text": "Maximum: The greatest or highest value."
},
{
"code": null,
"e": 4167,
"s": 4084,
"text": "The number of uniques (total distinct): The total amount of distinct observations."
},
{
"code": null,
"e": 4237,
"s": 4167,
"text": "Uniques (distinct): The distinct values or groups of values observed."
},
{
"code": null,
"e": 4368,
"s": 4237,
"text": "Skewness (symmetric): How much a distribution derives from the normal distribution. >> Explained Skew concept in the next section."
},
{
"code": null,
"e": 4519,
"s": 4368,
"text": "Kurtosis (volume of outliers): How long are the tails and how sharp is the peak of the distribution.>> Explained Kurtosis concept in the next section."
},
{
"code": null,
"e": 4635,
"s": 4519,
"text": "Count (size): The total sum of observations. Counting is also necessary for calculating the mean, median, and mode."
},
{
"code": null,
"e": 4767,
"s": 4635,
"text": "% highest unique (relativity): The proportion of the highest unique observation regarding all the unique values or group of values."
},
{
"code": null,
"e": 4960,
"s": 4767,
"text": "In a perfect world, the data’s distribution assumes the form of a bell curve (Gaussian or normally distributed), but in the real world, data distributions usually are not symmetric (= skewed)."
},
{
"code": null,
"e": 5106,
"s": 4960,
"text": "Therefore, the skewness indicates how much our distribution derives from the normal distribution (with the skewness value of zero or very close)."
},
{
"code": null,
"e": 5154,
"s": 5106,
"text": "There are three generic types of distributions:"
},
{
"code": null,
"e": 5289,
"s": 5154,
"text": "Symmetrical [median = mean]: In a normal distribution, the mean (average) divides the data symmetrically at the median value or close."
},
{
"code": null,
"e": 5543,
"s": 5289,
"text": "Positive skew [median < mean]: The distribution is asymmetrical, the tail is skewed/longer towards the right-hand side of the curve. In this type, the majority of the observations are concentrated on the left tail, and the value of skewness is positive."
},
{
"code": null,
"e": 5816,
"s": 5543,
"text": "Negative skew [median > mean]: The distribution is asymmetrical and the tail is skewed/longer towards the left-hand side of the curve. In this type of distribution, the majority of the observations are concentrated on the right tail, and the value of skewness is negative."
},
{
"code": null,
"e": 5832,
"s": 5816,
"text": "Rule of thumbs:"
},
{
"code": null,
"e": 5884,
"s": 5832,
"text": "Symmetric distribution: values between -0.5 to 0.5."
},
{
"code": null,
"e": 5941,
"s": 5884,
"text": "Moderate skew: values between -1 and -0.5 and 0.5 and 1."
},
{
"code": null,
"e": 5970,
"s": 5941,
"text": "High skew: values <-1 or >1."
},
{
"code": null,
"e": 6166,
"s": 5970,
"text": "kurtosis is another useful tool when it comes to quantify the shape of a distribution. It measures both how long are the tails, but most important, and how sharp is the peak of the distributions."
},
{
"code": null,
"e": 6402,
"s": 6166,
"text": "If the distribution has a sharper and taller peak and shorter tails, then it has a higher kurtosis while a low kurtosis can be observed when the peak of the distribution is flatter with thinner tails. There are three types of kurtosis:"
},
{
"code": null,
"e": 6490,
"s": 6402,
"text": "Leptokurtic: The distribution is tall and thin. The value of a leptokurtic must be > 3."
},
{
"code": null,
"e": 6620,
"s": 6490,
"text": "Mesokurtic: This distribution looks the same or very similar to a normal distribution. The value of a “normal” mesokurtic is = 3."
},
{
"code": null,
"e": 6788,
"s": 6620,
"text": "Platykurtic: The distributions have a flatter and wider peak and thinner tails, meaning that the data is moderately spread out. The value of a platykurtic must be < 3."
},
{
"code": null,
"e": 7248,
"s": 6788,
"text": "Kurtosis is calculated by raising the average of the standardized data to the fourth power. If we raise any standardized number (less than 1) to the 4th power, the result would be a very small number, somewhere close to zero. Such a small value would not contribute much to the kurtosis. The conclusion is that the values that would make a difference to the kurtosis would be the ones far away from the region of the peak, put it in other words, the outliers."
},
{
"code": null,
"e": 7398,
"s": 7248,
"text": "In this section, we will be giving short numeric stats summaries concerning the different measures of central tendency and dispersion of the dataset."
},
{
"code": null,
"e": 7492,
"s": 7398,
"text": "let’s work on some practical examples through a descriptive statistics environment in Pandas."
},
{
"code": null,
"e": 7510,
"s": 7492,
"text": "> Repo code here."
},
{
"code": null,
"e": 7553,
"s": 7510,
"text": "Start by importing the required libraries:"
},
{
"code": null,
"e": 7673,
"s": 7553,
"text": "import pandas as pdimport numpy as npimport scipyimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inline"
},
{
"code": null,
"e": 7730,
"s": 7673,
"text": "Load the dataset:df = pd.read_csv(\"sample.csv\", sep=\";\")"
},
{
"code": null,
"e": 7755,
"s": 7730,
"text": "Print the data:df.head()"
},
{
"code": null,
"e": 7831,
"s": 7755,
"text": "Before any stats calculus, let’s just take a quick look at the data:df.info"
},
{
"code": null,
"e": 7987,
"s": 7831,
"text": "The dataset consists of 310 observations and 2 columns. One of the attributes is numerical, and the other categorical. Both columns have no missing values."
},
{
"code": null,
"e": 8132,
"s": 7987,
"text": "The numerical variable we are going to analyze is age. First step is to visually observe the variable. So let's plot an histogram and a boxplot."
},
{
"code": null,
"e": 8217,
"s": 8132,
"text": "plt.hist(df.age, bins=20)plt.xlabel(“Age”)plt.ylabel(“Absolute Frequency”)plt.show()"
},
{
"code": null,
"e": 8308,
"s": 8217,
"text": "sns.boxplot(x=age, data=df, orient=\"h\").set(xlabel=\"Age\", title=\"Numeric variable 'Age'\");"
},
{
"code": null,
"e": 8480,
"s": 8308,
"text": "It is also possible to visually observe the variable with both a histogram and a boxplot combined. I find it a useful graphical combination and use it a lot in my reports."
},
{
"code": null,
"e": 8992,
"s": 8480,
"text": "age = df.agef, (ax_box, ax_hist) = plt.subplots(2, sharex=True, gridspec_kw= {\"height_ratios\": (0.8, 1.2)})mean=np.array(age).mean()median=np.median(age)sns.boxplot(age, ax=ax_box)ax_box.axvline(mean, color='r', linestyle='--')ax_box.axvline(median, color='g', linestyle='-')sns.distplot(age, ax=ax_hist)ax_hist.axvline(mean, color='r', linestyle='--')ax_hist.axvline(median, color='g', linestyle='-')plt.legend({'Mean':mean,'Median':median})plt.title(\"'Age' histogram + boxplot\")ax_box.set(xlabel='')plt.show()"
},
{
"code": null,
"e": 9014,
"s": 8992,
"text": "1. Mean:df.age.mean()"
},
{
"code": null,
"e": 9033,
"s": 9014,
"text": "35.564516129032256"
},
{
"code": null,
"e": 9059,
"s": 9033,
"text": "2. Median:df.age.median()"
},
{
"code": null,
"e": 9064,
"s": 9059,
"text": "32.0"
},
{
"code": null,
"e": 9099,
"s": 9064,
"text": "3. Standard deviation:df.age.std()"
},
{
"code": null,
"e": 9118,
"s": 9099,
"text": "18.824363618000913"
},
{
"code": null,
"e": 9143,
"s": 9118,
"text": "4. Variance:df.age.var()"
},
{
"code": null,
"e": 9161,
"s": 9143,
"text": "354.3566656227164"
},
{
"code": null,
"e": 9205,
"s": 9161,
"text": "5. a) Percentiles 25%:df.age.quantile(0.25)"
},
{
"code": null,
"e": 9210,
"s": 9205,
"text": "23.0"
},
{
"code": null,
"e": 9250,
"s": 9210,
"text": "b) Percentile 75%:df.age.quantile(0.75)"
},
{
"code": null,
"e": 9255,
"s": 9250,
"text": "45.0"
},
{
"code": null,
"e": 9297,
"s": 9255,
"text": "c) In one go:df.age.quantile(q=[.25, .75)"
},
{
"code": null,
"e": 9347,
"s": 9297,
"text": "0.25 23.00.75 45.0Name: age, dtype: float64"
},
{
"code": null,
"e": 9397,
"s": 9347,
"text": "6. Minimum and maximum:df.age.min(), df.age.max()"
},
{
"code": null,
"e": 9405,
"s": 9397,
"text": "(3, 98)"
},
{
"code": null,
"e": 9455,
"s": 9405,
"text": "7. Skewness (with scipy):scipy.stats.skew(df.age)"
},
{
"code": null,
"e": 9474,
"s": 9455,
"text": "0.9085582496839909"
},
{
"code": null,
"e": 9528,
"s": 9474,
"text": "8. Kurtosis (with scipy):scipy.stats.kurtosis(df.age)"
},
{
"code": null,
"e": 9547,
"s": 9528,
"text": "0.7254158742250474"
},
{
"code": null,
"e": 9587,
"s": 9547,
"text": "9. Size (number of rows):df.age.count()"
},
{
"code": null,
"e": 9591,
"s": 9587,
"text": "310"
},
{
"code": null,
"e": 9646,
"s": 9591,
"text": "10. Number of uniques (total distinct)df.age.nunique()"
},
{
"code": null,
"e": 9649,
"s": 9646,
"text": "74"
},
{
"code": null,
"e": 9688,
"s": 9649,
"text": "11. Uniques (distinct):df.age.unique()"
},
{
"code": null,
"e": 9986,
"s": 9688,
"text": "array([46, 22, 54, 33, 69, 35, 11, 97, 50, 34, 67, 43, 21, 12, 23, 45, 89, 76, 5, 55, 65, 24, 27, 57, 38, 28, 36, 60, 56, 53, 26, 25, 42, 83, 16, 51, 90, 10, 70, 44, 20, 31, 47, 30, 91, 7, 6, 41, 66, 61, 96, 32, 58, 17, 52, 29, 75, 86, 98, 48, 40, 13, 4, 68, 62, 9, 18, 39, 15, 19, 8, 71, 3, 37])"
},
{
"code": null,
"e": 10113,
"s": 9986,
"text": "The categorical variable we are going to analyze is city. Let’s plot a bar chart and get a visual observation of the variable."
},
{
"code": null,
"e": 10245,
"s": 10113,
"text": "df.city.value_counts().plot.bar()plt.xlabel(\"City\")plt.ylabel(\"Absolute Frequency\")plt.title(\"Categoric variable 'City'\")plt.show()"
},
{
"code": null,
"e": 10271,
"s": 10245,
"text": "1. Mode:df.city.mode()[0]"
},
{
"code": null,
"e": 10279,
"s": 10271,
"text": "'Paris'"
},
{
"code": null,
"e": 10318,
"s": 10279,
"text": "2. Number of uniques:df.city.nunique()"
},
{
"code": null,
"e": 10320,
"s": 10318,
"text": "6"
},
{
"code": null,
"e": 10359,
"s": 10320,
"text": "3. Uniques (distinct):df.city.unique()"
},
{
"code": null,
"e": 10444,
"s": 10359,
"text": "array(['Lisbon', 'Paris', 'Madrid', 'London', 'Luxembourg', 'Berlin'], dtype=object)"
},
{
"code": null,
"e": 10513,
"s": 10444,
"text": "4. Most frequent unique (value count):df.city.value_counts().head(1)"
},
{
"code": null,
"e": 10550,
"s": 10513,
"text": "Paris 67Name: city, dtype: int64"
},
{
"code": null,
"e": 10591,
"s": 10550,
"text": "5. Size (number of rows):df.city.count()"
},
{
"code": null,
"e": 10595,
"s": 10591,
"text": "310"
},
{
"code": null,
"e": 10750,
"s": 10595,
"text": "6. % of the highest unique (fraction of the most common unique in regards to all the others):p = df.city.value_counts(normalize=True)[0] print(f\"{p:.1%}\")"
},
{
"code": null,
"e": 10756,
"s": 10750,
"text": "21.6%"
},
{
"code": null,
"e": 10932,
"s": 10756,
"text": "The describe() method shows the descriptive statistics gathered in one table. By default, stats for numeric data. The result is represented as a pandas dataframe.df.describe()"
},
{
"code": null,
"e": 11085,
"s": 10932,
"text": "Adding other non-standard values, for instance, the ‘variance’.describe_var = data.describe()describe_var.append(pd.Series(data.var(), name='variance'))"
},
{
"code": null,
"e": 11220,
"s": 11085,
"text": "Displaying categorical data.df.describe(include=[\"O\"])<=> df.describe(exclude=['float64','int64'])<=> df.describe(include=[np.object])"
},
{
"code": null,
"e": 11341,
"s": 11220,
"text": "By passing the parameter include='all', displays both numeric and categoric variables at once.df.describe(include='all')"
},
{
"code": null,
"e": 11608,
"s": 11341,
"text": "These are the basics of descriptive statistics when developing an exploratory data analysis project with the help of Pandas, Numpy, Scipy, Matplolib and/or Seaborn. When well performed, these stats help us to understand and transform the data for further processing."
},
{
"code": null,
"e": 11780,
"s": 11608,
"text": "Remember always be a skeptic. Look at the data with your own eyes (don’t fully rely on statistics), and graphically visualize the variables (use and abuse of the visuals)."
},
{
"code": null,
"e": 11798,
"s": 11780,
"text": "> Repo code here."
},
{
"code": null,
"e": 11852,
"s": 11798,
"text": "Check out other articles you might also like to read:"
},
{
"code": null,
"e": 11875,
"s": 11852,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 11898,
"s": 11875,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 11921,
"s": 11898,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 11930,
"s": 11921,
"text": "Linkedin"
},
{
"code": null,
"e": 11938,
"s": 11930,
"text": "Twitter"
},
{
"code": null,
"e": 11945,
"s": 11938,
"text": "Medium"
},
{
"code": null,
"e": 11952,
"s": 11945,
"text": "GitHub"
},
{
"code": null,
"e": 11959,
"s": 11952,
"text": "Kaggle"
},
{
"code": null,
"e": 11965,
"s": 11959,
"text": "Email"
}
] |
Sum of subset differences - GeeksforGeeks | 28 May, 2018
Given a set S consisting of n numbers, find the sum of difference between last and first element of each subset. We find first and last element of every subset by keeping them in same order as they appear in input set S.
i.e., sumSetDiff(S) = ∑ (last(s) – first(s)),where sum goes over all subsets s of S.
Note: Elements in the subset should be in the same order as in the set S.
Examples:
S = {5, 2, 9, 6}, n = 4
Subsets are:
{5}, last(s)-first(s) = 0.
{2}, last(s)-first(s) = 0.
{9}, last(s)-first(s) = 0.
{6}, last(s)-first(s) = 0.
{5,2}, last(s)-first(s) = -3.
{5,9}, last(s)-first(s) = 4.
{5,6}, last(s)-first(s) = 1.
{2,9}, last(s)-first(s) = 7.
{2,6}, last(s)-first(s) = 4.
{9,6}, last(s)-first(s) = -3.
{5,2,9}, last(s)-first(s) = 4.
{5,2,6}, last(s)-first(s) = 1.
{5,9,6}, last(s)-first(s) = 1.
{2,9,6}, last(s)-first(s) = 4.
{5,2,9,6}, last(s)-first(s) = 1.
Output = -3+4+1+7+4-3+4+1+1+4+1
= 21.
A simple solution for this problem is to find the difference between the last and first element for each subset s of set S and output the sum of ll these differences. Time complexity for this approach is O(2n).
An efficient solution to solve the problem in linear time complexity.We are given a set S consisting of n numbers, and we need to compute the sum of difference between last and first element of each subset of S, i.e.,sumSetDiff(S) = ∑ (last(s) – first(s)), where sum goes over all subsets s of S.Equivalently,sumSetDiff(S) = ∑ (last(s)) – ∑ (first(s)),In other words, we can compute the sum of last element of each subset, and the sum of first element of each subset separately, and then compute their difference.
Let us say that the elements of S are {a1, a2, a3,..., an}. Note the following observation:
Subsets containing element a1 as the first element can be obtained by taking any subset of {a2, a3,..., an} and then including a1 into it. Number of such subsets will be 2n-1.Subsets containing element a2 as the first element can be obtained by taking any subset of {a3, a4,..., an} and then including a2 into it. Number of such subsets will be 2n-2.Subsets containing element ai as the first element can be obtained by taking any subset of {ai, a(i+1),..., an} and then including ai into it. Number of such subsets will be 2n-i.Therefore, the sum of first element of all subsets will be:SumF = a1.2n-1 + a2.2n-2 +...+ an.1In a similar way we can compute the sum of last element of all subsets of S (Taking at every step ai as last element instead of first element and then obtaining all the subsets).SumL = a1.1 + a2.2 +...+ an.2n-1Finally, the answer of our problem will be SumL – SumF.Implementation:C++JavaPython3C#PHPC++// A C++ program to find sum of difference between// last and first element of each subset#include<bits/stdc++.h> // Returns the sum of first elements of all subsetsint SumF(int S[], int n){ int sum = 0; // Compute the SumF as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, n-i-1)); return sum;} // Returns the sum of last elements of all subsetsint SumL(int S[], int n){ int sum = 0; // Compute the SumL as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, i)); return sum;} // Returns the difference between sum of last elements of// each subset and the sum of first elements of each subsetint sumSetDiff(int S[], int n){ return SumL(S, n) - SumF(S, n);} // Driver program to test above functionint main(){ int n = 4; int S[] = {5, 2, 9, 6}; printf("%d\n", sumSetDiff(S, n)); return 0;}Java// A Java program to find sum of difference // between last and first element of each // subsetclass GFG { // Returns the sum of first elements // of all subsets static int SumF(int S[], int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int S[], int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int S[], int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void main(String arg[]) { int n = 4; int S[] = { 5, 2, 9, 6 }; System.out.println(sumSetDiff(S, n)); }} // This code is contributed by Anant Agarwal.Python3# Python3 program to find sum of# difference between last and # first element of each subset # Returns the sum of first# elements of all subsetsdef SumF(S, n): sum = 0 # Compute the SumF as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, n - i - 1)) return sum # Returns the sum of last# elements of all subsetsdef SumL(S, n): sum = 0 # Compute the SumL as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, i)) return sum # Returns the difference between sum# of last elements of each subset and# the sum of first elements of each subsetdef sumSetDiff(S, n): return SumL(S, n) - SumF(S, n) # Driver programn = 4S = [5, 2, 9, 6]print(sumSetDiff(S, n)) # This code is contributed by Anant Agarwal.C#// A C# program to find sum of difference // between last and first element of each // subsetusing System;class GFG { // Returns the sum of first elements // of all subsets static int SumF(int []S, int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int []S, int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int []S, int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void Main() { int n = 4; int []S = { 5, 2, 9, 6 }; Console.Write(sumSetDiff(S, n)); }} // This code is contributed by nitin mittal.PHP<?php// A PHP program to find sum // of difference between last // and first element of each subset // Returns the sum of first // elements of all subsetsfunction SumF( $S, $n){ $sum = 0; // Compute the SumF as given // in the above explanation for ($i = 0; $i < $n; $i++) $sum = $sum + ($S[$i] * pow(2, $n - $i - 1)); return $sum;} // Returns the sum of last// elements of all subsetsfunction SumL( $S, $n){ $sum = 0; // Compute the SumL as given // in the above explanation for($i = 0; $i < $n; $i++) $sum = $sum + ($S[$i] * pow(2, $i)); return $sum;} // Returns the difference between// sum of last elements of// each subset and the sum of// first elements of each subsetfunction sumSetDiff( $S, $n){ return SumL($S, $n) - SumF($S, $n);} // Driver Code $n = 4; $S = array(5, 2, 9, 6); echo sumSetDiff($S, $n); // This code is contributed by anuj_67.?>Output:21
Time Complexity : O(n)This article is contributed by Akash Aggarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes
arrow_drop_upSave
Subsets containing element a1 as the first element can be obtained by taking any subset of {a2, a3,..., an} and then including a1 into it. Number of such subsets will be 2n-1.
Subsets containing element a2 as the first element can be obtained by taking any subset of {a3, a4,..., an} and then including a2 into it. Number of such subsets will be 2n-2.
Subsets containing element ai as the first element can be obtained by taking any subset of {ai, a(i+1),..., an} and then including ai into it. Number of such subsets will be 2n-i.Therefore, the sum of first element of all subsets will be:SumF = a1.2n-1 + a2.2n-2 +...+ an.1In a similar way we can compute the sum of last element of all subsets of S (Taking at every step ai as last element instead of first element and then obtaining all the subsets).SumL = a1.1 + a2.2 +...+ an.2n-1Finally, the answer of our problem will be SumL – SumF.Implementation:C++JavaPython3C#PHPC++// A C++ program to find sum of difference between// last and first element of each subset#include<bits/stdc++.h> // Returns the sum of first elements of all subsetsint SumF(int S[], int n){ int sum = 0; // Compute the SumF as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, n-i-1)); return sum;} // Returns the sum of last elements of all subsetsint SumL(int S[], int n){ int sum = 0; // Compute the SumL as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, i)); return sum;} // Returns the difference between sum of last elements of// each subset and the sum of first elements of each subsetint sumSetDiff(int S[], int n){ return SumL(S, n) - SumF(S, n);} // Driver program to test above functionint main(){ int n = 4; int S[] = {5, 2, 9, 6}; printf("%d\n", sumSetDiff(S, n)); return 0;}Java// A Java program to find sum of difference // between last and first element of each // subsetclass GFG { // Returns the sum of first elements // of all subsets static int SumF(int S[], int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int S[], int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int S[], int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void main(String arg[]) { int n = 4; int S[] = { 5, 2, 9, 6 }; System.out.println(sumSetDiff(S, n)); }} // This code is contributed by Anant Agarwal.Python3# Python3 program to find sum of# difference between last and # first element of each subset # Returns the sum of first# elements of all subsetsdef SumF(S, n): sum = 0 # Compute the SumF as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, n - i - 1)) return sum # Returns the sum of last# elements of all subsetsdef SumL(S, n): sum = 0 # Compute the SumL as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, i)) return sum # Returns the difference between sum# of last elements of each subset and# the sum of first elements of each subsetdef sumSetDiff(S, n): return SumL(S, n) - SumF(S, n) # Driver programn = 4S = [5, 2, 9, 6]print(sumSetDiff(S, n)) # This code is contributed by Anant Agarwal.C#// A C# program to find sum of difference // between last and first element of each // subsetusing System;class GFG { // Returns the sum of first elements // of all subsets static int SumF(int []S, int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int []S, int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int []S, int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void Main() { int n = 4; int []S = { 5, 2, 9, 6 }; Console.Write(sumSetDiff(S, n)); }} // This code is contributed by nitin mittal.PHP<?php// A PHP program to find sum // of difference between last // and first element of each subset // Returns the sum of first // elements of all subsetsfunction SumF( $S, $n){ $sum = 0; // Compute the SumF as given // in the above explanation for ($i = 0; $i < $n; $i++) $sum = $sum + ($S[$i] * pow(2, $n - $i - 1)); return $sum;} // Returns the sum of last// elements of all subsetsfunction SumL( $S, $n){ $sum = 0; // Compute the SumL as given // in the above explanation for($i = 0; $i < $n; $i++) $sum = $sum + ($S[$i] * pow(2, $i)); return $sum;} // Returns the difference between// sum of last elements of// each subset and the sum of// first elements of each subsetfunction sumSetDiff( $S, $n){ return SumL($S, $n) - SumF($S, $n);} // Driver Code $n = 4; $S = array(5, 2, 9, 6); echo sumSetDiff($S, $n); // This code is contributed by anuj_67.?>Output:21
Time Complexity : O(n)This article is contributed by Akash Aggarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes
arrow_drop_upSave
Therefore, the sum of first element of all subsets will be:SumF = a1.2n-1 + a2.2n-2 +...+ an.1
In a similar way we can compute the sum of last element of all subsets of S (Taking at every step ai as last element instead of first element and then obtaining all the subsets).SumL = a1.1 + a2.2 +...+ an.2n-1
Finally, the answer of our problem will be SumL – SumF.
Implementation:
C++
Java
Python3
C#
PHP
// A C++ program to find sum of difference between// last and first element of each subset#include<bits/stdc++.h> // Returns the sum of first elements of all subsetsint SumF(int S[], int n){ int sum = 0; // Compute the SumF as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, n-i-1)); return sum;} // Returns the sum of last elements of all subsetsint SumL(int S[], int n){ int sum = 0; // Compute the SumL as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, i)); return sum;} // Returns the difference between sum of last elements of// each subset and the sum of first elements of each subsetint sumSetDiff(int S[], int n){ return SumL(S, n) - SumF(S, n);} // Driver program to test above functionint main(){ int n = 4; int S[] = {5, 2, 9, 6}; printf("%d\n", sumSetDiff(S, n)); return 0;}
// A Java program to find sum of difference // between last and first element of each // subsetclass GFG { // Returns the sum of first elements // of all subsets static int SumF(int S[], int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int S[], int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int S[], int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void main(String arg[]) { int n = 4; int S[] = { 5, 2, 9, 6 }; System.out.println(sumSetDiff(S, n)); }} // This code is contributed by Anant Agarwal.
# Python3 program to find sum of# difference between last and # first element of each subset # Returns the sum of first# elements of all subsetsdef SumF(S, n): sum = 0 # Compute the SumF as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, n - i - 1)) return sum # Returns the sum of last# elements of all subsetsdef SumL(S, n): sum = 0 # Compute the SumL as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, i)) return sum # Returns the difference between sum# of last elements of each subset and# the sum of first elements of each subsetdef sumSetDiff(S, n): return SumL(S, n) - SumF(S, n) # Driver programn = 4S = [5, 2, 9, 6]print(sumSetDiff(S, n)) # This code is contributed by Anant Agarwal.
// A C# program to find sum of difference // between last and first element of each // subsetusing System;class GFG { // Returns the sum of first elements // of all subsets static int SumF(int []S, int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int []S, int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int []S, int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void Main() { int n = 4; int []S = { 5, 2, 9, 6 }; Console.Write(sumSetDiff(S, n)); }} // This code is contributed by nitin mittal.
<?php// A PHP program to find sum // of difference between last // and first element of each subset // Returns the sum of first // elements of all subsetsfunction SumF( $S, $n){ $sum = 0; // Compute the SumF as given // in the above explanation for ($i = 0; $i < $n; $i++) $sum = $sum + ($S[$i] * pow(2, $n - $i - 1)); return $sum;} // Returns the sum of last// elements of all subsetsfunction SumL( $S, $n){ $sum = 0; // Compute the SumL as given // in the above explanation for($i = 0; $i < $n; $i++) $sum = $sum + ($S[$i] * pow(2, $i)); return $sum;} // Returns the difference between// sum of last elements of// each subset and the sum of// first elements of each subsetfunction sumSetDiff( $S, $n){ return SumL($S, $n) - SumF($S, $n);} // Driver Code $n = 4; $S = array(5, 2, 9, 6); echo sumSetDiff($S, $n); // This code is contributed by anuj_67.?>
21
Time Complexity : O(n)
This article is contributed by Akash Aggarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
vt_m
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
Python | Using 2D arrays/lists the right way
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Maximum and minimum of an array using minimum number of comparisons
Queue | Set 1 (Introduction and Array Implementation) | [
{
"code": null,
"e": 24469,
"s": 24441,
"text": "\n28 May, 2018"
},
{
"code": null,
"e": 24690,
"s": 24469,
"text": "Given a set S consisting of n numbers, find the sum of difference between last and first element of each subset. We find first and last element of every subset by keeping them in same order as they appear in input set S."
},
{
"code": null,
"e": 24775,
"s": 24690,
"text": "i.e., sumSetDiff(S) = ∑ (last(s) – first(s)),where sum goes over all subsets s of S."
},
{
"code": null,
"e": 24849,
"s": 24775,
"text": "Note: Elements in the subset should be in the same order as in the set S."
},
{
"code": null,
"e": 24859,
"s": 24849,
"text": "Examples:"
},
{
"code": null,
"e": 25387,
"s": 24859,
"text": "S = {5, 2, 9, 6}, n = 4\n\nSubsets are:\n{5}, last(s)-first(s) = 0.\n{2}, last(s)-first(s) = 0.\n{9}, last(s)-first(s) = 0.\n{6}, last(s)-first(s) = 0.\n{5,2}, last(s)-first(s) = -3.\n{5,9}, last(s)-first(s) = 4.\n{5,6}, last(s)-first(s) = 1.\n{2,9}, last(s)-first(s) = 7.\n{2,6}, last(s)-first(s) = 4.\n{9,6}, last(s)-first(s) = -3.\n{5,2,9}, last(s)-first(s) = 4.\n{5,2,6}, last(s)-first(s) = 1.\n{5,9,6}, last(s)-first(s) = 1.\n{2,9,6}, last(s)-first(s) = 4.\n{5,2,9,6}, last(s)-first(s) = 1.\n\nOutput = -3+4+1+7+4-3+4+1+1+4+1\n = 21.\n"
},
{
"code": null,
"e": 25598,
"s": 25387,
"text": "A simple solution for this problem is to find the difference between the last and first element for each subset s of set S and output the sum of ll these differences. Time complexity for this approach is O(2n)."
},
{
"code": null,
"e": 26112,
"s": 25598,
"text": "An efficient solution to solve the problem in linear time complexity.We are given a set S consisting of n numbers, and we need to compute the sum of difference between last and first element of each subset of S, i.e.,sumSetDiff(S) = ∑ (last(s) – first(s)), where sum goes over all subsets s of S.Equivalently,sumSetDiff(S) = ∑ (last(s)) – ∑ (first(s)),In other words, we can compute the sum of last element of each subset, and the sum of first element of each subset separately, and then compute their difference."
},
{
"code": null,
"e": 26204,
"s": 26112,
"text": "Let us say that the elements of S are {a1, a2, a3,..., an}. Note the following observation:"
},
{
"code": null,
"e": 32868,
"s": 26204,
"text": "Subsets containing element a1 as the first element can be obtained by taking any subset of {a2, a3,..., an} and then including a1 into it. Number of such subsets will be 2n-1.Subsets containing element a2 as the first element can be obtained by taking any subset of {a3, a4,..., an} and then including a2 into it. Number of such subsets will be 2n-2.Subsets containing element ai as the first element can be obtained by taking any subset of {ai, a(i+1),..., an} and then including ai into it. Number of such subsets will be 2n-i.Therefore, the sum of first element of all subsets will be:SumF = a1.2n-1 + a2.2n-2 +...+ an.1In a similar way we can compute the sum of last element of all subsets of S (Taking at every step ai as last element instead of first element and then obtaining all the subsets).SumL = a1.1 + a2.2 +...+ an.2n-1Finally, the answer of our problem will be SumL – SumF.Implementation:C++JavaPython3C#PHPC++// A C++ program to find sum of difference between// last and first element of each subset#include<bits/stdc++.h> // Returns the sum of first elements of all subsetsint SumF(int S[], int n){ int sum = 0; // Compute the SumF as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, n-i-1)); return sum;} // Returns the sum of last elements of all subsetsint SumL(int S[], int n){ int sum = 0; // Compute the SumL as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, i)); return sum;} // Returns the difference between sum of last elements of// each subset and the sum of first elements of each subsetint sumSetDiff(int S[], int n){ return SumL(S, n) - SumF(S, n);} // Driver program to test above functionint main(){ int n = 4; int S[] = {5, 2, 9, 6}; printf(\"%d\\n\", sumSetDiff(S, n)); return 0;}Java// A Java program to find sum of difference // between last and first element of each // subsetclass GFG { // Returns the sum of first elements // of all subsets static int SumF(int S[], int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int S[], int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int S[], int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void main(String arg[]) { int n = 4; int S[] = { 5, 2, 9, 6 }; System.out.println(sumSetDiff(S, n)); }} // This code is contributed by Anant Agarwal.Python3# Python3 program to find sum of# difference between last and # first element of each subset # Returns the sum of first# elements of all subsetsdef SumF(S, n): sum = 0 # Compute the SumF as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, n - i - 1)) return sum # Returns the sum of last# elements of all subsetsdef SumL(S, n): sum = 0 # Compute the SumL as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, i)) return sum # Returns the difference between sum# of last elements of each subset and# the sum of first elements of each subsetdef sumSetDiff(S, n): return SumL(S, n) - SumF(S, n) # Driver programn = 4S = [5, 2, 9, 6]print(sumSetDiff(S, n)) # This code is contributed by Anant Agarwal.C#// A C# program to find sum of difference // between last and first element of each // subsetusing System;class GFG { // Returns the sum of first elements // of all subsets static int SumF(int []S, int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int []S, int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int []S, int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void Main() { int n = 4; int []S = { 5, 2, 9, 6 }; Console.Write(sumSetDiff(S, n)); }} // This code is contributed by nitin mittal.PHP<?php// A PHP program to find sum // of difference between last // and first element of each subset // Returns the sum of first // elements of all subsetsfunction SumF( $S, $n){ $sum = 0; // Compute the SumF as given // in the above explanation for ($i = 0; $i < $n; $i++) $sum = $sum + ($S[$i] * pow(2, $n - $i - 1)); return $sum;} // Returns the sum of last// elements of all subsetsfunction SumL( $S, $n){ $sum = 0; // Compute the SumL as given // in the above explanation for($i = 0; $i < $n; $i++) $sum = $sum + ($S[$i] * pow(2, $i)); return $sum;} // Returns the difference between// sum of last elements of// each subset and the sum of// first elements of each subsetfunction sumSetDiff( $S, $n){ return SumL($S, $n) - SumF($S, $n);} // Driver Code $n = 4; $S = array(5, 2, 9, 6); echo sumSetDiff($S, $n); // This code is contributed by anuj_67.?>Output:21\nTime Complexity : O(n)This article is contributed by Akash Aggarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 33044,
"s": 32868,
"text": "Subsets containing element a1 as the first element can be obtained by taking any subset of {a2, a3,..., an} and then including a1 into it. Number of such subsets will be 2n-1."
},
{
"code": null,
"e": 33220,
"s": 33044,
"text": "Subsets containing element a2 as the first element can be obtained by taking any subset of {a3, a4,..., an} and then including a2 into it. Number of such subsets will be 2n-2."
},
{
"code": null,
"e": 39534,
"s": 33220,
"text": "Subsets containing element ai as the first element can be obtained by taking any subset of {ai, a(i+1),..., an} and then including ai into it. Number of such subsets will be 2n-i.Therefore, the sum of first element of all subsets will be:SumF = a1.2n-1 + a2.2n-2 +...+ an.1In a similar way we can compute the sum of last element of all subsets of S (Taking at every step ai as last element instead of first element and then obtaining all the subsets).SumL = a1.1 + a2.2 +...+ an.2n-1Finally, the answer of our problem will be SumL – SumF.Implementation:C++JavaPython3C#PHPC++// A C++ program to find sum of difference between// last and first element of each subset#include<bits/stdc++.h> // Returns the sum of first elements of all subsetsint SumF(int S[], int n){ int sum = 0; // Compute the SumF as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, n-i-1)); return sum;} // Returns the sum of last elements of all subsetsint SumL(int S[], int n){ int sum = 0; // Compute the SumL as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, i)); return sum;} // Returns the difference between sum of last elements of// each subset and the sum of first elements of each subsetint sumSetDiff(int S[], int n){ return SumL(S, n) - SumF(S, n);} // Driver program to test above functionint main(){ int n = 4; int S[] = {5, 2, 9, 6}; printf(\"%d\\n\", sumSetDiff(S, n)); return 0;}Java// A Java program to find sum of difference // between last and first element of each // subsetclass GFG { // Returns the sum of first elements // of all subsets static int SumF(int S[], int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int S[], int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int S[], int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void main(String arg[]) { int n = 4; int S[] = { 5, 2, 9, 6 }; System.out.println(sumSetDiff(S, n)); }} // This code is contributed by Anant Agarwal.Python3# Python3 program to find sum of# difference between last and # first element of each subset # Returns the sum of first# elements of all subsetsdef SumF(S, n): sum = 0 # Compute the SumF as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, n - i - 1)) return sum # Returns the sum of last# elements of all subsetsdef SumL(S, n): sum = 0 # Compute the SumL as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, i)) return sum # Returns the difference between sum# of last elements of each subset and# the sum of first elements of each subsetdef sumSetDiff(S, n): return SumL(S, n) - SumF(S, n) # Driver programn = 4S = [5, 2, 9, 6]print(sumSetDiff(S, n)) # This code is contributed by Anant Agarwal.C#// A C# program to find sum of difference // between last and first element of each // subsetusing System;class GFG { // Returns the sum of first elements // of all subsets static int SumF(int []S, int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int []S, int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int []S, int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void Main() { int n = 4; int []S = { 5, 2, 9, 6 }; Console.Write(sumSetDiff(S, n)); }} // This code is contributed by nitin mittal.PHP<?php// A PHP program to find sum // of difference between last // and first element of each subset // Returns the sum of first // elements of all subsetsfunction SumF( $S, $n){ $sum = 0; // Compute the SumF as given // in the above explanation for ($i = 0; $i < $n; $i++) $sum = $sum + ($S[$i] * pow(2, $n - $i - 1)); return $sum;} // Returns the sum of last// elements of all subsetsfunction SumL( $S, $n){ $sum = 0; // Compute the SumL as given // in the above explanation for($i = 0; $i < $n; $i++) $sum = $sum + ($S[$i] * pow(2, $i)); return $sum;} // Returns the difference between// sum of last elements of// each subset and the sum of// first elements of each subsetfunction sumSetDiff( $S, $n){ return SumL($S, $n) - SumF($S, $n);} // Driver Code $n = 4; $S = array(5, 2, 9, 6); echo sumSetDiff($S, $n); // This code is contributed by anuj_67.?>Output:21\nTime Complexity : O(n)This article is contributed by Akash Aggarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 39629,
"s": 39534,
"text": "Therefore, the sum of first element of all subsets will be:SumF = a1.2n-1 + a2.2n-2 +...+ an.1"
},
{
"code": null,
"e": 39840,
"s": 39629,
"text": "In a similar way we can compute the sum of last element of all subsets of S (Taking at every step ai as last element instead of first element and then obtaining all the subsets).SumL = a1.1 + a2.2 +...+ an.2n-1"
},
{
"code": null,
"e": 39896,
"s": 39840,
"text": "Finally, the answer of our problem will be SumL – SumF."
},
{
"code": null,
"e": 39912,
"s": 39896,
"text": "Implementation:"
},
{
"code": null,
"e": 39916,
"s": 39912,
"text": "C++"
},
{
"code": null,
"e": 39921,
"s": 39916,
"text": "Java"
},
{
"code": null,
"e": 39929,
"s": 39921,
"text": "Python3"
},
{
"code": null,
"e": 39932,
"s": 39929,
"text": "C#"
},
{
"code": null,
"e": 39936,
"s": 39932,
"text": "PHP"
},
{
"code": "// A C++ program to find sum of difference between// last and first element of each subset#include<bits/stdc++.h> // Returns the sum of first elements of all subsetsint SumF(int S[], int n){ int sum = 0; // Compute the SumF as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, n-i-1)); return sum;} // Returns the sum of last elements of all subsetsint SumL(int S[], int n){ int sum = 0; // Compute the SumL as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, i)); return sum;} // Returns the difference between sum of last elements of// each subset and the sum of first elements of each subsetint sumSetDiff(int S[], int n){ return SumL(S, n) - SumF(S, n);} // Driver program to test above functionint main(){ int n = 4; int S[] = {5, 2, 9, 6}; printf(\"%d\\n\", sumSetDiff(S, n)); return 0;}",
"e": 40861,
"s": 39936,
"text": null
},
{
"code": "// A Java program to find sum of difference // between last and first element of each // subsetclass GFG { // Returns the sum of first elements // of all subsets static int SumF(int S[], int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int S[], int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int S[], int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void main(String arg[]) { int n = 4; int S[] = { 5, 2, 9, 6 }; System.out.println(sumSetDiff(S, n)); }} // This code is contributed by Anant Agarwal.",
"e": 42125,
"s": 40861,
"text": null
},
{
"code": "# Python3 program to find sum of# difference between last and # first element of each subset # Returns the sum of first# elements of all subsetsdef SumF(S, n): sum = 0 # Compute the SumF as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, n - i - 1)) return sum # Returns the sum of last# elements of all subsetsdef SumL(S, n): sum = 0 # Compute the SumL as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, i)) return sum # Returns the difference between sum# of last elements of each subset and# the sum of first elements of each subsetdef sumSetDiff(S, n): return SumL(S, n) - SumF(S, n) # Driver programn = 4S = [5, 2, 9, 6]print(sumSetDiff(S, n)) # This code is contributed by Anant Agarwal.",
"e": 42945,
"s": 42125,
"text": null
},
{
"code": "// A C# program to find sum of difference // between last and first element of each // subsetusing System;class GFG { // Returns the sum of first elements // of all subsets static int SumF(int []S, int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int []S, int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int []S, int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void Main() { int n = 4; int []S = { 5, 2, 9, 6 }; Console.Write(sumSetDiff(S, n)); }} // This code is contributed by nitin mittal.",
"e": 44211,
"s": 42945,
"text": null
},
{
"code": "<?php// A PHP program to find sum // of difference between last // and first element of each subset // Returns the sum of first // elements of all subsetsfunction SumF( $S, $n){ $sum = 0; // Compute the SumF as given // in the above explanation for ($i = 0; $i < $n; $i++) $sum = $sum + ($S[$i] * pow(2, $n - $i - 1)); return $sum;} // Returns the sum of last// elements of all subsetsfunction SumL( $S, $n){ $sum = 0; // Compute the SumL as given // in the above explanation for($i = 0; $i < $n; $i++) $sum = $sum + ($S[$i] * pow(2, $i)); return $sum;} // Returns the difference between// sum of last elements of// each subset and the sum of// first elements of each subsetfunction sumSetDiff( $S, $n){ return SumL($S, $n) - SumF($S, $n);} // Driver Code $n = 4; $S = array(5, 2, 9, 6); echo sumSetDiff($S, $n); // This code is contributed by anuj_67.?>",
"e": 45175,
"s": 44211,
"text": null
},
{
"code": null,
"e": 45179,
"s": 45175,
"text": "21\n"
},
{
"code": null,
"e": 45202,
"s": 45179,
"text": "Time Complexity : O(n)"
},
{
"code": null,
"e": 45500,
"s": 45202,
"text": "This article is contributed by Akash Aggarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 45625,
"s": 45500,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 45638,
"s": 45625,
"text": "nitin mittal"
},
{
"code": null,
"e": 45643,
"s": 45638,
"text": "vt_m"
},
{
"code": null,
"e": 45650,
"s": 45643,
"text": "Arrays"
},
{
"code": null,
"e": 45657,
"s": 45650,
"text": "Arrays"
},
{
"code": null,
"e": 45755,
"s": 45657,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 45764,
"s": 45755,
"text": "Comments"
},
{
"code": null,
"e": 45777,
"s": 45764,
"text": "Old Comments"
},
{
"code": null,
"e": 45825,
"s": 45777,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 45869,
"s": 45825,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 45892,
"s": 45869,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 45924,
"s": 45892,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 45938,
"s": 45924,
"text": "Linear Search"
},
{
"code": null,
"e": 45959,
"s": 45938,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 46004,
"s": 45959,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 46089,
"s": 46004,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 46157,
"s": 46089,
"text": "Maximum and minimum of an array using minimum number of comparisons"
}
] |
How to create responsive image gallery using HTML, CSS, jQuery and Bootstrap? - GeeksforGeeks | 22 Dec, 2021
With the advent of new frameworks in web technologies, it has become quite easy to design and implement feature-rich and responsive web pages. Here, we are going to design a responsive image gallery using HTML, CSS, jQuery and Bootstrap.
Features or Functionalities to implement:
Responsive images
Responsive Grid System
Image viewer
Prerequisites: Basic knowledge of HTML, CSS, JavaScript, jQuery, and Bootstrap. Also, the user should be aware of how the grid system in Bootstrap works.
We will divide the complete solution into three different sections in the first section we will create the structure for the gallery. In the second section, we will design the gallery by using CSS. And in the last section will make it available to respond to the user’s interactions.
Creating structure: Initialize HTML layout and responsive images, but we will attach the images by jQuery, in an array format.
HTML Code:<!DOCTYPE html><html><meta charset="utf-8"> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script></head><body> <br> <br> <center> <h1 class="text text-success">GeeksforGeeks</h1> <b>Responsive image gallery</b> </center> <br> <br> <div class="container-fluid"> <center> <div id=gallery> <!-- Content is appended here --> </div> </center> <!-- Modal --> <div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> × </button> </div> <div class="modal-body"> </div> <div class="modal-footer"> </div> </div> </div> </div> </div> </body> </html>Designing structure: We’ll be adding CSS properties as per the requirement in the project.CSS Code:<style> img { border-radius: 8px; } .container-fluid { margin-left: 12px; margin-right: 12px } .contain { padding-top: 8px; padding-bottom: 8px; }</style>Bootstrap code: We will use a bootstrap modal as image viewer and modify it according to our requirements accordingly. We will render all unnecessary components of modal transparent. Remember, we are appending the image in the modal, so we need to use on() method to attach functionalities for such selectors.<style> /* For overriding box-shadow and other default effects of modal and it's children */ .modal, .modal-content, .modal-header, .modal-footer { background-color: transparent; border: 0px; color: white; /* Disable box shadow for different browsers */ -webkit-box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); -moz-box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); } .modal-dialog { width: 100%; height: 50%; margin-top: 8px; } .close { color: white; opacity: 0.8; } .modal-body { height: 75%; }</style>Respond section: In this section we will attach all the images for the responsive gallery, make them responsive to the user. Below is the grid arrangement we’ll be using for displaying images in the image gallery. Since classes used col-sm-6 col-md-2. The logic is 2-grids for medium screen break-point and 6-grids for large breakpoints. They also divide further whenever content overlaps thereby presenting as a single grid.jQuery code: Below is the script for appending in this manner. We’ll be supposing that we are getting the images from the server (as an array of image URLs in JavaScript). Now we will append the image accordingly in the content panel of our page. Below is the implementation for the same<script> // Taking Array of Image Addresses // Suppose it as information from the server // Modify this for different address a = ['https://www.geeksforgeeks.org/wp-content/uploads/javascript.png','https://www.geeksforgeeks.org/wp-content/uploads/jquery-banner.png','https://www.geeksforgeeks.org/wp-content/uploads/html-768x256.png','https://www.geeksforgeeks.org/wp-content/uploads/CSS-768x256.png','https://www.geeksforgeeks.org/wp-content/uploads/php-1-768x256.png','https://media.geeksforgeeks.org/wp-content/uploads/20200130114942/bootstrap4.png' ]; var x = 0; for (var i = 0; x < a.length; i++) { var append = "<div class='row'>"; for (var j = 0; j < 6 && x < a.length; j++) { append += ` <div class="contain col-sm-6 col-md-2"> <img class="img-responsive" src=` + a[x++] + `> </div> `; } append += '</div>'; appender(append); } // Function to append the data function appender(x) { $('#gallery').html(function(i, original_html) { return (original_html + x); }); } // For Image Modal $(document).on('click', 'img', function() { imgAddr = $(this).attr('src'); data = "<center><img src=" + imgAddr + " width='50%'>"; $('#myModal').find('.modal-body').html(data); $('#myModal').modal(); }); </script>Final Solution: This is the combination of the above three-section, this is the complete responsive image gallery code.Code:<!DOCTYPE html><html><meta charset="utf-8"> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script></head><style> img { border-radius: 8px; } .container-fluid { margin-left: 12px; margin-right: 12px } .contain { padding-top: 8px; padding-bottom: 8px; } /* For overriding box-shadow and other default effects of modal and it's children */ .modal, .modal-content, .modal-header, .modal-footer { background-color: transparent; border: 0px; color: white; /* Disable box shadow for different browsers */ -webkit-box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); -moz-box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); } .modal-dialog { width: 100%; height: 50%; margin-top: 8px; } .close { color: white; opacity: 0.8; } .modal-body { height: 75%; }</style> <body> <br> <br> <center> <h1 class="text text-success">GeeksforGeeks</h1> <b>Responsive image gallery</b> </center> <br> <br> <div class="container-fluid"> <center> <div id=gallery> <!-- Content is appended here --> </div> </center> <!-- Modal --> <div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> × </button> </div> <div class="modal-body"> </div> <div class="modal-footer"> </div> </div> </div> </div> </div> <script> // Taking Array of Image Addresses // Suppose it as information from the server // Modify this for different address a = ['https://www.geeksforgeeks.org/wp-content/uploads/javascript.png','https://www.geeksforgeeks.org/wp-content/uploads/jquery-banner.png','https://www.geeksforgeeks.org/wp-content/uploads/html-768x256.png','https://www.geeksforgeeks.org/wp-content/uploads/CSS-768x256.png','https://www.geeksforgeeks.org/wp-content/uploads/php-1-768x256.png','https://media.geeksforgeeks.org/wp-content/uploads/20200130114942/bootstrap4.png' ]; var x = 0; for (var i = 0; x < a.length; i++) { var append = "<div class='row'>"; for (var j = 0; j < 6 && x < a.length; j++) { append += ` <div class="contain col-sm-6 col-md-2"> <img class="img-responsive" src=` + a[x++] + `> </div> `; } append += '</div>'; appender(append); } // Function to append the data function appender(x) { $('#gallery').html(function(i, original_html) { return (original_html + x); }); } // For Image Modal $(document).on('click', 'img', function() { imgAddr = $(this).attr('src'); data = "<center><img src=" + imgAddr + " width='50%'>"; $('#myModal').find('.modal-body').html(data); $('#myModal').modal(); }); </script></body> </html>Output:Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes
arrow_drop_upSave
<!DOCTYPE html><html><meta charset="utf-8"> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script></head><body> <br> <br> <center> <h1 class="text text-success">GeeksforGeeks</h1> <b>Responsive image gallery</b> </center> <br> <br> <div class="container-fluid"> <center> <div id=gallery> <!-- Content is appended here --> </div> </center> <!-- Modal --> <div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> × </button> </div> <div class="modal-body"> </div> <div class="modal-footer"> </div> </div> </div> </div> </div> </body> </html>
Designing structure: We’ll be adding CSS properties as per the requirement in the project.
CSS Code:<style> img { border-radius: 8px; } .container-fluid { margin-left: 12px; margin-right: 12px } .contain { padding-top: 8px; padding-bottom: 8px; }</style>
<style> img { border-radius: 8px; } .container-fluid { margin-left: 12px; margin-right: 12px } .contain { padding-top: 8px; padding-bottom: 8px; }</style>
Bootstrap code: We will use a bootstrap modal as image viewer and modify it according to our requirements accordingly. We will render all unnecessary components of modal transparent. Remember, we are appending the image in the modal, so we need to use on() method to attach functionalities for such selectors.<style> /* For overriding box-shadow and other default effects of modal and it's children */ .modal, .modal-content, .modal-header, .modal-footer { background-color: transparent; border: 0px; color: white; /* Disable box shadow for different browsers */ -webkit-box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); -moz-box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); } .modal-dialog { width: 100%; height: 50%; margin-top: 8px; } .close { color: white; opacity: 0.8; } .modal-body { height: 75%; }</style>
<style> /* For overriding box-shadow and other default effects of modal and it's children */ .modal, .modal-content, .modal-header, .modal-footer { background-color: transparent; border: 0px; color: white; /* Disable box shadow for different browsers */ -webkit-box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); -moz-box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); } .modal-dialog { width: 100%; height: 50%; margin-top: 8px; } .close { color: white; opacity: 0.8; } .modal-body { height: 75%; }</style>
Respond section: In this section we will attach all the images for the responsive gallery, make them responsive to the user. Below is the grid arrangement we’ll be using for displaying images in the image gallery. Since classes used col-sm-6 col-md-2. The logic is 2-grids for medium screen break-point and 6-grids for large breakpoints. They also divide further whenever content overlaps thereby presenting as a single grid.
jQuery code: Below is the script for appending in this manner. We’ll be supposing that we are getting the images from the server (as an array of image URLs in JavaScript). Now we will append the image accordingly in the content panel of our page. Below is the implementation for the same<script> // Taking Array of Image Addresses // Suppose it as information from the server // Modify this for different address a = ['https://www.geeksforgeeks.org/wp-content/uploads/javascript.png','https://www.geeksforgeeks.org/wp-content/uploads/jquery-banner.png','https://www.geeksforgeeks.org/wp-content/uploads/html-768x256.png','https://www.geeksforgeeks.org/wp-content/uploads/CSS-768x256.png','https://www.geeksforgeeks.org/wp-content/uploads/php-1-768x256.png','https://media.geeksforgeeks.org/wp-content/uploads/20200130114942/bootstrap4.png' ]; var x = 0; for (var i = 0; x < a.length; i++) { var append = "<div class='row'>"; for (var j = 0; j < 6 && x < a.length; j++) { append += ` <div class="contain col-sm-6 col-md-2"> <img class="img-responsive" src=` + a[x++] + `> </div> `; } append += '</div>'; appender(append); } // Function to append the data function appender(x) { $('#gallery').html(function(i, original_html) { return (original_html + x); }); } // For Image Modal $(document).on('click', 'img', function() { imgAddr = $(this).attr('src'); data = "<center><img src=" + imgAddr + " width='50%'>"; $('#myModal').find('.modal-body').html(data); $('#myModal').modal(); }); </script>
<script> // Taking Array of Image Addresses // Suppose it as information from the server // Modify this for different address a = ['https://www.geeksforgeeks.org/wp-content/uploads/javascript.png','https://www.geeksforgeeks.org/wp-content/uploads/jquery-banner.png','https://www.geeksforgeeks.org/wp-content/uploads/html-768x256.png','https://www.geeksforgeeks.org/wp-content/uploads/CSS-768x256.png','https://www.geeksforgeeks.org/wp-content/uploads/php-1-768x256.png','https://media.geeksforgeeks.org/wp-content/uploads/20200130114942/bootstrap4.png' ]; var x = 0; for (var i = 0; x < a.length; i++) { var append = "<div class='row'>"; for (var j = 0; j < 6 && x < a.length; j++) { append += ` <div class="contain col-sm-6 col-md-2"> <img class="img-responsive" src=` + a[x++] + `> </div> `; } append += '</div>'; appender(append); } // Function to append the data function appender(x) { $('#gallery').html(function(i, original_html) { return (original_html + x); }); } // For Image Modal $(document).on('click', 'img', function() { imgAddr = $(this).attr('src'); data = "<center><img src=" + imgAddr + " width='50%'>"; $('#myModal').find('.modal-body').html(data); $('#myModal').modal(); }); </script>
Final Solution: This is the combination of the above three-section, this is the complete responsive image gallery code.
Code:<!DOCTYPE html><html><meta charset="utf-8"> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script></head><style> img { border-radius: 8px; } .container-fluid { margin-left: 12px; margin-right: 12px } .contain { padding-top: 8px; padding-bottom: 8px; } /* For overriding box-shadow and other default effects of modal and it's children */ .modal, .modal-content, .modal-header, .modal-footer { background-color: transparent; border: 0px; color: white; /* Disable box shadow for different browsers */ -webkit-box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); -moz-box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); } .modal-dialog { width: 100%; height: 50%; margin-top: 8px; } .close { color: white; opacity: 0.8; } .modal-body { height: 75%; }</style> <body> <br> <br> <center> <h1 class="text text-success">GeeksforGeeks</h1> <b>Responsive image gallery</b> </center> <br> <br> <div class="container-fluid"> <center> <div id=gallery> <!-- Content is appended here --> </div> </center> <!-- Modal --> <div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> × </button> </div> <div class="modal-body"> </div> <div class="modal-footer"> </div> </div> </div> </div> </div> <script> // Taking Array of Image Addresses // Suppose it as information from the server // Modify this for different address a = ['https://www.geeksforgeeks.org/wp-content/uploads/javascript.png','https://www.geeksforgeeks.org/wp-content/uploads/jquery-banner.png','https://www.geeksforgeeks.org/wp-content/uploads/html-768x256.png','https://www.geeksforgeeks.org/wp-content/uploads/CSS-768x256.png','https://www.geeksforgeeks.org/wp-content/uploads/php-1-768x256.png','https://media.geeksforgeeks.org/wp-content/uploads/20200130114942/bootstrap4.png' ]; var x = 0; for (var i = 0; x < a.length; i++) { var append = "<div class='row'>"; for (var j = 0; j < 6 && x < a.length; j++) { append += ` <div class="contain col-sm-6 col-md-2"> <img class="img-responsive" src=` + a[x++] + `> </div> `; } append += '</div>'; appender(append); } // Function to append the data function appender(x) { $('#gallery').html(function(i, original_html) { return (original_html + x); }); } // For Image Modal $(document).on('click', 'img', function() { imgAddr = $(this).attr('src'); data = "<center><img src=" + imgAddr + " width='50%'>"; $('#myModal').find('.modal-body').html(data); $('#myModal').modal(); }); </script></body> </html>
<!DOCTYPE html><html><meta charset="utf-8"> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script></head><style> img { border-radius: 8px; } .container-fluid { margin-left: 12px; margin-right: 12px } .contain { padding-top: 8px; padding-bottom: 8px; } /* For overriding box-shadow and other default effects of modal and it's children */ .modal, .modal-content, .modal-header, .modal-footer { background-color: transparent; border: 0px; color: white; /* Disable box shadow for different browsers */ -webkit-box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); -moz-box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); } .modal-dialog { width: 100%; height: 50%; margin-top: 8px; } .close { color: white; opacity: 0.8; } .modal-body { height: 75%; }</style> <body> <br> <br> <center> <h1 class="text text-success">GeeksforGeeks</h1> <b>Responsive image gallery</b> </center> <br> <br> <div class="container-fluid"> <center> <div id=gallery> <!-- Content is appended here --> </div> </center> <!-- Modal --> <div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> × </button> </div> <div class="modal-body"> </div> <div class="modal-footer"> </div> </div> </div> </div> </div> <script> // Taking Array of Image Addresses // Suppose it as information from the server // Modify this for different address a = ['https://www.geeksforgeeks.org/wp-content/uploads/javascript.png','https://www.geeksforgeeks.org/wp-content/uploads/jquery-banner.png','https://www.geeksforgeeks.org/wp-content/uploads/html-768x256.png','https://www.geeksforgeeks.org/wp-content/uploads/CSS-768x256.png','https://www.geeksforgeeks.org/wp-content/uploads/php-1-768x256.png','https://media.geeksforgeeks.org/wp-content/uploads/20200130114942/bootstrap4.png' ]; var x = 0; for (var i = 0; x < a.length; i++) { var append = "<div class='row'>"; for (var j = 0; j < 6 && x < a.length; j++) { append += ` <div class="contain col-sm-6 col-md-2"> <img class="img-responsive" src=` + a[x++] + `> </div> `; } append += '</div>'; appender(append); } // Function to append the data function appender(x) { $('#gallery').html(function(i, original_html) { return (original_html + x); }); } // For Image Modal $(document).on('click', 'img', function() { imgAddr = $(this).attr('src'); data = "<center><img src=" + imgAddr + " width='50%'>"; $('#myModal').find('.modal-body').html(data); $('#myModal').modal(); }); </script></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
arorakashish0911
CSS-Misc
HTML-Misc
JavaScript-Misc
Technical Scripter 2019
Bootstrap
CSS
HTML
JQuery
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to pass data into a bootstrap modal?
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to change the background color of the active nav-item?
How to Use Bootstrap with React?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
CSS to put icon inside an input element in a form | [
{
"code": null,
"e": 24461,
"s": 24433,
"text": "\n22 Dec, 2021"
},
{
"code": null,
"e": 24699,
"s": 24461,
"text": "With the advent of new frameworks in web technologies, it has become quite easy to design and implement feature-rich and responsive web pages. Here, we are going to design a responsive image gallery using HTML, CSS, jQuery and Bootstrap."
},
{
"code": null,
"e": 24741,
"s": 24699,
"text": "Features or Functionalities to implement:"
},
{
"code": null,
"e": 24759,
"s": 24741,
"text": "Responsive images"
},
{
"code": null,
"e": 24782,
"s": 24759,
"text": "Responsive Grid System"
},
{
"code": null,
"e": 24795,
"s": 24782,
"text": "Image viewer"
},
{
"code": null,
"e": 24949,
"s": 24795,
"text": "Prerequisites: Basic knowledge of HTML, CSS, JavaScript, jQuery, and Bootstrap. Also, the user should be aware of how the grid system in Bootstrap works."
},
{
"code": null,
"e": 25233,
"s": 24949,
"text": "We will divide the complete solution into three different sections in the first section we will create the structure for the gallery. In the second section, we will design the gallery by using CSS. And in the last section will make it available to respond to the user’s interactions."
},
{
"code": null,
"e": 25360,
"s": 25233,
"text": "Creating structure: Initialize HTML layout and responsive images, but we will attach the images by jQuery, in an array format."
},
{
"code": null,
"e": 34342,
"s": 25360,
"text": "HTML Code:<!DOCTYPE html><html><meta charset=\"utf-8\"> <head> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script></head><body> <br> <br> <center> <h1 class=\"text text-success\">GeeksforGeeks</h1> <b>Responsive image gallery</b> </center> <br> <br> <div class=\"container-fluid\"> <center> <div id=gallery> <!-- Content is appended here --> </div> </center> <!-- Modal --> <div class=\"modal fade\" id=\"myModal\" role=\"dialog\"> <div class=\"modal-dialog\"> <!-- Modal content--> <div class=\"modal-content\"> <div class=\"modal-header\"> <button type=\"button\" class=\"close\" data-dismiss=\"modal\"> × </button> </div> <div class=\"modal-body\"> </div> <div class=\"modal-footer\"> </div> </div> </div> </div> </div> </body> </html>Designing structure: We’ll be adding CSS properties as per the requirement in the project.CSS Code:<style> img { border-radius: 8px; } .container-fluid { margin-left: 12px; margin-right: 12px } .contain { padding-top: 8px; padding-bottom: 8px; }</style>Bootstrap code: We will use a bootstrap modal as image viewer and modify it according to our requirements accordingly. We will render all unnecessary components of modal transparent. Remember, we are appending the image in the modal, so we need to use on() method to attach functionalities for such selectors.<style> /* For overriding box-shadow and other default effects of modal and it's children */ .modal, .modal-content, .modal-header, .modal-footer { background-color: transparent; border: 0px; color: white; /* Disable box shadow for different browsers */ -webkit-box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); -moz-box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); } .modal-dialog { width: 100%; height: 50%; margin-top: 8px; } .close { color: white; opacity: 0.8; } .modal-body { height: 75%; }</style>Respond section: In this section we will attach all the images for the responsive gallery, make them responsive to the user. Below is the grid arrangement we’ll be using for displaying images in the image gallery. Since classes used col-sm-6 col-md-2. The logic is 2-grids for medium screen break-point and 6-grids for large breakpoints. They also divide further whenever content overlaps thereby presenting as a single grid.jQuery code: Below is the script for appending in this manner. We’ll be supposing that we are getting the images from the server (as an array of image URLs in JavaScript). Now we will append the image accordingly in the content panel of our page. Below is the implementation for the same<script> // Taking Array of Image Addresses // Suppose it as information from the server // Modify this for different address a = ['https://www.geeksforgeeks.org/wp-content/uploads/javascript.png','https://www.geeksforgeeks.org/wp-content/uploads/jquery-banner.png','https://www.geeksforgeeks.org/wp-content/uploads/html-768x256.png','https://www.geeksforgeeks.org/wp-content/uploads/CSS-768x256.png','https://www.geeksforgeeks.org/wp-content/uploads/php-1-768x256.png','https://media.geeksforgeeks.org/wp-content/uploads/20200130114942/bootstrap4.png' ]; var x = 0; for (var i = 0; x < a.length; i++) { var append = \"<div class='row'>\"; for (var j = 0; j < 6 && x < a.length; j++) { append += ` <div class=\"contain col-sm-6 col-md-2\"> <img class=\"img-responsive\" src=` + a[x++] + `> </div> `; } append += '</div>'; appender(append); } // Function to append the data function appender(x) { $('#gallery').html(function(i, original_html) { return (original_html + x); }); } // For Image Modal $(document).on('click', 'img', function() { imgAddr = $(this).attr('src'); data = \"<center><img src=\" + imgAddr + \" width='50%'>\"; $('#myModal').find('.modal-body').html(data); $('#myModal').modal(); }); </script>Final Solution: This is the combination of the above three-section, this is the complete responsive image gallery code.Code:<!DOCTYPE html><html><meta charset=\"utf-8\"> <head> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script></head><style> img { border-radius: 8px; } .container-fluid { margin-left: 12px; margin-right: 12px } .contain { padding-top: 8px; padding-bottom: 8px; } /* For overriding box-shadow and other default effects of modal and it's children */ .modal, .modal-content, .modal-header, .modal-footer { background-color: transparent; border: 0px; color: white; /* Disable box shadow for different browsers */ -webkit-box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); -moz-box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); } .modal-dialog { width: 100%; height: 50%; margin-top: 8px; } .close { color: white; opacity: 0.8; } .modal-body { height: 75%; }</style> <body> <br> <br> <center> <h1 class=\"text text-success\">GeeksforGeeks</h1> <b>Responsive image gallery</b> </center> <br> <br> <div class=\"container-fluid\"> <center> <div id=gallery> <!-- Content is appended here --> </div> </center> <!-- Modal --> <div class=\"modal fade\" id=\"myModal\" role=\"dialog\"> <div class=\"modal-dialog\"> <!-- Modal content--> <div class=\"modal-content\"> <div class=\"modal-header\"> <button type=\"button\" class=\"close\" data-dismiss=\"modal\"> × </button> </div> <div class=\"modal-body\"> </div> <div class=\"modal-footer\"> </div> </div> </div> </div> </div> <script> // Taking Array of Image Addresses // Suppose it as information from the server // Modify this for different address a = ['https://www.geeksforgeeks.org/wp-content/uploads/javascript.png','https://www.geeksforgeeks.org/wp-content/uploads/jquery-banner.png','https://www.geeksforgeeks.org/wp-content/uploads/html-768x256.png','https://www.geeksforgeeks.org/wp-content/uploads/CSS-768x256.png','https://www.geeksforgeeks.org/wp-content/uploads/php-1-768x256.png','https://media.geeksforgeeks.org/wp-content/uploads/20200130114942/bootstrap4.png' ]; var x = 0; for (var i = 0; x < a.length; i++) { var append = \"<div class='row'>\"; for (var j = 0; j < 6 && x < a.length; j++) { append += ` <div class=\"contain col-sm-6 col-md-2\"> <img class=\"img-responsive\" src=` + a[x++] + `> </div> `; } append += '</div>'; appender(append); } // Function to append the data function appender(x) { $('#gallery').html(function(i, original_html) { return (original_html + x); }); } // For Image Modal $(document).on('click', 'img', function() { imgAddr = $(this).attr('src'); data = \"<center><img src=\" + imgAddr + \" width='50%'>\"; $('#myModal').find('.modal-body').html(data); $('#myModal').modal(); }); </script></body> </html>Output:Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes\narrow_drop_upSave"
},
{
"code": "<!DOCTYPE html><html><meta charset=\"utf-8\"> <head> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script></head><body> <br> <br> <center> <h1 class=\"text text-success\">GeeksforGeeks</h1> <b>Responsive image gallery</b> </center> <br> <br> <div class=\"container-fluid\"> <center> <div id=gallery> <!-- Content is appended here --> </div> </center> <!-- Modal --> <div class=\"modal fade\" id=\"myModal\" role=\"dialog\"> <div class=\"modal-dialog\"> <!-- Modal content--> <div class=\"modal-content\"> <div class=\"modal-header\"> <button type=\"button\" class=\"close\" data-dismiss=\"modal\"> × </button> </div> <div class=\"modal-body\"> </div> <div class=\"modal-footer\"> </div> </div> </div> </div> </div> </body> </html>",
"e": 35736,
"s": 34342,
"text": null
},
{
"code": null,
"e": 35827,
"s": 35736,
"text": "Designing structure: We’ll be adding CSS properties as per the requirement in the project."
},
{
"code": null,
"e": 36060,
"s": 35827,
"text": "CSS Code:<style> img { border-radius: 8px; } .container-fluid { margin-left: 12px; margin-right: 12px } .contain { padding-top: 8px; padding-bottom: 8px; }</style>"
},
{
"code": "<style> img { border-radius: 8px; } .container-fluid { margin-left: 12px; margin-right: 12px } .contain { padding-top: 8px; padding-bottom: 8px; }</style>",
"e": 36284,
"s": 36060,
"text": null
},
{
"code": null,
"e": 37314,
"s": 36284,
"text": "Bootstrap code: We will use a bootstrap modal as image viewer and modify it according to our requirements accordingly. We will render all unnecessary components of modal transparent. Remember, we are appending the image in the modal, so we need to use on() method to attach functionalities for such selectors.<style> /* For overriding box-shadow and other default effects of modal and it's children */ .modal, .modal-content, .modal-header, .modal-footer { background-color: transparent; border: 0px; color: white; /* Disable box shadow for different browsers */ -webkit-box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); -moz-box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); } .modal-dialog { width: 100%; height: 50%; margin-top: 8px; } .close { color: white; opacity: 0.8; } .modal-body { height: 75%; }</style>"
},
{
"code": "<style> /* For overriding box-shadow and other default effects of modal and it's children */ .modal, .modal-content, .modal-header, .modal-footer { background-color: transparent; border: 0px; color: white; /* Disable box shadow for different browsers */ -webkit-box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); -moz-box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); } .modal-dialog { width: 100%; height: 50%; margin-top: 8px; } .close { color: white; opacity: 0.8; } .modal-body { height: 75%; }</style>",
"e": 38035,
"s": 37314,
"text": null
},
{
"code": null,
"e": 38461,
"s": 38035,
"text": "Respond section: In this section we will attach all the images for the responsive gallery, make them responsive to the user. Below is the grid arrangement we’ll be using for displaying images in the image gallery. Since classes used col-sm-6 col-md-2. The logic is 2-grids for medium screen break-point and 6-grids for large breakpoints. They also divide further whenever content overlaps thereby presenting as a single grid."
},
{
"code": null,
"e": 40192,
"s": 38461,
"text": "jQuery code: Below is the script for appending in this manner. We’ll be supposing that we are getting the images from the server (as an array of image URLs in JavaScript). Now we will append the image accordingly in the content panel of our page. Below is the implementation for the same<script> // Taking Array of Image Addresses // Suppose it as information from the server // Modify this for different address a = ['https://www.geeksforgeeks.org/wp-content/uploads/javascript.png','https://www.geeksforgeeks.org/wp-content/uploads/jquery-banner.png','https://www.geeksforgeeks.org/wp-content/uploads/html-768x256.png','https://www.geeksforgeeks.org/wp-content/uploads/CSS-768x256.png','https://www.geeksforgeeks.org/wp-content/uploads/php-1-768x256.png','https://media.geeksforgeeks.org/wp-content/uploads/20200130114942/bootstrap4.png' ]; var x = 0; for (var i = 0; x < a.length; i++) { var append = \"<div class='row'>\"; for (var j = 0; j < 6 && x < a.length; j++) { append += ` <div class=\"contain col-sm-6 col-md-2\"> <img class=\"img-responsive\" src=` + a[x++] + `> </div> `; } append += '</div>'; appender(append); } // Function to append the data function appender(x) { $('#gallery').html(function(i, original_html) { return (original_html + x); }); } // For Image Modal $(document).on('click', 'img', function() { imgAddr = $(this).attr('src'); data = \"<center><img src=\" + imgAddr + \" width='50%'>\"; $('#myModal').find('.modal-body').html(data); $('#myModal').modal(); }); </script>"
},
{
"code": "<script> // Taking Array of Image Addresses // Suppose it as information from the server // Modify this for different address a = ['https://www.geeksforgeeks.org/wp-content/uploads/javascript.png','https://www.geeksforgeeks.org/wp-content/uploads/jquery-banner.png','https://www.geeksforgeeks.org/wp-content/uploads/html-768x256.png','https://www.geeksforgeeks.org/wp-content/uploads/CSS-768x256.png','https://www.geeksforgeeks.org/wp-content/uploads/php-1-768x256.png','https://media.geeksforgeeks.org/wp-content/uploads/20200130114942/bootstrap4.png' ]; var x = 0; for (var i = 0; x < a.length; i++) { var append = \"<div class='row'>\"; for (var j = 0; j < 6 && x < a.length; j++) { append += ` <div class=\"contain col-sm-6 col-md-2\"> <img class=\"img-responsive\" src=` + a[x++] + `> </div> `; } append += '</div>'; appender(append); } // Function to append the data function appender(x) { $('#gallery').html(function(i, original_html) { return (original_html + x); }); } // For Image Modal $(document).on('click', 'img', function() { imgAddr = $(this).attr('src'); data = \"<center><img src=\" + imgAddr + \" width='50%'>\"; $('#myModal').find('.modal-body').html(data); $('#myModal').modal(); }); </script>",
"e": 41636,
"s": 40192,
"text": null
},
{
"code": null,
"e": 41756,
"s": 41636,
"text": "Final Solution: This is the combination of the above three-section, this is the complete responsive image gallery code."
},
{
"code": null,
"e": 45532,
"s": 41756,
"text": "Code:<!DOCTYPE html><html><meta charset=\"utf-8\"> <head> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script></head><style> img { border-radius: 8px; } .container-fluid { margin-left: 12px; margin-right: 12px } .contain { padding-top: 8px; padding-bottom: 8px; } /* For overriding box-shadow and other default effects of modal and it's children */ .modal, .modal-content, .modal-header, .modal-footer { background-color: transparent; border: 0px; color: white; /* Disable box shadow for different browsers */ -webkit-box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); -moz-box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); } .modal-dialog { width: 100%; height: 50%; margin-top: 8px; } .close { color: white; opacity: 0.8; } .modal-body { height: 75%; }</style> <body> <br> <br> <center> <h1 class=\"text text-success\">GeeksforGeeks</h1> <b>Responsive image gallery</b> </center> <br> <br> <div class=\"container-fluid\"> <center> <div id=gallery> <!-- Content is appended here --> </div> </center> <!-- Modal --> <div class=\"modal fade\" id=\"myModal\" role=\"dialog\"> <div class=\"modal-dialog\"> <!-- Modal content--> <div class=\"modal-content\"> <div class=\"modal-header\"> <button type=\"button\" class=\"close\" data-dismiss=\"modal\"> × </button> </div> <div class=\"modal-body\"> </div> <div class=\"modal-footer\"> </div> </div> </div> </div> </div> <script> // Taking Array of Image Addresses // Suppose it as information from the server // Modify this for different address a = ['https://www.geeksforgeeks.org/wp-content/uploads/javascript.png','https://www.geeksforgeeks.org/wp-content/uploads/jquery-banner.png','https://www.geeksforgeeks.org/wp-content/uploads/html-768x256.png','https://www.geeksforgeeks.org/wp-content/uploads/CSS-768x256.png','https://www.geeksforgeeks.org/wp-content/uploads/php-1-768x256.png','https://media.geeksforgeeks.org/wp-content/uploads/20200130114942/bootstrap4.png' ]; var x = 0; for (var i = 0; x < a.length; i++) { var append = \"<div class='row'>\"; for (var j = 0; j < 6 && x < a.length; j++) { append += ` <div class=\"contain col-sm-6 col-md-2\"> <img class=\"img-responsive\" src=` + a[x++] + `> </div> `; } append += '</div>'; appender(append); } // Function to append the data function appender(x) { $('#gallery').html(function(i, original_html) { return (original_html + x); }); } // For Image Modal $(document).on('click', 'img', function() { imgAddr = $(this).attr('src'); data = \"<center><img src=\" + imgAddr + \" width='50%'>\"; $('#myModal').find('.modal-body').html(data); $('#myModal').modal(); }); </script></body> </html>"
},
{
"code": "<!DOCTYPE html><html><meta charset=\"utf-8\"> <head> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script></head><style> img { border-radius: 8px; } .container-fluid { margin-left: 12px; margin-right: 12px } .contain { padding-top: 8px; padding-bottom: 8px; } /* For overriding box-shadow and other default effects of modal and it's children */ .modal, .modal-content, .modal-header, .modal-footer { background-color: transparent; border: 0px; color: white; /* Disable box shadow for different browsers */ -webkit-box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); -moz-box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); box-shadow: 0px 0px 0px 0px rgba(255, 255, 255, 1); } .modal-dialog { width: 100%; height: 50%; margin-top: 8px; } .close { color: white; opacity: 0.8; } .modal-body { height: 75%; }</style> <body> <br> <br> <center> <h1 class=\"text text-success\">GeeksforGeeks</h1> <b>Responsive image gallery</b> </center> <br> <br> <div class=\"container-fluid\"> <center> <div id=gallery> <!-- Content is appended here --> </div> </center> <!-- Modal --> <div class=\"modal fade\" id=\"myModal\" role=\"dialog\"> <div class=\"modal-dialog\"> <!-- Modal content--> <div class=\"modal-content\"> <div class=\"modal-header\"> <button type=\"button\" class=\"close\" data-dismiss=\"modal\"> × </button> </div> <div class=\"modal-body\"> </div> <div class=\"modal-footer\"> </div> </div> </div> </div> </div> <script> // Taking Array of Image Addresses // Suppose it as information from the server // Modify this for different address a = ['https://www.geeksforgeeks.org/wp-content/uploads/javascript.png','https://www.geeksforgeeks.org/wp-content/uploads/jquery-banner.png','https://www.geeksforgeeks.org/wp-content/uploads/html-768x256.png','https://www.geeksforgeeks.org/wp-content/uploads/CSS-768x256.png','https://www.geeksforgeeks.org/wp-content/uploads/php-1-768x256.png','https://media.geeksforgeeks.org/wp-content/uploads/20200130114942/bootstrap4.png' ]; var x = 0; for (var i = 0; x < a.length; i++) { var append = \"<div class='row'>\"; for (var j = 0; j < 6 && x < a.length; j++) { append += ` <div class=\"contain col-sm-6 col-md-2\"> <img class=\"img-responsive\" src=` + a[x++] + `> </div> `; } append += '</div>'; appender(append); } // Function to append the data function appender(x) { $('#gallery').html(function(i, original_html) { return (original_html + x); }); } // For Image Modal $(document).on('click', 'img', function() { imgAddr = $(this).attr('src'); data = \"<center><img src=\" + imgAddr + \" width='50%'>\"; $('#myModal').find('.modal-body').html(data); $('#myModal').modal(); }); </script></body> </html>",
"e": 49303,
"s": 45532,
"text": null
},
{
"code": null,
"e": 49311,
"s": 49303,
"text": "Output:"
},
{
"code": null,
"e": 49448,
"s": 49311,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 49465,
"s": 49448,
"text": "arorakashish0911"
},
{
"code": null,
"e": 49474,
"s": 49465,
"text": "CSS-Misc"
},
{
"code": null,
"e": 49484,
"s": 49474,
"text": "HTML-Misc"
},
{
"code": null,
"e": 49500,
"s": 49484,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 49524,
"s": 49500,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 49534,
"s": 49524,
"text": "Bootstrap"
},
{
"code": null,
"e": 49538,
"s": 49534,
"text": "CSS"
},
{
"code": null,
"e": 49543,
"s": 49538,
"text": "HTML"
},
{
"code": null,
"e": 49550,
"s": 49543,
"text": "JQuery"
},
{
"code": null,
"e": 49567,
"s": 49550,
"text": "Web Technologies"
},
{
"code": null,
"e": 49594,
"s": 49567,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 49599,
"s": 49594,
"text": "HTML"
},
{
"code": null,
"e": 49697,
"s": 49599,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 49738,
"s": 49697,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 49779,
"s": 49738,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 49842,
"s": 49779,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 49901,
"s": 49842,
"text": "How to change the background color of the active nav-item?"
},
{
"code": null,
"e": 49934,
"s": 49901,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 49996,
"s": 49934,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 50046,
"s": 49996,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 50104,
"s": 50046,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 50152,
"s": 50104,
"text": "How to update Node.js and NPM to next version ?"
}
] |
Java String trim() Method | ❮ String Methods
Remove whitespace from both sides of a string:
String myStr = " Hello World! ";
System.out.println(myStr);
System.out.println(myStr.trim());
Try it Yourself »
The trim() method removes whitespace from both ends of a string.
Note: This method does not change the original string.
public String trim()
None.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 19,
"s": 0,
"text": "\n❮ String Methods\n"
},
{
"code": null,
"e": 66,
"s": 19,
"text": "Remove whitespace from both sides of a string:"
},
{
"code": null,
"e": 172,
"s": 66,
"text": "String myStr = \" Hello World! \";\nSystem.out.println(myStr);\nSystem.out.println(myStr.trim());"
},
{
"code": null,
"e": 192,
"s": 172,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 257,
"s": 192,
"text": "The trim() method removes whitespace from both ends of a string."
},
{
"code": null,
"e": 312,
"s": 257,
"text": "Note: This method does not change the original string."
},
{
"code": null,
"e": 334,
"s": 312,
"text": "public String trim()\n"
},
{
"code": null,
"e": 340,
"s": 334,
"text": "None."
},
{
"code": null,
"e": 373,
"s": 340,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 415,
"s": 373,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 522,
"s": 415,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 541,
"s": 522,
"text": "help@w3schools.com"
}
] |
Find m-th summation of first n natural numbers. - GeeksforGeeks | 22 Mar, 2021
m-th summation of first n natural numbers is defined as following.
If m > 1
SUM(n, m) = SUM(SUM(n, m - 1), 1)
Else
SUM(n, 1) = Sum of first n natural numbers.
We are given m and n, we need to find SUM(n, m).Examples:
Input : n = 4, m = 1
Output : SUM(4, 1) = 10
Explanation : 1 + 2 + 3 + 4 = 10
Input : n = 3, m = 2
Output : SUM(3, 2) = 21
Explanation : SUM(3, 2)
= SUM(SUM(3, 1), 1)
= SUM(6, 1)
= 21
Naive Approach : We can solve this problem using two nested loop, where outer loop iterate for m and inner loop iterate for n. After completion of a single outer iteration, we should update n as whole of inner loop got executed and value of n must be changed then. Time complexity should be O(n*m).
for (int i = 1;i <= m;i++)
{
sum = 0;
for (int j = 1;j <= n;j++)
sum += j;
n = sum; // update n
}
Efficient Approach : We can use direct formula for sum of first n numbers to reduce time. We can also use recursion. In this approach m = 1 will be our base condition and for any intermediate step SUM(n, m), we will call SUM (SUM(n, m-1), 1) and for a single step SUM(n, 1) = n * (n + 1) / 2 will be used. This will reduce our time complexity to O(m).
int SUM (int n, int m)
{
if (m == 1)
return (n * (n + 1) / 2);
int sum = SUM(n, m-1);
return (sum * (sum + 1) / 2);
}
Below is the implementation of above idea :
C++
Java
C#
PHP
Javascript
// CPP program to find m-th summation#include <bits/stdc++.h>using namespace std; // Function to return mth summationint SUM(int n, int m){ // base case if (m == 1) return (n * (n + 1) / 2); int sum = SUM(n, m-1); return (sum * (sum + 1) / 2);} // driver programint main(){ int n = 5; int m = 3; cout << "SUM(" << n << ", " << m << "): " << SUM(n, m); return 0;}
// Java program to find m-th summation.class GFG { // Function to return mth summation static int SUM(int n, int m) { // base case if (m == 1) return (n * (n + 1) / 2); int sum = SUM(n, m - 1); return (sum * (sum + 1) / 2); } // Driver code public static void main(String[] args) { int n = 5; int m = 3; System.out.println("SUM(" + n + ", " + m + "): " + SUM(n, m)); }} // This code is contributed by Anant Agarwal.
Python3
# Python3 program to find m-th summation
# Function to return mth summation
def SUM(n, m):
# base case
if (m == 1):
return (n * (n + 1) / 2)
sum = SUM(n, m-1)
return int(sum * (sum + 1) / 2)
# driver program
n = 5
m = 3
print("SUM(", n, ", ", m, "):", SUM(n, m))
# This code is contributed by Smitha Dinesh Semwal
// C# program to find m-th summation.using System; class GFG{ // Function to return mth summation static int SUM(int n, int m) { // base case if (m == 1) return (n * (n + 1) / 2); int sum = SUM(n, m - 1); return (sum * (sum + 1) / 2); } // Driver Code public static void Main() { int n = 5; int m = 3; Console.Write("SUM(" + n + ", " + m + "): " + SUM(n, m)); }} // This code is contributed by Nitin Mittal.
<?php// PHP program to find m-th summation // Function to return// mth summationfunction SUM($n, $m){ // base case if ($m == 1) return ($n * ($n + 1) / 2); $sum = SUM($n, $m - 1); return ($sum * ($sum + 1) / 2);} // Driver Code $n = 5; $m = 3; echo "SUM(" , $n , ", " , $m , "): " , SUM($n, $m); // This code is contributed by vt_m.?>
<script>// javascript program to find m-th summation // Function to return mth summationfunction SUM( n, m){ // base case if (m == 1) return (n * (n + 1) / 2); let sum = SUM(n, m-1); return (sum * (sum + 1) / 2);} // driver program let n = 5; let m = 3; document.write( "SUM(" + n + ", " + m + "): " + SUM(n, m)); // This code contributed by Rajput-Ji </script>
Output:
SUM(5, 3): 7260
This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
vt_m
Rajput-Ji
Mathematical
Recursion
Mathematical
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find all factors of a natural number | Set 1
Check if a number is Palindrome
Program to print prime numbers from 1 to N.
Program to add two binary strings
Program to multiply two matrices
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Recursion
Program for Tower of Hanoi
Program for Sum of the digits of a given number
Backtracking | Introduction | [
{
"code": null,
"e": 24327,
"s": 24299,
"text": "\n22 Mar, 2021"
},
{
"code": null,
"e": 24395,
"s": 24327,
"text": "m-th summation of first n natural numbers is defined as following. "
},
{
"code": null,
"e": 24492,
"s": 24395,
"text": "If m > 1\n SUM(n, m) = SUM(SUM(n, m - 1), 1)\nElse \n SUM(n, 1) = Sum of first n natural numbers."
},
{
"code": null,
"e": 24552,
"s": 24492,
"text": "We are given m and n, we need to find SUM(n, m).Examples: "
},
{
"code": null,
"e": 24783,
"s": 24552,
"text": "Input : n = 4, m = 1 \nOutput : SUM(4, 1) = 10\nExplanation : 1 + 2 + 3 + 4 = 10\n\nInput : n = 3, m = 2 \nOutput : SUM(3, 2) = 21\nExplanation : SUM(3, 2) \n = SUM(SUM(3, 1), 1) \n = SUM(6, 1) \n = 21"
},
{
"code": null,
"e": 25086,
"s": 24785,
"text": "Naive Approach : We can solve this problem using two nested loop, where outer loop iterate for m and inner loop iterate for n. After completion of a single outer iteration, we should update n as whole of inner loop got executed and value of n must be changed then. Time complexity should be O(n*m). "
},
{
"code": null,
"e": 25205,
"s": 25086,
"text": "for (int i = 1;i <= m;i++)\n{\n sum = 0;\n for (int j = 1;j <= n;j++)\n sum += j;\n n = sum; // update n\n}"
},
{
"code": null,
"e": 25559,
"s": 25205,
"text": "Efficient Approach : We can use direct formula for sum of first n numbers to reduce time. We can also use recursion. In this approach m = 1 will be our base condition and for any intermediate step SUM(n, m), we will call SUM (SUM(n, m-1), 1) and for a single step SUM(n, 1) = n * (n + 1) / 2 will be used. This will reduce our time complexity to O(m). "
},
{
"code": null,
"e": 25697,
"s": 25559,
"text": "int SUM (int n, int m)\n{\n if (m == 1)\n return (n * (n + 1) / 2);\n int sum = SUM(n, m-1);\n return (sum * (sum + 1) / 2);\n}"
},
{
"code": null,
"e": 25742,
"s": 25697,
"text": "Below is the implementation of above idea : "
},
{
"code": null,
"e": 25746,
"s": 25742,
"text": "C++"
},
{
"code": null,
"e": 25751,
"s": 25746,
"text": "Java"
},
{
"code": null,
"e": 25754,
"s": 25751,
"text": "C#"
},
{
"code": null,
"e": 25758,
"s": 25754,
"text": "PHP"
},
{
"code": null,
"e": 25769,
"s": 25758,
"text": "Javascript"
},
{
"code": "// CPP program to find m-th summation#include <bits/stdc++.h>using namespace std; // Function to return mth summationint SUM(int n, int m){ // base case if (m == 1) return (n * (n + 1) / 2); int sum = SUM(n, m-1); return (sum * (sum + 1) / 2);} // driver programint main(){ int n = 5; int m = 3; cout << \"SUM(\" << n << \", \" << m << \"): \" << SUM(n, m); return 0;}",
"e": 26182,
"s": 25769,
"text": null
},
{
"code": "// Java program to find m-th summation.class GFG { // Function to return mth summation static int SUM(int n, int m) { // base case if (m == 1) return (n * (n + 1) / 2); int sum = SUM(n, m - 1); return (sum * (sum + 1) / 2); } // Driver code public static void main(String[] args) { int n = 5; int m = 3; System.out.println(\"SUM(\" + n + \", \" + m + \"): \" + SUM(n, m)); }} // This code is contributed by Anant Agarwal.",
"e": 26753,
"s": 26182,
"text": null
},
{
"code": null,
"e": 26762,
"s": 26753,
"text": "Python3 "
},
{
"code": null,
"e": 27117,
"s": 26762,
"text": "\n# Python3 program to find m-th summation \n\n# Function to return mth summation\ndef SUM(n, m):\n\n # base case\n if (m == 1):\n return (n * (n + 1) / 2)\n \n sum = SUM(n, m-1)\n return int(sum * (sum + 1) / 2)\n\n\n# driver program\nn = 5\nm = 3\nprint(\"SUM(\", n, \", \", m, \"):\", SUM(n, m))\n\n# This code is contributed by Smitha Dinesh Semwal\n"
},
{
"code": "// C# program to find m-th summation.using System; class GFG{ // Function to return mth summation static int SUM(int n, int m) { // base case if (m == 1) return (n * (n + 1) / 2); int sum = SUM(n, m - 1); return (sum * (sum + 1) / 2); } // Driver Code public static void Main() { int n = 5; int m = 3; Console.Write(\"SUM(\" + n + \", \" + m + \"): \" + SUM(n, m)); }} // This code is contributed by Nitin Mittal.",
"e": 27682,
"s": 27117,
"text": null
},
{
"code": "<?php// PHP program to find m-th summation // Function to return// mth summationfunction SUM($n, $m){ // base case if ($m == 1) return ($n * ($n + 1) / 2); $sum = SUM($n, $m - 1); return ($sum * ($sum + 1) / 2);} // Driver Code $n = 5; $m = 3; echo \"SUM(\" , $n , \", \" , $m , \"): \" , SUM($n, $m); // This code is contributed by vt_m.?>",
"e": 28071,
"s": 27682,
"text": null
},
{
"code": "<script>// javascript program to find m-th summation // Function to return mth summationfunction SUM( n, m){ // base case if (m == 1) return (n * (n + 1) / 2); let sum = SUM(n, m-1); return (sum * (sum + 1) / 2);} // driver program let n = 5; let m = 3; document.write( \"SUM(\" + n + \", \" + m + \"): \" + SUM(n, m)); // This code contributed by Rajput-Ji </script>",
"e": 28481,
"s": 28071,
"text": null
},
{
"code": null,
"e": 28491,
"s": 28481,
"text": "Output: "
},
{
"code": null,
"e": 28507,
"s": 28491,
"text": "SUM(5, 3): 7260"
},
{
"code": null,
"e": 28947,
"s": 28507,
"text": "This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 28960,
"s": 28947,
"text": "nitin mittal"
},
{
"code": null,
"e": 28965,
"s": 28960,
"text": "vt_m"
},
{
"code": null,
"e": 28975,
"s": 28965,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 28988,
"s": 28975,
"text": "Mathematical"
},
{
"code": null,
"e": 28998,
"s": 28988,
"text": "Recursion"
},
{
"code": null,
"e": 29011,
"s": 28998,
"text": "Mathematical"
},
{
"code": null,
"e": 29021,
"s": 29011,
"text": "Recursion"
},
{
"code": null,
"e": 29119,
"s": 29021,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29128,
"s": 29119,
"text": "Comments"
},
{
"code": null,
"e": 29141,
"s": 29128,
"text": "Old Comments"
},
{
"code": null,
"e": 29186,
"s": 29141,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 29218,
"s": 29186,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 29262,
"s": 29218,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 29296,
"s": 29262,
"text": "Program to add two binary strings"
},
{
"code": null,
"e": 29329,
"s": 29296,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 29414,
"s": 29329,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 29424,
"s": 29414,
"text": "Recursion"
},
{
"code": null,
"e": 29451,
"s": 29424,
"text": "Program for Tower of Hanoi"
},
{
"code": null,
"e": 29499,
"s": 29451,
"text": "Program for Sum of the digits of a given number"
}
] |
Best practices for caching in Spark SQL | by David Vrba | Towards Data Science | In Spark SQL caching is a common technique for reusing some computation. It has the potential to speedup other queries that are using the same data, but there are some caveats that are good to keep in mind if we want to achieve good performance. In this article, we will take a look under the hood to see how caching works internally and we will try to demystify Spark's behavior related to data persistence.
In DataFrame API, there are two functions that can be used to cache a DataFrame, cache() and persist():
df.cache() # see in PySpark docs heredf.persist() # see in PySpark docs here
They are almost equivalent, the difference is that persist can take an optional argument storageLevel by which we can specify where the data will be persisted. The default value of the storageLevel for both functions is MEMORY_AND_DISK which means that the data will be stored in memory if there is space for it, otherwise, it will be stored on disk. Here you can see the (PySpark) documentation for other possible storage levels.
Caching is a lazy transformation, so immediately after calling the function nothing happens with the data but the query plan is updated by the Cache Manager by adding a new operator — InMemoryRelation. So this is just some information that will be used during the query execution later on when some action is called. Spark will look for the data in the caching layer and read it from there if it is available. If it doesn’t find the data in the caching layer (which happens for sure the first time the query runs), it will become responsible for getting the data there and it will use it immediately afterward.
The Cache Manager is responsible to keep track of what computation has already been cached in terms of the query plan. When the caching function is called, the Cache Manager is invoked directly under the hood and it pulls out the analyzed logical plan of the DataFrame on which the caching function is called and stores that plan in an indexed sequence called cachedData.
The phase of the Cache Manager is part of logical planning and it takes place after the analyzer and before the optimizer:
When you run a query with an action, the query plan will be processed and transformed. In the step of the Cache Manager (just before the optimizer) Spark will check for each subtree of the analyzed plan if it is stored in the cachedData sequence. If it finds a match it means that the same plan (the same computation) has already been cached (perhaps in some previous query) and so Spark can use that and thus it adds that information to the query plan using the InMemoryRelation operator which will carry information about this cached plan. This InMemoryRelation is then used in the phase of physical planning to create a physical operator— InMemoryTableScan.
df = spark.table("users").filter(col(col_name) > x).cache()df.count() # now check the query plan in Spark UI
Here in the above picture you can see graphical and string representation of a query which was using caching. To see what transformations were cached you need to look into the string representation of the plan because the graphical representation doesn’t show this information.
Let’s see a simple example to understand better how the Cache Manager works:
df = spark.read.parquet(data_path)df.select(col1, col2).filter(col2 > 0).cache()
Consider the following three queries. Which one of them will leverage the cached data?
1) df.filter(col2 > 0).select(col1, col2)2) df.select(col1, col2).filter(col2 > 10)3) df.select(col1).filter(col2 > 0)
The decisive factor is the analyzed logical plan. If it is the same as the analyzed plan of the cached query, then the cache will be leveraged. For query number 1 you might be tempted to say that it has the same plan because the filter will be pushed by the optimizer in both cases anyway. But this is actually not entirely accurate. The important thing to understand is that the phase of the Cache Manager takes place before the optimizer. What would be the same are the optimized plans but not analyzed plans. So query n. 1 will not leverage the cache simply because the analyzed plans are different.
For query n. 2 you might be again tempted to assume that it will use the cached data because the filter is more restrictive than the filter in the cached query. We can logically see that the queried data is in the cache, but Spark will not read it from there because of the same reason as before — the analyzed plans are different — this time the filtering condition is not the same. To use the cached data we can, however, fix the second query just by adding the filter there:
df.select(col1, col2).filter(col2 > 0).filter(col2 > 10)
At first sight, the filter col2 > 0 seems to be useless here, but it is not because now part of the analyzed logical plan will be identical with the cached plan and the Cache Manager will be able to find it and use the InMemoryRelation in the query plan.
Query number 3 is tricky, at first sight, it appears that it also will have a different analyzed plan because the query is different — we select only col1. The filtering condition is, however, using col2, which is not present in the previous projection and so the analyzer will invoke a rule ResolveMissingReferences and it will add col2 to the projection and the analyzed plan will actually become identical with the cached plan. This time the Cache Manager will find it and use it.
So the final answer is that query n. 3 will leverage the cached data.
Let’s list a couple of rules of thumb related to caching:
When you cache a DataFrame create a new variable for it cachedDF = df.cache(). This will allow you to bypass the problems that we were solving in our example, that sometimes it is not clear what is the analyzed plan and what was actually cached. Here whenever you call cachedDF.select(...) it will leverage the cached data.
Unpersist the DataFrame after it is no longer needed using cachedDF.unpersist(). If the caching layer becomes full, Spark will start evicting the data from memory using the LRU (least recently used) strategy. So it is good practice to use unpersist to stay more in control about what should be evicted. Also, the more space you have in memory the more can Spark use for execution, for instance, for building hash maps and so on.
Before you cache, make sure you are caching only what you will need in your queries. For example, if one query will use (col1, col2, col3) and the second query will use (col2, col3, col4), select a superset of these columns: cachedDF = df.select(col1, col2, col3, col4).cache(). It is not very useful to call cachedDF = df.cache() if the df contains lots of columns and only a small subset will be needed in follow-up queries.
Use the caching only if it makes sense. That is if the cached computation will be used multiple times. It is good to understand that putting the data to memory is also related to some overhead, so in some cases, it might be even faster to simply run the computation again if it is fast enough and not use caching at all as you can see in the next paragraph.
There are situations where caching doesn’t help at all and on the contrary slows down the execution. This is related for instance to queries based on large datasets stored in a columnar file format that supports column pruning and predicate pushdown such as parquet. Let’s consider the following example, in which we will cache the entire dataset and then run some queries on top of it. We will use the following dataset and cluster properties:
dataset size: 14.3GB in compressed parquet sitting on S3cluster size: 2 workers c5.4xlarge (32 cores together)platform: Databricks (runtime 6.6 wit Spark 2.4.5)
First, let’s measure the execution times for the queries where caching is not used:
df = spark.table(table_name)df.count() # runs 7.9sdf.filter(col("id") > xxx).count() # runs 18.2s
Now run the same queries with caching (the entire dataset doesn’t fit in memory and about 30% is cached on disk):
df = spark.table(table_name).cache()# this count will take long because it is putting data to memorydf.count() # runs 1.28mindf.count() # runs 14sdf.filter(col("id") > xxx).count() # runs 20.6s
No wonder that the first count takes 1.3min, there is the overhead related to putting data to memory. However, as you can see, also the second count and the query with the filter take longer for the cached dataset as compared to reading directly from parquet. It is a combination of two major reasons. The first one is the properties of the parquet file format — queries based on top of parquet are fast on its own. In the case of reading from parquet, Spark will read only the metadata to get the count so it doesn’t need to scan the entire dataset. For the filtering query, it will use column pruning and scan only the id column. On the other hand, when reading the data from the cache, Spark will read the entire dataset. This can be seen from Spark UI, where you can check the input size for the first stage (see the picture below).
The second reason is that the dataset is large and doesn’t fit entirely in ram. Part of the data is stored on disk as well and reading from the disk is much slower than reading from ram.
If you prefer using directly SQL instead of DataFrame DSL, you can still use caching, there are some differences, however.
spark.sql("cache table table_name")
The main difference is that using SQL the caching is eager by default, so a job will run immediately and will put the data to the caching layer. To make it lazy as it is in the DataFrame DSL we can use the lazy keyword explicitly:
spark.sql("cache lazy table table_name")
To remove the data from the cache, just call:
spark.sql("uncache table table_name")
Sometimes you may wonder what data is already cached. One possibility is to check Spark UI which provides some basic information about data that is already cached on the cluster.
Here for each cached dataset, you can see how much space it takes in memory or on disk. You can even zoom more and click on the record in the table which will take you to another page with details about each partition.
To check whether the entire table is cached we can use Catalog API:
spark.catalog.isCached("table_name")
The Catalog API can also be used to remove all data from the cache as follows:
spark.catalog.clearCache()
In Scala API you can also use the internal API of the Cache Manager which provides some functions, for instance, you can ask whether the Cache Manager is empty:
// In Scala API:val cm = spark.sharedState.cacheManagercm.isEmpty
Caching is one of more techniques that can be used for reusing some computation. Apart from caching there is also checkpointing and exchange-reuse.
The checkpointing is useful for instance in situations where we need to break the query plan because it is too large. A large query plan may become a bottleneck in the driver where it is processed because the processing of a very large plan will take to long. The checkpoint will however break the plan and materialize the query. For the next transformations, Spark will start building a new plan. The checkpointing is related to two functions checkpoint and localCheckpoint which differ by the storage used for the data.
The exchange-reuse where Spark persists the output of a shuffle on disk, is, on the other hand, a technique that can not be controlled directly by some API function, but instead, it is an internal feature that Spark handles on its own. In some special situations, it can be controlled indirectly by rewriting the query trying to achieve identical exchange branches. To read more about exchange-reuse, you can check my other article, where I describe it more in detail.
In this article, we tried to demystify Spark's behavior related to caching. We have seen how it works under the hood and what are the differences between using DSL vs SQL. We discussed some best practices on how to make caching as efficient as possible. On one example we showed that for big datasets that do not fit in memory, it might be faster to avoid caching especially if the data is stored in columnar file format. We also mentioned some alternatives to caching such as checkpointing or reused exchange that can be useful for data persistence in some situations. | [
{
"code": null,
"e": 581,
"s": 172,
"text": "In Spark SQL caching is a common technique for reusing some computation. It has the potential to speedup other queries that are using the same data, but there are some caveats that are good to keep in mind if we want to achieve good performance. In this article, we will take a look under the hood to see how caching works internally and we will try to demystify Spark's behavior related to data persistence."
},
{
"code": null,
"e": 685,
"s": 581,
"text": "In DataFrame API, there are two functions that can be used to cache a DataFrame, cache() and persist():"
},
{
"code": null,
"e": 762,
"s": 685,
"text": "df.cache() # see in PySpark docs heredf.persist() # see in PySpark docs here"
},
{
"code": null,
"e": 1193,
"s": 762,
"text": "They are almost equivalent, the difference is that persist can take an optional argument storageLevel by which we can specify where the data will be persisted. The default value of the storageLevel for both functions is MEMORY_AND_DISK which means that the data will be stored in memory if there is space for it, otherwise, it will be stored on disk. Here you can see the (PySpark) documentation for other possible storage levels."
},
{
"code": null,
"e": 1804,
"s": 1193,
"text": "Caching is a lazy transformation, so immediately after calling the function nothing happens with the data but the query plan is updated by the Cache Manager by adding a new operator — InMemoryRelation. So this is just some information that will be used during the query execution later on when some action is called. Spark will look for the data in the caching layer and read it from there if it is available. If it doesn’t find the data in the caching layer (which happens for sure the first time the query runs), it will become responsible for getting the data there and it will use it immediately afterward."
},
{
"code": null,
"e": 2176,
"s": 1804,
"text": "The Cache Manager is responsible to keep track of what computation has already been cached in terms of the query plan. When the caching function is called, the Cache Manager is invoked directly under the hood and it pulls out the analyzed logical plan of the DataFrame on which the caching function is called and stores that plan in an indexed sequence called cachedData."
},
{
"code": null,
"e": 2299,
"s": 2176,
"text": "The phase of the Cache Manager is part of logical planning and it takes place after the analyzer and before the optimizer:"
},
{
"code": null,
"e": 2960,
"s": 2299,
"text": "When you run a query with an action, the query plan will be processed and transformed. In the step of the Cache Manager (just before the optimizer) Spark will check for each subtree of the analyzed plan if it is stored in the cachedData sequence. If it finds a match it means that the same plan (the same computation) has already been cached (perhaps in some previous query) and so Spark can use that and thus it adds that information to the query plan using the InMemoryRelation operator which will carry information about this cached plan. This InMemoryRelation is then used in the phase of physical planning to create a physical operator— InMemoryTableScan."
},
{
"code": null,
"e": 3069,
"s": 2960,
"text": "df = spark.table(\"users\").filter(col(col_name) > x).cache()df.count() # now check the query plan in Spark UI"
},
{
"code": null,
"e": 3347,
"s": 3069,
"text": "Here in the above picture you can see graphical and string representation of a query which was using caching. To see what transformations were cached you need to look into the string representation of the plan because the graphical representation doesn’t show this information."
},
{
"code": null,
"e": 3424,
"s": 3347,
"text": "Let’s see a simple example to understand better how the Cache Manager works:"
},
{
"code": null,
"e": 3505,
"s": 3424,
"text": "df = spark.read.parquet(data_path)df.select(col1, col2).filter(col2 > 0).cache()"
},
{
"code": null,
"e": 3592,
"s": 3505,
"text": "Consider the following three queries. Which one of them will leverage the cached data?"
},
{
"code": null,
"e": 3711,
"s": 3592,
"text": "1) df.filter(col2 > 0).select(col1, col2)2) df.select(col1, col2).filter(col2 > 10)3) df.select(col1).filter(col2 > 0)"
},
{
"code": null,
"e": 4314,
"s": 3711,
"text": "The decisive factor is the analyzed logical plan. If it is the same as the analyzed plan of the cached query, then the cache will be leveraged. For query number 1 you might be tempted to say that it has the same plan because the filter will be pushed by the optimizer in both cases anyway. But this is actually not entirely accurate. The important thing to understand is that the phase of the Cache Manager takes place before the optimizer. What would be the same are the optimized plans but not analyzed plans. So query n. 1 will not leverage the cache simply because the analyzed plans are different."
},
{
"code": null,
"e": 4792,
"s": 4314,
"text": "For query n. 2 you might be again tempted to assume that it will use the cached data because the filter is more restrictive than the filter in the cached query. We can logically see that the queried data is in the cache, but Spark will not read it from there because of the same reason as before — the analyzed plans are different — this time the filtering condition is not the same. To use the cached data we can, however, fix the second query just by adding the filter there:"
},
{
"code": null,
"e": 4849,
"s": 4792,
"text": "df.select(col1, col2).filter(col2 > 0).filter(col2 > 10)"
},
{
"code": null,
"e": 5104,
"s": 4849,
"text": "At first sight, the filter col2 > 0 seems to be useless here, but it is not because now part of the analyzed logical plan will be identical with the cached plan and the Cache Manager will be able to find it and use the InMemoryRelation in the query plan."
},
{
"code": null,
"e": 5588,
"s": 5104,
"text": "Query number 3 is tricky, at first sight, it appears that it also will have a different analyzed plan because the query is different — we select only col1. The filtering condition is, however, using col2, which is not present in the previous projection and so the analyzer will invoke a rule ResolveMissingReferences and it will add col2 to the projection and the analyzed plan will actually become identical with the cached plan. This time the Cache Manager will find it and use it."
},
{
"code": null,
"e": 5658,
"s": 5588,
"text": "So the final answer is that query n. 3 will leverage the cached data."
},
{
"code": null,
"e": 5716,
"s": 5658,
"text": "Let’s list a couple of rules of thumb related to caching:"
},
{
"code": null,
"e": 6040,
"s": 5716,
"text": "When you cache a DataFrame create a new variable for it cachedDF = df.cache(). This will allow you to bypass the problems that we were solving in our example, that sometimes it is not clear what is the analyzed plan and what was actually cached. Here whenever you call cachedDF.select(...) it will leverage the cached data."
},
{
"code": null,
"e": 6469,
"s": 6040,
"text": "Unpersist the DataFrame after it is no longer needed using cachedDF.unpersist(). If the caching layer becomes full, Spark will start evicting the data from memory using the LRU (least recently used) strategy. So it is good practice to use unpersist to stay more in control about what should be evicted. Also, the more space you have in memory the more can Spark use for execution, for instance, for building hash maps and so on."
},
{
"code": null,
"e": 6896,
"s": 6469,
"text": "Before you cache, make sure you are caching only what you will need in your queries. For example, if one query will use (col1, col2, col3) and the second query will use (col2, col3, col4), select a superset of these columns: cachedDF = df.select(col1, col2, col3, col4).cache(). It is not very useful to call cachedDF = df.cache() if the df contains lots of columns and only a small subset will be needed in follow-up queries."
},
{
"code": null,
"e": 7254,
"s": 6896,
"text": "Use the caching only if it makes sense. That is if the cached computation will be used multiple times. It is good to understand that putting the data to memory is also related to some overhead, so in some cases, it might be even faster to simply run the computation again if it is fast enough and not use caching at all as you can see in the next paragraph."
},
{
"code": null,
"e": 7699,
"s": 7254,
"text": "There are situations where caching doesn’t help at all and on the contrary slows down the execution. This is related for instance to queries based on large datasets stored in a columnar file format that supports column pruning and predicate pushdown such as parquet. Let’s consider the following example, in which we will cache the entire dataset and then run some queries on top of it. We will use the following dataset and cluster properties:"
},
{
"code": null,
"e": 7860,
"s": 7699,
"text": "dataset size: 14.3GB in compressed parquet sitting on S3cluster size: 2 workers c5.4xlarge (32 cores together)platform: Databricks (runtime 6.6 wit Spark 2.4.5)"
},
{
"code": null,
"e": 7944,
"s": 7860,
"text": "First, let’s measure the execution times for the queries where caching is not used:"
},
{
"code": null,
"e": 8042,
"s": 7944,
"text": "df = spark.table(table_name)df.count() # runs 7.9sdf.filter(col(\"id\") > xxx).count() # runs 18.2s"
},
{
"code": null,
"e": 8156,
"s": 8042,
"text": "Now run the same queries with caching (the entire dataset doesn’t fit in memory and about 30% is cached on disk):"
},
{
"code": null,
"e": 8350,
"s": 8156,
"text": "df = spark.table(table_name).cache()# this count will take long because it is putting data to memorydf.count() # runs 1.28mindf.count() # runs 14sdf.filter(col(\"id\") > xxx).count() # runs 20.6s"
},
{
"code": null,
"e": 9187,
"s": 8350,
"text": "No wonder that the first count takes 1.3min, there is the overhead related to putting data to memory. However, as you can see, also the second count and the query with the filter take longer for the cached dataset as compared to reading directly from parquet. It is a combination of two major reasons. The first one is the properties of the parquet file format — queries based on top of parquet are fast on its own. In the case of reading from parquet, Spark will read only the metadata to get the count so it doesn’t need to scan the entire dataset. For the filtering query, it will use column pruning and scan only the id column. On the other hand, when reading the data from the cache, Spark will read the entire dataset. This can be seen from Spark UI, where you can check the input size for the first stage (see the picture below)."
},
{
"code": null,
"e": 9374,
"s": 9187,
"text": "The second reason is that the dataset is large and doesn’t fit entirely in ram. Part of the data is stored on disk as well and reading from the disk is much slower than reading from ram."
},
{
"code": null,
"e": 9497,
"s": 9374,
"text": "If you prefer using directly SQL instead of DataFrame DSL, you can still use caching, there are some differences, however."
},
{
"code": null,
"e": 9533,
"s": 9497,
"text": "spark.sql(\"cache table table_name\")"
},
{
"code": null,
"e": 9764,
"s": 9533,
"text": "The main difference is that using SQL the caching is eager by default, so a job will run immediately and will put the data to the caching layer. To make it lazy as it is in the DataFrame DSL we can use the lazy keyword explicitly:"
},
{
"code": null,
"e": 9805,
"s": 9764,
"text": "spark.sql(\"cache lazy table table_name\")"
},
{
"code": null,
"e": 9851,
"s": 9805,
"text": "To remove the data from the cache, just call:"
},
{
"code": null,
"e": 9889,
"s": 9851,
"text": "spark.sql(\"uncache table table_name\")"
},
{
"code": null,
"e": 10068,
"s": 9889,
"text": "Sometimes you may wonder what data is already cached. One possibility is to check Spark UI which provides some basic information about data that is already cached on the cluster."
},
{
"code": null,
"e": 10287,
"s": 10068,
"text": "Here for each cached dataset, you can see how much space it takes in memory or on disk. You can even zoom more and click on the record in the table which will take you to another page with details about each partition."
},
{
"code": null,
"e": 10355,
"s": 10287,
"text": "To check whether the entire table is cached we can use Catalog API:"
},
{
"code": null,
"e": 10392,
"s": 10355,
"text": "spark.catalog.isCached(\"table_name\")"
},
{
"code": null,
"e": 10471,
"s": 10392,
"text": "The Catalog API can also be used to remove all data from the cache as follows:"
},
{
"code": null,
"e": 10498,
"s": 10471,
"text": "spark.catalog.clearCache()"
},
{
"code": null,
"e": 10659,
"s": 10498,
"text": "In Scala API you can also use the internal API of the Cache Manager which provides some functions, for instance, you can ask whether the Cache Manager is empty:"
},
{
"code": null,
"e": 10725,
"s": 10659,
"text": "// In Scala API:val cm = spark.sharedState.cacheManagercm.isEmpty"
},
{
"code": null,
"e": 10873,
"s": 10725,
"text": "Caching is one of more techniques that can be used for reusing some computation. Apart from caching there is also checkpointing and exchange-reuse."
},
{
"code": null,
"e": 11395,
"s": 10873,
"text": "The checkpointing is useful for instance in situations where we need to break the query plan because it is too large. A large query plan may become a bottleneck in the driver where it is processed because the processing of a very large plan will take to long. The checkpoint will however break the plan and materialize the query. For the next transformations, Spark will start building a new plan. The checkpointing is related to two functions checkpoint and localCheckpoint which differ by the storage used for the data."
},
{
"code": null,
"e": 11864,
"s": 11395,
"text": "The exchange-reuse where Spark persists the output of a shuffle on disk, is, on the other hand, a technique that can not be controlled directly by some API function, but instead, it is an internal feature that Spark handles on its own. In some special situations, it can be controlled indirectly by rewriting the query trying to achieve identical exchange branches. To read more about exchange-reuse, you can check my other article, where I describe it more in detail."
}
] |
C library function - gmtime() | The C library function struct tm *gmtime(const time_t *timer) uses the value pointed by timer to fill a tm structure with the values that represent the corresponding time, expressed in Coordinated Universal Time (UTC) or GMT timezone.
Following is the declaration for gmtime() function.
struct tm *gmtime(const time_t *timer)
timeptr − This is the pointer to a time_t value representing a calendar time.
timeptr − This is the pointer to a time_t value representing a calendar time.
This function returns pointer to a tm structure with the time information filled in. Below is the detail of timeptr structure −
struct tm {
int tm_sec; /* seconds, range 0 to 59 */
int tm_min; /* minutes, range 0 to 59 */
int tm_hour; /* hours, range 0 to 23 */
int tm_mday; /* day of the month, range 1 to 31 */
int tm_mon; /* month, range 0 to 11 */
int tm_year; /* The number of years since 1900 */
int tm_wday; /* day of the week, range 0 to 6 */
int tm_yday; /* day in the year, range 0 to 365 */
int tm_isdst; /* daylight saving time */
};
The following example shows the usage of gmtime() function.
#include <stdio.h>
#include <time.h>
#define BST (+1)
#define CCT (+8)
int main () {
time_t rawtime;
struct tm *info;
time(&rawtime);
/* Get GMT time */
info = gmtime(&rawtime );
printf("Current world clock:\n");
printf("London : %2d:%02d\n", (info->tm_hour+BST)%24, info->tm_min);
printf("China : %2d:%02d\n", (info->tm_hour+CCT)%24, info->tm_min);
return(0);
}
Let us compile and run the above program that will produce the following result −
Current world clock:
London : 14:10
China : 21:10
12 Lectures
2 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
12 Lectures
2 hours
Richa Maheshwari
20 Lectures
3.5 hours
Vandana Annavaram
44 Lectures
1 hours
Amit Diwan
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2242,
"s": 2007,
"text": "The C library function struct tm *gmtime(const time_t *timer) uses the value pointed by timer to fill a tm structure with the values that represent the corresponding time, expressed in Coordinated Universal Time (UTC) or GMT timezone."
},
{
"code": null,
"e": 2294,
"s": 2242,
"text": "Following is the declaration for gmtime() function."
},
{
"code": null,
"e": 2333,
"s": 2294,
"text": "struct tm *gmtime(const time_t *timer)"
},
{
"code": null,
"e": 2411,
"s": 2333,
"text": "timeptr − This is the pointer to a time_t value representing a calendar time."
},
{
"code": null,
"e": 2489,
"s": 2411,
"text": "timeptr − This is the pointer to a time_t value representing a calendar time."
},
{
"code": null,
"e": 2617,
"s": 2489,
"text": "This function returns pointer to a tm structure with the time information filled in. Below is the detail of timeptr structure −"
},
{
"code": null,
"e": 3191,
"s": 2617,
"text": "struct tm {\n int tm_sec; /* seconds, range 0 to 59 */\n int tm_min; /* minutes, range 0 to 59 */\n int tm_hour; /* hours, range 0 to 23 */\n int tm_mday; /* day of the month, range 1 to 31 */\n int tm_mon; /* month, range 0 to 11 */\n int tm_year; /* The number of years since 1900 */\n int tm_wday; /* day of the week, range 0 to 6 */\n int tm_yday; /* day in the year, range 0 to 365 */\n int tm_isdst; /* daylight saving time */\t\n};"
},
{
"code": null,
"e": 3251,
"s": 3191,
"text": "The following example shows the usage of gmtime() function."
},
{
"code": null,
"e": 3651,
"s": 3251,
"text": "#include <stdio.h>\n#include <time.h>\n\n#define BST (+1)\n#define CCT (+8)\n\nint main () {\n\n time_t rawtime;\n struct tm *info;\n\n time(&rawtime);\n /* Get GMT time */\n info = gmtime(&rawtime );\n \n printf(\"Current world clock:\\n\");\n printf(\"London : %2d:%02d\\n\", (info->tm_hour+BST)%24, info->tm_min);\n printf(\"China : %2d:%02d\\n\", (info->tm_hour+CCT)%24, info->tm_min);\n\n return(0);\n}"
},
{
"code": null,
"e": 3733,
"s": 3651,
"text": "Let us compile and run the above program that will produce the following result −"
},
{
"code": null,
"e": 3784,
"s": 3733,
"text": "Current world clock:\nLondon : 14:10\nChina : 21:10\n"
},
{
"code": null,
"e": 3817,
"s": 3784,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3832,
"s": 3817,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3867,
"s": 3832,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3882,
"s": 3867,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3917,
"s": 3882,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3931,
"s": 3917,
"text": " Asif Hussain"
},
{
"code": null,
"e": 3964,
"s": 3931,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3982,
"s": 3964,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 4017,
"s": 3982,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4036,
"s": 4017,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 4069,
"s": 4036,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4081,
"s": 4069,
"text": " Amit Diwan"
},
{
"code": null,
"e": 4088,
"s": 4081,
"text": " Print"
},
{
"code": null,
"e": 4099,
"s": 4088,
"text": " Add Notes"
}
] |
Concurrent data pipelines in golang | Towards Data Science | Data is a vital piece for all applications. Applications mainly receive data, process it and then create some sort of output out of it. The amount of data that is available nowadays is immense, which brings many challenges when trying to make sense out of it and transforming it into useful information. Besides the usual data system process, we also have to consider the data that is generated by the execution of such systems, like logs and metrics. Everything is data.
Therefore, there’s a growing need for data driven applications. It’s not unusual to have systems only dealing with moving and transforming data. From one place to another or from one structure to another. That is even more common in distributed systems, because each system generates data for their own purpose, structured the way it’s easier for them to process. However, those systems still have to communicate, so the data has to be transformed and moved. Moreover, sometimes the data has to be transferred to a different environment, or to a different platform. Even more trouble!
There are very sophisticated tools to do this job, but very often they are a real pain to configure and maintain, not to mention the costs involved. Thus they are not always the best option. Some times, depending on the use case, you can create your own pipelines to move data with a simpler solution. In this article we are going to see how to build data pipelines using golang.
Pipelines are a really good way to express how we want to deal with data. By definition, pipelines are a sequence of steps or actions that are executed. Usually the output of a previous step is used as the input for the following step. When pipelines are designed, each step doesn’t have to worry about other steps’ work, relying only on the inputs and outputs contracts. This makes the design very robust, as it’s based on contracts and abstractions. Also it’s a very flexible design as you can add more steps as long as you don’t break the contracts. Fun!
There are countless ways of doing it. In this article we will focus on how we can leverage go’s concurrency model, which I wrote about here, to create data pipelines.
As we mentioned earlier, data pipelines are a sequence of steps that are executed using the output of a previous step as the input for the next one. That sound like a really good usage for goroutines and channels. We can create each step as a goroutine, and the communications between them as channels. It means that our data pipeline can execute concurrently, which is a great benefit if used wisely. Let’s jump to an example to make things easier.
In this example we are going to create a simple pipeline for reading some GUID’s from a text file, transform them into the input data structure we are going to use for processing, fetch related data from an external service and finally persist the data in a data storage using a batch operation. Here’s what the high level workflow looks like:
As we can see on this diagram, each operation is going to be created using a goroutine (represented by gophers) and tied together using channels. The whole idea on how to do that is that each function (besides the data generator) will receive its input channel as parameter and return the output channel as the return value of the function. Inside each function we are going to spin a goroutine to actually listen to the input channel and act on each one of the items received, as well as send the result on the output channel.
All channels are unbuffered for simplicity, it means that each one of the GUID’s stored on the guids.txt file will pass trough the pipeline individually. The only batch operation will be at the very end, where we persist them into batches to the data storage. Also for simplicity the error handling has been simplified, bear in mind that for a production pipeline you would want to make it more robust. Alright, enough explanation, let’s get cracking with this example. You can find the entire source code in my github repository.
Here’s what the guids.txt file looks like:
ea464197-d864-4f8a-8a60-2d3a6f3d87bf74c1a7bd-b536-4f9e-be36-5e16c491d833c524c1e9-e473-42eb-b74d-97d82575b720d5003029-7e10-4128-8a18-392e384ef0bdb1fbf405-7b3c-4b82-8b51-4c5c2c0cca56b4f6a28c-86b2-4741-89e5-612451346eb7353629f7-c9ba-4ed1-8e1b-b7694381a36ad3b305cb-eb1b-4f8a-8a23-4741960c26a466c03c1a-45f7-4255-b568-669d9dc553d99272d9f4-da5a-4449-8826-f8529ce4f428
The first piece of our pipeline is to read each line of that file, parse it into auuid.UUID type and send it over on a channel. Here’s how this function can look like:
The important part here is that we are creating the output channel (line 13) and returning it (line 37), as well as using it on the goroutine that actually does the job of reading the file and sending the parsed uuid.UUID values (line 15). That is very powerful, because it allow us to use that channel as input for another function straight away, without worrying on how the internal job is done. Also important is the fact that we are closing the channel once the job is done, this way we can safely use the for range statement on that channel without worrying about infinite loops. Let’s jump on to our second step, preparing the data:
Here the function signature changes slightly. We are receiving the channel we want to use as input. However the internal technique of creating the channel output channel (line 16) and returning it (line 26) is still the same. For this specific step we are only using the uuid.UUID received on the input channel and transforming them into a dummy struct inputData as well as logging what is being processed. This is a very basic example, but it illustrates what you can do for data transforming (a very common step in data pipelines) you only have to change apply the same logic for any struct you want. Let’s check a more in depth example with our third step, data fetching:
This function uses pretty much the same technique as before, we receive an input channel and return an output channel. In this case I decided to emulate the external call for simplicity, so we are actually generating in memory random related values for a given GUID. The interesting thing here is that we are actually using concurrency to call this (fake) external service. This allows the rest of the pipeline to still run while we are waiting for a specific value to return form the external value. We still want to wait for all the calls to the external service to finish before closing our output channel (saying that our job for this piece of the pipeline is done).
To do that I introduced a very common pattern when working with asynchronous calls that need to be synchronised back at some point, using sync.WaitGroup. We wait (synchronise) right before calling the close(oc) on line 29. This way we can make sure that all calls to the external service are finished before closing the channel. It happens because this specific step may run slower than the prior step on the data pipeline, as it depends on external services, so all values may be received from the input channel before we can process all of them, calling the external service.
That was a very interesting step, let’s have a look on the last step of our pipeline, the data store:
In this step we are introducing a different technique, batching. This may be useful for services where calling each operation for each item is not very efficient in terms of performance or cost. So in order to workaround that we can batch some items together. I created a simple batching mechanism based on the amount of data we want to add to the batch. You can use any mechanism you want, I’m sure the logic will be very similar. In this case we are batching 7 items at once, so every time we have 7 items to persist to the database, we call the persisting function (fake) and open the next batch. Before finishing we are checking if there is an open batch and save it in that case. Also we are returning a channel with the information of what items were saved and a timestamp. Now we only need to put this pipeline together:
As you can see we call the pipeline in a reversed order. You can change the parameters to make it more clear if you want. However for this case it is working almost like a decorator pattern. If we start with the generateData() function, that is the one that receives no channels but returns one. So the returned channel from that function is used as input parameter for prepareData. The output channel from that function is used as parameter for the fetchData. The output channel is used finally by saveData as input. The last function also returns a channel, that we are going to range over to print which items have been saved. If we execute this example, we are going to see something like:
./data-pipeline-golang2020/06/10 09:49:50 Data ready for processing: {id:ea464197-d864-4f8a-8a60-2d3a6f3d87bf timestamp:1591778990056111000}2020/06/10 09:49:50 Data ready for processing: {id:74c1a7bd-b536-4f9e-be36-5e16c491d833 timestamp:1591778990056467000}2020/06/10 09:49:50 Data ready for processing: {id:c524c1e9-e473-42eb-b74d-97d82575b720 timestamp:1591778990056587000}2020/06/10 09:49:50 Data ready for processing: {id:d5003029-7e10-4128-8a18-392e384ef0bd timestamp:1591778990056744000}2020/06/10 09:49:50 Data ready for processing: {id:b1fbf405-7b3c-4b82-8b51-4c5c2c0cca56 timestamp:1591778990056773000}2020/06/10 09:49:50 Data ready for processing: {id:b4f6a28c-86b2-4741-89e5-612451346eb7 timestamp:1591778990056803000}2020/06/10 09:49:50 Data ready for processing: {id:353629f7-c9ba-4ed1-8e1b-b7694381a36a timestamp:1591778990056814000}2020/06/10 09:49:50 Data ready for processing: {id:d3b305cb-eb1b-4f8a-8a23-4741960c26a4 timestamp:1591778990056984000}2020/06/10 09:49:50 Data ready for processing: {id:66c03c1a-45f7-4255-b568-669d9dc553d9 timestamp:1591778990057220000}2020/06/10 09:49:50 Items saved: {idsSaved:[66c03c1a-45f7-4255-b568-669d9dc553d9 c524c1e9-e473-42eb-b74d-97d82575b720 353629f7-c9ba-4ed1-8e1b-b7694381a36a b4f6a28c-86b2-4741-89e5-612451346eb7 74c1a7bd-b536-4f9e-be36-5e16c491d833 b1fbf405-7b3c-4b82-8b51-4c5c2c0cca56 ea464197-d864-4f8a-8a60-2d3a6f3d87bf] timestamp:1591778990097935000}2020/06/10 09:49:50 Items saved: {idsSaved:[d3b305cb-eb1b-4f8a-8a23-4741960c26a4 d5003029-7e10-4128-8a18-392e384ef0bd] timestamp:1591778990105146000}
We can see that the prepareData function logged 9 items that were ready for being processed, and the main function logged that 2 batches were actually saved, the first one containing 7 items and the second one containing 2 items.
Creating data pipelines is a very common task for engineers dealing with data driven or data intensive applications. Data pipelines are essential to transform and move data from one system to another, one platform to another or even one environment to another. If we understand golang’s concurrency model we can leverage that to create concurrent data pipelines in a very clean and easy way. The main pattern used here is to create and return a channel for each step, this way we can easily pipe all steps together. Using this paradigm we can boost our pipeline with all sort of cools things, like parallel execution for steps, multiple workers for a specific pipeline step, so on.
This technique is not always the right choice, and there are many tools available out there that can be an easier solution depending on each case. | [
{
"code": null,
"e": 518,
"s": 46,
"text": "Data is a vital piece for all applications. Applications mainly receive data, process it and then create some sort of output out of it. The amount of data that is available nowadays is immense, which brings many challenges when trying to make sense out of it and transforming it into useful information. Besides the usual data system process, we also have to consider the data that is generated by the execution of such systems, like logs and metrics. Everything is data."
},
{
"code": null,
"e": 1103,
"s": 518,
"text": "Therefore, there’s a growing need for data driven applications. It’s not unusual to have systems only dealing with moving and transforming data. From one place to another or from one structure to another. That is even more common in distributed systems, because each system generates data for their own purpose, structured the way it’s easier for them to process. However, those systems still have to communicate, so the data has to be transformed and moved. Moreover, sometimes the data has to be transferred to a different environment, or to a different platform. Even more trouble!"
},
{
"code": null,
"e": 1483,
"s": 1103,
"text": "There are very sophisticated tools to do this job, but very often they are a real pain to configure and maintain, not to mention the costs involved. Thus they are not always the best option. Some times, depending on the use case, you can create your own pipelines to move data with a simpler solution. In this article we are going to see how to build data pipelines using golang."
},
{
"code": null,
"e": 2041,
"s": 1483,
"text": "Pipelines are a really good way to express how we want to deal with data. By definition, pipelines are a sequence of steps or actions that are executed. Usually the output of a previous step is used as the input for the following step. When pipelines are designed, each step doesn’t have to worry about other steps’ work, relying only on the inputs and outputs contracts. This makes the design very robust, as it’s based on contracts and abstractions. Also it’s a very flexible design as you can add more steps as long as you don’t break the contracts. Fun!"
},
{
"code": null,
"e": 2208,
"s": 2041,
"text": "There are countless ways of doing it. In this article we will focus on how we can leverage go’s concurrency model, which I wrote about here, to create data pipelines."
},
{
"code": null,
"e": 2658,
"s": 2208,
"text": "As we mentioned earlier, data pipelines are a sequence of steps that are executed using the output of a previous step as the input for the next one. That sound like a really good usage for goroutines and channels. We can create each step as a goroutine, and the communications between them as channels. It means that our data pipeline can execute concurrently, which is a great benefit if used wisely. Let’s jump to an example to make things easier."
},
{
"code": null,
"e": 3002,
"s": 2658,
"text": "In this example we are going to create a simple pipeline for reading some GUID’s from a text file, transform them into the input data structure we are going to use for processing, fetch related data from an external service and finally persist the data in a data storage using a batch operation. Here’s what the high level workflow looks like:"
},
{
"code": null,
"e": 3530,
"s": 3002,
"text": "As we can see on this diagram, each operation is going to be created using a goroutine (represented by gophers) and tied together using channels. The whole idea on how to do that is that each function (besides the data generator) will receive its input channel as parameter and return the output channel as the return value of the function. Inside each function we are going to spin a goroutine to actually listen to the input channel and act on each one of the items received, as well as send the result on the output channel."
},
{
"code": null,
"e": 4061,
"s": 3530,
"text": "All channels are unbuffered for simplicity, it means that each one of the GUID’s stored on the guids.txt file will pass trough the pipeline individually. The only batch operation will be at the very end, where we persist them into batches to the data storage. Also for simplicity the error handling has been simplified, bear in mind that for a production pipeline you would want to make it more robust. Alright, enough explanation, let’s get cracking with this example. You can find the entire source code in my github repository."
},
{
"code": null,
"e": 4104,
"s": 4061,
"text": "Here’s what the guids.txt file looks like:"
},
{
"code": null,
"e": 4465,
"s": 4104,
"text": "ea464197-d864-4f8a-8a60-2d3a6f3d87bf74c1a7bd-b536-4f9e-be36-5e16c491d833c524c1e9-e473-42eb-b74d-97d82575b720d5003029-7e10-4128-8a18-392e384ef0bdb1fbf405-7b3c-4b82-8b51-4c5c2c0cca56b4f6a28c-86b2-4741-89e5-612451346eb7353629f7-c9ba-4ed1-8e1b-b7694381a36ad3b305cb-eb1b-4f8a-8a23-4741960c26a466c03c1a-45f7-4255-b568-669d9dc553d99272d9f4-da5a-4449-8826-f8529ce4f428"
},
{
"code": null,
"e": 4633,
"s": 4465,
"text": "The first piece of our pipeline is to read each line of that file, parse it into auuid.UUID type and send it over on a channel. Here’s how this function can look like:"
},
{
"code": null,
"e": 5272,
"s": 4633,
"text": "The important part here is that we are creating the output channel (line 13) and returning it (line 37), as well as using it on the goroutine that actually does the job of reading the file and sending the parsed uuid.UUID values (line 15). That is very powerful, because it allow us to use that channel as input for another function straight away, without worrying on how the internal job is done. Also important is the fact that we are closing the channel once the job is done, this way we can safely use the for range statement on that channel without worrying about infinite loops. Let’s jump on to our second step, preparing the data:"
},
{
"code": null,
"e": 5947,
"s": 5272,
"text": "Here the function signature changes slightly. We are receiving the channel we want to use as input. However the internal technique of creating the channel output channel (line 16) and returning it (line 26) is still the same. For this specific step we are only using the uuid.UUID received on the input channel and transforming them into a dummy struct inputData as well as logging what is being processed. This is a very basic example, but it illustrates what you can do for data transforming (a very common step in data pipelines) you only have to change apply the same logic for any struct you want. Let’s check a more in depth example with our third step, data fetching:"
},
{
"code": null,
"e": 6618,
"s": 5947,
"text": "This function uses pretty much the same technique as before, we receive an input channel and return an output channel. In this case I decided to emulate the external call for simplicity, so we are actually generating in memory random related values for a given GUID. The interesting thing here is that we are actually using concurrency to call this (fake) external service. This allows the rest of the pipeline to still run while we are waiting for a specific value to return form the external value. We still want to wait for all the calls to the external service to finish before closing our output channel (saying that our job for this piece of the pipeline is done)."
},
{
"code": null,
"e": 7196,
"s": 6618,
"text": "To do that I introduced a very common pattern when working with asynchronous calls that need to be synchronised back at some point, using sync.WaitGroup. We wait (synchronise) right before calling the close(oc) on line 29. This way we can make sure that all calls to the external service are finished before closing the channel. It happens because this specific step may run slower than the prior step on the data pipeline, as it depends on external services, so all values may be received from the input channel before we can process all of them, calling the external service."
},
{
"code": null,
"e": 7298,
"s": 7196,
"text": "That was a very interesting step, let’s have a look on the last step of our pipeline, the data store:"
},
{
"code": null,
"e": 8126,
"s": 7298,
"text": "In this step we are introducing a different technique, batching. This may be useful for services where calling each operation for each item is not very efficient in terms of performance or cost. So in order to workaround that we can batch some items together. I created a simple batching mechanism based on the amount of data we want to add to the batch. You can use any mechanism you want, I’m sure the logic will be very similar. In this case we are batching 7 items at once, so every time we have 7 items to persist to the database, we call the persisting function (fake) and open the next batch. Before finishing we are checking if there is an open batch and save it in that case. Also we are returning a channel with the information of what items were saved and a timestamp. Now we only need to put this pipeline together:"
},
{
"code": null,
"e": 8820,
"s": 8126,
"text": "As you can see we call the pipeline in a reversed order. You can change the parameters to make it more clear if you want. However for this case it is working almost like a decorator pattern. If we start with the generateData() function, that is the one that receives no channels but returns one. So the returned channel from that function is used as input parameter for prepareData. The output channel from that function is used as parameter for the fetchData. The output channel is used finally by saveData as input. The last function also returns a channel, that we are going to range over to print which items have been saved. If we execute this example, we are going to see something like:"
},
{
"code": null,
"e": 10388,
"s": 8820,
"text": "./data-pipeline-golang2020/06/10 09:49:50 Data ready for processing: {id:ea464197-d864-4f8a-8a60-2d3a6f3d87bf timestamp:1591778990056111000}2020/06/10 09:49:50 Data ready for processing: {id:74c1a7bd-b536-4f9e-be36-5e16c491d833 timestamp:1591778990056467000}2020/06/10 09:49:50 Data ready for processing: {id:c524c1e9-e473-42eb-b74d-97d82575b720 timestamp:1591778990056587000}2020/06/10 09:49:50 Data ready for processing: {id:d5003029-7e10-4128-8a18-392e384ef0bd timestamp:1591778990056744000}2020/06/10 09:49:50 Data ready for processing: {id:b1fbf405-7b3c-4b82-8b51-4c5c2c0cca56 timestamp:1591778990056773000}2020/06/10 09:49:50 Data ready for processing: {id:b4f6a28c-86b2-4741-89e5-612451346eb7 timestamp:1591778990056803000}2020/06/10 09:49:50 Data ready for processing: {id:353629f7-c9ba-4ed1-8e1b-b7694381a36a timestamp:1591778990056814000}2020/06/10 09:49:50 Data ready for processing: {id:d3b305cb-eb1b-4f8a-8a23-4741960c26a4 timestamp:1591778990056984000}2020/06/10 09:49:50 Data ready for processing: {id:66c03c1a-45f7-4255-b568-669d9dc553d9 timestamp:1591778990057220000}2020/06/10 09:49:50 Items saved: {idsSaved:[66c03c1a-45f7-4255-b568-669d9dc553d9 c524c1e9-e473-42eb-b74d-97d82575b720 353629f7-c9ba-4ed1-8e1b-b7694381a36a b4f6a28c-86b2-4741-89e5-612451346eb7 74c1a7bd-b536-4f9e-be36-5e16c491d833 b1fbf405-7b3c-4b82-8b51-4c5c2c0cca56 ea464197-d864-4f8a-8a60-2d3a6f3d87bf] timestamp:1591778990097935000}2020/06/10 09:49:50 Items saved: {idsSaved:[d3b305cb-eb1b-4f8a-8a23-4741960c26a4 d5003029-7e10-4128-8a18-392e384ef0bd] timestamp:1591778990105146000}"
},
{
"code": null,
"e": 10618,
"s": 10388,
"text": "We can see that the prepareData function logged 9 items that were ready for being processed, and the main function logged that 2 batches were actually saved, the first one containing 7 items and the second one containing 2 items."
},
{
"code": null,
"e": 11300,
"s": 10618,
"text": "Creating data pipelines is a very common task for engineers dealing with data driven or data intensive applications. Data pipelines are essential to transform and move data from one system to another, one platform to another or even one environment to another. If we understand golang’s concurrency model we can leverage that to create concurrent data pipelines in a very clean and easy way. The main pattern used here is to create and return a channel for each step, this way we can easily pipe all steps together. Using this paradigm we can boost our pipeline with all sort of cools things, like parallel execution for steps, multiple workers for a specific pipeline step, so on."
}
] |
Understanding and Writing your first Text Mining Script with R | by Lorna Maria A | Towards Data Science | One of the reasons data science has become popular is because of it’s ability to reveal so much information on large data sets in a split second or just a query.
Think about it deeply ,on a daily basis how much information in form of text do we give out? All this information contains our sentiments,our opinions ,our plans ,pieces of advice ,our favourite phrase among other things.
However revealing each of those this can seem like finding a needle from a haystack at a glance ,until we use techniques like text mining/analysis .
Text mining takes in account information retrieval ,analysis and study of word frequencies and pattern recognition to aid visualisation and predictive analytics.
In this article ,We go through the major steps that a data set undergoes to get ready for further analysis.we shall write our script using R and the code will be written in R studio .
To achieve our goal ,we shall use an R package called “tm”.This package supports all text mining functions like loading data,cleaning data and building a term matrix.It is available on CRAN.
#downloading and installing the package from CRANinstall.packages("tm")#loading tmlibrary(tm)
Text to be mined can be loaded into R from different source formats.It can come from text files(.txt),pdfs (.pdf),csv files(.csv) e.t.c ,but no matter the source format ,to be used in the tm package it is turned into a “corpus”.
A corpus is defined as “a collection of written texts, especially the entire works of a particular author or a body of writing on a particular subject”.
The tm package use the Corpus() function to create a corpus.
#loading a text file from local computernewdata<- readlines(filepath)#Load data as corpus#VectorSource() creates character vectorsmydata <- Corpus(VectorSource(newdata))
Refer to this guide to learn more about importing files into R.
Once we have successfully loaded the data into the work space,it is time to clean this data .Our goal at this step is to create independent terms(words) from the data file before we can start counting how frequent they appear.
Since R is case sensitive ,we shall first convert the entire text to lowercase to avoid considering same words like “write” and “Write” differently.
We shall remove : URLs ,emojis,non-english words,punctuations,numbers,whitespace and stop words.
Stop words: The commonly used english words like “a”,” is ”,”the” in the tm package are referred to as stop words. These words have to be eliminated so as to render the results more accurate.It is also possible to create your own custom stop words.
# convert to lower casemydata <- tm_map(mydata, content_transformer(tolower))#remove ������ what would be emojismydata<-tm_map(mydata, content_transformer(gsub), pattern="\\W",replace=" ")# remove URLsremoveURL <- function(x) gsub("http[^[:space:]]*", "", x)mydata <- tm_map(mydata, content_transformer(removeURL))# remove anything other than English letters or spaceremoveNumPunct <- function(x) gsub("[^[:alpha:][:space:]]*", "", x)mydata <- tm_map(mydata, content_transformer(removeNumPunct))# remove stopwordsmydata <- tm_map(mydata, removeWords, stopwords("english"))#u can create custom stop words using the code below.#myStopwords <- c(setdiff(stopwords('english'), c("r", "big")),"use", "see", "used", "via", "amp")#mydata <- tm_map(mydata, removeWords, myStopwords)# remove extra whitespacemydata <- tm_map(mydata, stripWhitespace)# Remove numbersmydata <- tm_map(mydata, removeNumbers)# Remove punctuationsmydata <- tm_map(mydata, removePunctuation)
Stemming is the process of gathering words of similar origin into one word for example “communication”, “communicates”, “communicate”. Stemming helps us increase accuracy in our mined text by removing suffixes and reducing words to their basic forms.We shall use the SnowballC library.
library(SnowballC)mydata <- tm_map(mydata, stemDocument)
After the cleaning process ,we are left with independent terms that exist throughout the document.These are stored in a matrix that shows each of their occurrence. This matrix logs the number of times the term appears in our clean data set thus being called a term matrix.
#create a term matrix and store it as dtmdtm <- TermDocumentMatrix(mydata)
Word frequencies : These are the number of times words appear in data set.Word frequencies will indicate to us from the most frequently used words in the data set to the least used using the compilation of occurrences from the term matrix.
We have just written a basic text mining script ,however it is just the beginning of text mining.The ability to get the text in its raw format and clean it to this point will give us direction to things like building a word cloud,sentiment analysis and building models.
Hold on to this script because it will come in handy when we start doing sentiment analysis.
Feel free to reach out to me with any question > @lornamariak . | [
{
"code": null,
"e": 209,
"s": 47,
"text": "One of the reasons data science has become popular is because of it’s ability to reveal so much information on large data sets in a split second or just a query."
},
{
"code": null,
"e": 431,
"s": 209,
"text": "Think about it deeply ,on a daily basis how much information in form of text do we give out? All this information contains our sentiments,our opinions ,our plans ,pieces of advice ,our favourite phrase among other things."
},
{
"code": null,
"e": 580,
"s": 431,
"text": "However revealing each of those this can seem like finding a needle from a haystack at a glance ,until we use techniques like text mining/analysis ."
},
{
"code": null,
"e": 742,
"s": 580,
"text": "Text mining takes in account information retrieval ,analysis and study of word frequencies and pattern recognition to aid visualisation and predictive analytics."
},
{
"code": null,
"e": 926,
"s": 742,
"text": "In this article ,We go through the major steps that a data set undergoes to get ready for further analysis.we shall write our script using R and the code will be written in R studio ."
},
{
"code": null,
"e": 1117,
"s": 926,
"text": "To achieve our goal ,we shall use an R package called “tm”.This package supports all text mining functions like loading data,cleaning data and building a term matrix.It is available on CRAN."
},
{
"code": null,
"e": 1211,
"s": 1117,
"text": "#downloading and installing the package from CRANinstall.packages(\"tm\")#loading tmlibrary(tm)"
},
{
"code": null,
"e": 1440,
"s": 1211,
"text": "Text to be mined can be loaded into R from different source formats.It can come from text files(.txt),pdfs (.pdf),csv files(.csv) e.t.c ,but no matter the source format ,to be used in the tm package it is turned into a “corpus”."
},
{
"code": null,
"e": 1593,
"s": 1440,
"text": "A corpus is defined as “a collection of written texts, especially the entire works of a particular author or a body of writing on a particular subject”."
},
{
"code": null,
"e": 1654,
"s": 1593,
"text": "The tm package use the Corpus() function to create a corpus."
},
{
"code": null,
"e": 1824,
"s": 1654,
"text": "#loading a text file from local computernewdata<- readlines(filepath)#Load data as corpus#VectorSource() creates character vectorsmydata <- Corpus(VectorSource(newdata))"
},
{
"code": null,
"e": 1888,
"s": 1824,
"text": "Refer to this guide to learn more about importing files into R."
},
{
"code": null,
"e": 2115,
"s": 1888,
"text": "Once we have successfully loaded the data into the work space,it is time to clean this data .Our goal at this step is to create independent terms(words) from the data file before we can start counting how frequent they appear."
},
{
"code": null,
"e": 2264,
"s": 2115,
"text": "Since R is case sensitive ,we shall first convert the entire text to lowercase to avoid considering same words like “write” and “Write” differently."
},
{
"code": null,
"e": 2361,
"s": 2264,
"text": "We shall remove : URLs ,emojis,non-english words,punctuations,numbers,whitespace and stop words."
},
{
"code": null,
"e": 2610,
"s": 2361,
"text": "Stop words: The commonly used english words like “a”,” is ”,”the” in the tm package are referred to as stop words. These words have to be eliminated so as to render the results more accurate.It is also possible to create your own custom stop words."
},
{
"code": null,
"e": 3570,
"s": 2610,
"text": "# convert to lower casemydata <- tm_map(mydata, content_transformer(tolower))#remove ������ what would be emojismydata<-tm_map(mydata, content_transformer(gsub), pattern=\"\\\\W\",replace=\" \")# remove URLsremoveURL <- function(x) gsub(\"http[^[:space:]]*\", \"\", x)mydata <- tm_map(mydata, content_transformer(removeURL))# remove anything other than English letters or spaceremoveNumPunct <- function(x) gsub(\"[^[:alpha:][:space:]]*\", \"\", x)mydata <- tm_map(mydata, content_transformer(removeNumPunct))# remove stopwordsmydata <- tm_map(mydata, removeWords, stopwords(\"english\"))#u can create custom stop words using the code below.#myStopwords <- c(setdiff(stopwords('english'), c(\"r\", \"big\")),\"use\", \"see\", \"used\", \"via\", \"amp\")#mydata <- tm_map(mydata, removeWords, myStopwords)# remove extra whitespacemydata <- tm_map(mydata, stripWhitespace)# Remove numbersmydata <- tm_map(mydata, removeNumbers)# Remove punctuationsmydata <- tm_map(mydata, removePunctuation)"
},
{
"code": null,
"e": 3856,
"s": 3570,
"text": "Stemming is the process of gathering words of similar origin into one word for example “communication”, “communicates”, “communicate”. Stemming helps us increase accuracy in our mined text by removing suffixes and reducing words to their basic forms.We shall use the SnowballC library."
},
{
"code": null,
"e": 3913,
"s": 3856,
"text": "library(SnowballC)mydata <- tm_map(mydata, stemDocument)"
},
{
"code": null,
"e": 4186,
"s": 3913,
"text": "After the cleaning process ,we are left with independent terms that exist throughout the document.These are stored in a matrix that shows each of their occurrence. This matrix logs the number of times the term appears in our clean data set thus being called a term matrix."
},
{
"code": null,
"e": 4261,
"s": 4186,
"text": "#create a term matrix and store it as dtmdtm <- TermDocumentMatrix(mydata)"
},
{
"code": null,
"e": 4501,
"s": 4261,
"text": "Word frequencies : These are the number of times words appear in data set.Word frequencies will indicate to us from the most frequently used words in the data set to the least used using the compilation of occurrences from the term matrix."
},
{
"code": null,
"e": 4771,
"s": 4501,
"text": "We have just written a basic text mining script ,however it is just the beginning of text mining.The ability to get the text in its raw format and clean it to this point will give us direction to things like building a word cloud,sentiment analysis and building models."
},
{
"code": null,
"e": 4864,
"s": 4771,
"text": "Hold on to this script because it will come in handy when we start doing sentiment analysis."
}
] |
How to merge two lists in Python | Merging two Lists in Python | PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
There are different ways to merge two lists in python. According to our python version and packages installed, we can use any one of them to merge two lists.
#Input
list1 = [10, 20, 30]
list2 = [40, 50, 60]
#Output
[10, 20, 30, 40, 50, 60]
We can simply merge two lists using + operator like below.
list1 = [10, 20, 30]
list2 = [40, 50, 60]
merged_list = list1+list2
print("Merged List: ",merged_list)
#It is also equivalent to above code using +=
list1 += list2
print("Merged List using +=: ",list1)
The above solution internally creates a new list (merged_list) with a shallow copy of list1 and is concatenated with a shallow copy of list2.
Output:
Merged List: [10, 20, 30, 40, 50, 60]
Merged List using +=: [10, 20, 30, 40, 50, 60]
If you are using python >= 3.5 version the PEP additional unpacking generations allows you to concatenate lists using * operator.
list1 = [10, 20, 30]
list2 = [40, 50, 60]
mergedList = [*list1, *list2]
print(mergedList)
Output:
[10, 20, 30, 40, 50, 60]
The itertools allows us to chain the multiple lists so that the simple solution is to iterating the items in both the lists and generate a new list (or we can even use for processing).
import itertools
list1 = [10, 20, 30]
list2 = [40, 50, 60]
for item in itertools.chain(list1, list2):
print(item)
Output:
10
20
30
40
50
60
As we know, the list allows duplicate items. So if we wanted to remove duplicates while merging two lists, we could use the below solution.
list1 = [10, 20, 30, 40]
list2 = [30, 40, 50, 60]
merged_list = list(set(list1+list2))
print("Merged List with out duplicates: ",merged_list)
Output:
Merged List with out duplicates: [40, 10, 50, 20, 60, 30]
We can even extend the list by appending another list using the list.extend().
list1 = [10, 20, 30, 40]
list2 = [30, 40, 50, 60]
list1.extend(list2)
print(list1)
Output:
[10, 20, 30, 40, 30, 40, 50, 60]
Python List in depth
Python more on Lists
Happy Learning 🙂
Python List Data Structure In Depth
Python Set Data Structure in Depth
Python Tuple Data Structure in Depth
How to Convert Python List Of Objects to CSV File
Python – How to merge two dict in Python ?
Java 8 How to get common elements from two lists
How to Read CSV File in Python
Python – How to remove key from dictionary ?
How to get the size of a Directory in Python ?
Python – How to remove duplicate elements from List
Python – Print different vowels present in a String
Python – Find the biggest of 2 given numbers
How to Remove Spaces from String in Python
How to get Words Count in Python from a File
How to get Characters Count in Python from a File
Python List Data Structure In Depth
Python Set Data Structure in Depth
Python Tuple Data Structure in Depth
How to Convert Python List Of Objects to CSV File
Python – How to merge two dict in Python ?
Java 8 How to get common elements from two lists
How to Read CSV File in Python
Python – How to remove key from dictionary ?
How to get the size of a Directory in Python ?
Python – How to remove duplicate elements from List
Python – Print different vowels present in a String
Python – Find the biggest of 2 given numbers
How to Remove Spaces from String in Python
How to get Words Count in Python from a File
How to get Characters Count in Python from a File
Δ
Python – Introduction
Python – Features
Python – Install on Windows
Python – Modes of Program
Python – Number System
Python – Identifiers
Python – Operators
Python – Ternary Operator
Python – Command Line Arguments
Python – Keywords
Python – Data Types
Python – Upgrade Python PIP
Python – Virtual Environment
Pyhton – Type Casting
Python – String to Int
Python – Conditional Statements
Python – if statement
Python – *args and **kwargs
Python – Date Formatting
Python – Read input from keyboard
Python – raw_input
Python – List In Depth
Python – List Comprehension
Python – Set in Depth
Python – Dictionary in Depth
Python – Tuple in Depth
Python – Stack Datastructure
Python – Classes and Objects
Python – Constructors
Python – Object Introspection
Python – Inheritance
Python – Decorators
Python – Serialization with Pickle
Python – Exceptions Handling
Python – User defined Exceptions
Python – Multiprocessing
Python – Default function parameters
Python – Lambdas Functions
Python – NumPy Library
Python – MySQL Connector
Python – MySQL Create Database
Python – MySQL Read Data
Python – MySQL Insert Data
Python – MySQL Update Records
Python – MySQL Delete Records
Python – String Case Conversion
Howto – Find biggest of 2 numbers
Howto – Remove duplicates from List
Howto – Convert any Number to Binary
Howto – Merge two Lists
Howto – Merge two dicts
Howto – Get Characters Count in a File
Howto – Get Words Count in a File
Howto – Remove Spaces from String
Howto – Read Env variables
Howto – Read a text File
Howto – Read a JSON File
Howto – Read Config.ini files
Howto – Iterate Dictionary
Howto – Convert List Of Objects to CSV
Howto – Merge two dict in Python
Howto – create Zip File
Howto – Get OS info
Howto – Get size of Directory
Howto – Check whether a file exists
Howto – Remove key from dictionary
Howto – Sort Objects
Howto – Create or Delete Directories
Howto – Read CSV File
Howto – Create Python Iterable class
Howto – Access for loop index
Howto – Clear all elements from List
Howto – Remove empty lists from a List
Howto – Remove special characters from String
Howto – Sort dictionary by key
Howto – Filter a list | [
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 556,
"s": 398,
"text": "There are different ways to merge two lists in python. According to our python version and packages installed, we can use any one of them to merge two lists."
},
{
"code": null,
"e": 639,
"s": 556,
"text": "#Input\nlist1 = [10, 20, 30]\nlist2 = [40, 50, 60]\n#Output\n[10, 20, 30, 40, 50, 60]\n"
},
{
"code": null,
"e": 698,
"s": 639,
"text": "We can simply merge two lists using + operator like below."
},
{
"code": null,
"e": 903,
"s": 698,
"text": "list1 = [10, 20, 30]\nlist2 = [40, 50, 60]\nmerged_list = list1+list2\n\nprint(\"Merged List: \",merged_list)\n\n#It is also equivalent to above code using +=\n\nlist1 += list2\nprint(\"Merged List using +=: \",list1)"
},
{
"code": null,
"e": 1045,
"s": 903,
"text": "The above solution internally creates a new list (merged_list) with a shallow copy of list1 and is concatenated with a shallow copy of list2."
},
{
"code": null,
"e": 1053,
"s": 1045,
"text": "Output:"
},
{
"code": null,
"e": 1139,
"s": 1053,
"text": "Merged List: [10, 20, 30, 40, 50, 60]\nMerged List using +=: [10, 20, 30, 40, 50, 60]"
},
{
"code": null,
"e": 1269,
"s": 1139,
"text": "If you are using python >= 3.5 version the PEP additional unpacking generations allows you to concatenate lists using * operator."
},
{
"code": null,
"e": 1360,
"s": 1269,
"text": "list1 = [10, 20, 30]\nlist2 = [40, 50, 60]\n\nmergedList = [*list1, *list2]\nprint(mergedList)"
},
{
"code": null,
"e": 1368,
"s": 1360,
"text": "Output:"
},
{
"code": null,
"e": 1393,
"s": 1368,
"text": "[10, 20, 30, 40, 50, 60]"
},
{
"code": null,
"e": 1578,
"s": 1393,
"text": "The itertools allows us to chain the multiple lists so that the simple solution is to iterating the items in both the lists and generate a new list (or we can even use for processing)."
},
{
"code": null,
"e": 1699,
"s": 1578,
"text": "import itertools\n\nlist1 = [10, 20, 30]\nlist2 = [40, 50, 60]\n\nfor item in itertools.chain(list1, list2):\n print(item)\n"
},
{
"code": null,
"e": 1707,
"s": 1699,
"text": "Output:"
},
{
"code": null,
"e": 1725,
"s": 1707,
"text": "10\n20\n30\n40\n50\n60"
},
{
"code": null,
"e": 1865,
"s": 1725,
"text": "As we know, the list allows duplicate items. So if we wanted to remove duplicates while merging two lists, we could use the below solution."
},
{
"code": null,
"e": 2008,
"s": 1865,
"text": "list1 = [10, 20, 30, 40]\nlist2 = [30, 40, 50, 60]\n\nmerged_list = list(set(list1+list2))\nprint(\"Merged List with out duplicates: \",merged_list)"
},
{
"code": null,
"e": 2016,
"s": 2008,
"text": "Output:"
},
{
"code": null,
"e": 2075,
"s": 2016,
"text": "Merged List with out duplicates: [40, 10, 50, 20, 60, 30]"
},
{
"code": null,
"e": 2154,
"s": 2075,
"text": "We can even extend the list by appending another list using the list.extend()."
},
{
"code": null,
"e": 2238,
"s": 2154,
"text": "list1 = [10, 20, 30, 40]\nlist2 = [30, 40, 50, 60]\n\nlist1.extend(list2)\nprint(list1)"
},
{
"code": null,
"e": 2246,
"s": 2238,
"text": "Output:"
},
{
"code": null,
"e": 2279,
"s": 2246,
"text": "[10, 20, 30, 40, 30, 40, 50, 60]"
},
{
"code": null,
"e": 2300,
"s": 2279,
"text": "Python List in depth"
},
{
"code": null,
"e": 2321,
"s": 2300,
"text": "Python more on Lists"
},
{
"code": null,
"e": 2338,
"s": 2321,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 3000,
"s": 2338,
"text": "\nPython List Data Structure In Depth\nPython Set Data Structure in Depth\nPython Tuple Data Structure in Depth\nHow to Convert Python List Of Objects to CSV File\nPython – How to merge two dict in Python ?\nJava 8 How to get common elements from two lists\nHow to Read CSV File in Python\nPython – How to remove key from dictionary ?\nHow to get the size of a Directory in Python ?\nPython – How to remove duplicate elements from List\nPython – Print different vowels present in a String\nPython – Find the biggest of 2 given numbers\nHow to Remove Spaces from String in Python\nHow to get Words Count in Python from a File\nHow to get Characters Count in Python from a File\n"
},
{
"code": null,
"e": 3036,
"s": 3000,
"text": "Python List Data Structure In Depth"
},
{
"code": null,
"e": 3071,
"s": 3036,
"text": "Python Set Data Structure in Depth"
},
{
"code": null,
"e": 3108,
"s": 3071,
"text": "Python Tuple Data Structure in Depth"
},
{
"code": null,
"e": 3158,
"s": 3108,
"text": "How to Convert Python List Of Objects to CSV File"
},
{
"code": null,
"e": 3201,
"s": 3158,
"text": "Python – How to merge two dict in Python ?"
},
{
"code": null,
"e": 3250,
"s": 3201,
"text": "Java 8 How to get common elements from two lists"
},
{
"code": null,
"e": 3281,
"s": 3250,
"text": "How to Read CSV File in Python"
},
{
"code": null,
"e": 3326,
"s": 3281,
"text": "Python – How to remove key from dictionary ?"
},
{
"code": null,
"e": 3373,
"s": 3326,
"text": "How to get the size of a Directory in Python ?"
},
{
"code": null,
"e": 3425,
"s": 3373,
"text": "Python – How to remove duplicate elements from List"
},
{
"code": null,
"e": 3477,
"s": 3425,
"text": "Python – Print different vowels present in a String"
},
{
"code": null,
"e": 3522,
"s": 3477,
"text": "Python – Find the biggest of 2 given numbers"
},
{
"code": null,
"e": 3565,
"s": 3522,
"text": "How to Remove Spaces from String in Python"
},
{
"code": null,
"e": 3610,
"s": 3565,
"text": "How to get Words Count in Python from a File"
},
{
"code": null,
"e": 3660,
"s": 3610,
"text": "How to get Characters Count in Python from a File"
},
{
"code": null,
"e": 3666,
"s": 3664,
"text": "Δ"
},
{
"code": null,
"e": 3689,
"s": 3666,
"text": " Python – Introduction"
},
{
"code": null,
"e": 3708,
"s": 3689,
"text": " Python – Features"
},
{
"code": null,
"e": 3737,
"s": 3708,
"text": " Python – Install on Windows"
},
{
"code": null,
"e": 3764,
"s": 3737,
"text": " Python – Modes of Program"
},
{
"code": null,
"e": 3788,
"s": 3764,
"text": " Python – Number System"
},
{
"code": null,
"e": 3810,
"s": 3788,
"text": " Python – Identifiers"
},
{
"code": null,
"e": 3830,
"s": 3810,
"text": " Python – Operators"
},
{
"code": null,
"e": 3857,
"s": 3830,
"text": " Python – Ternary Operator"
},
{
"code": null,
"e": 3890,
"s": 3857,
"text": " Python – Command Line Arguments"
},
{
"code": null,
"e": 3909,
"s": 3890,
"text": " Python – Keywords"
},
{
"code": null,
"e": 3930,
"s": 3909,
"text": " Python – Data Types"
},
{
"code": null,
"e": 3959,
"s": 3930,
"text": " Python – Upgrade Python PIP"
},
{
"code": null,
"e": 3989,
"s": 3959,
"text": " Python – Virtual Environment"
},
{
"code": null,
"e": 4012,
"s": 3989,
"text": " Pyhton – Type Casting"
},
{
"code": null,
"e": 4036,
"s": 4012,
"text": " Python – String to Int"
},
{
"code": null,
"e": 4069,
"s": 4036,
"text": " Python – Conditional Statements"
},
{
"code": null,
"e": 4092,
"s": 4069,
"text": " Python – if statement"
},
{
"code": null,
"e": 4121,
"s": 4092,
"text": " Python – *args and **kwargs"
},
{
"code": null,
"e": 4147,
"s": 4121,
"text": " Python – Date Formatting"
},
{
"code": null,
"e": 4182,
"s": 4147,
"text": " Python – Read input from keyboard"
},
{
"code": null,
"e": 4202,
"s": 4182,
"text": " Python – raw_input"
},
{
"code": null,
"e": 4226,
"s": 4202,
"text": " Python – List In Depth"
},
{
"code": null,
"e": 4255,
"s": 4226,
"text": " Python – List Comprehension"
},
{
"code": null,
"e": 4278,
"s": 4255,
"text": " Python – Set in Depth"
},
{
"code": null,
"e": 4308,
"s": 4278,
"text": " Python – Dictionary in Depth"
},
{
"code": null,
"e": 4333,
"s": 4308,
"text": " Python – Tuple in Depth"
},
{
"code": null,
"e": 4363,
"s": 4333,
"text": " Python – Stack Datastructure"
},
{
"code": null,
"e": 4393,
"s": 4363,
"text": " Python – Classes and Objects"
},
{
"code": null,
"e": 4416,
"s": 4393,
"text": " Python – Constructors"
},
{
"code": null,
"e": 4447,
"s": 4416,
"text": " Python – Object Introspection"
},
{
"code": null,
"e": 4469,
"s": 4447,
"text": " Python – Inheritance"
},
{
"code": null,
"e": 4490,
"s": 4469,
"text": " Python – Decorators"
},
{
"code": null,
"e": 4526,
"s": 4490,
"text": " Python – Serialization with Pickle"
},
{
"code": null,
"e": 4556,
"s": 4526,
"text": " Python – Exceptions Handling"
},
{
"code": null,
"e": 4590,
"s": 4556,
"text": " Python – User defined Exceptions"
},
{
"code": null,
"e": 4616,
"s": 4590,
"text": " Python – Multiprocessing"
},
{
"code": null,
"e": 4654,
"s": 4616,
"text": " Python – Default function parameters"
},
{
"code": null,
"e": 4682,
"s": 4654,
"text": " Python – Lambdas Functions"
},
{
"code": null,
"e": 4706,
"s": 4682,
"text": " Python – NumPy Library"
},
{
"code": null,
"e": 4732,
"s": 4706,
"text": " Python – MySQL Connector"
},
{
"code": null,
"e": 4764,
"s": 4732,
"text": " Python – MySQL Create Database"
},
{
"code": null,
"e": 4790,
"s": 4764,
"text": " Python – MySQL Read Data"
},
{
"code": null,
"e": 4818,
"s": 4790,
"text": " Python – MySQL Insert Data"
},
{
"code": null,
"e": 4849,
"s": 4818,
"text": " Python – MySQL Update Records"
},
{
"code": null,
"e": 4880,
"s": 4849,
"text": " Python – MySQL Delete Records"
},
{
"code": null,
"e": 4913,
"s": 4880,
"text": " Python – String Case Conversion"
},
{
"code": null,
"e": 4948,
"s": 4913,
"text": " Howto – Find biggest of 2 numbers"
},
{
"code": null,
"e": 4985,
"s": 4948,
"text": " Howto – Remove duplicates from List"
},
{
"code": null,
"e": 5023,
"s": 4985,
"text": " Howto – Convert any Number to Binary"
},
{
"code": null,
"e": 5049,
"s": 5023,
"text": " Howto – Merge two Lists"
},
{
"code": null,
"e": 5074,
"s": 5049,
"text": " Howto – Merge two dicts"
},
{
"code": null,
"e": 5114,
"s": 5074,
"text": " Howto – Get Characters Count in a File"
},
{
"code": null,
"e": 5149,
"s": 5114,
"text": " Howto – Get Words Count in a File"
},
{
"code": null,
"e": 5184,
"s": 5149,
"text": " Howto – Remove Spaces from String"
},
{
"code": null,
"e": 5213,
"s": 5184,
"text": " Howto – Read Env variables"
},
{
"code": null,
"e": 5239,
"s": 5213,
"text": " Howto – Read a text File"
},
{
"code": null,
"e": 5265,
"s": 5239,
"text": " Howto – Read a JSON File"
},
{
"code": null,
"e": 5297,
"s": 5265,
"text": " Howto – Read Config.ini files"
},
{
"code": null,
"e": 5325,
"s": 5297,
"text": " Howto – Iterate Dictionary"
},
{
"code": null,
"e": 5365,
"s": 5325,
"text": " Howto – Convert List Of Objects to CSV"
},
{
"code": null,
"e": 5399,
"s": 5365,
"text": " Howto – Merge two dict in Python"
},
{
"code": null,
"e": 5424,
"s": 5399,
"text": " Howto – create Zip File"
},
{
"code": null,
"e": 5445,
"s": 5424,
"text": " Howto – Get OS info"
},
{
"code": null,
"e": 5476,
"s": 5445,
"text": " Howto – Get size of Directory"
},
{
"code": null,
"e": 5513,
"s": 5476,
"text": " Howto – Check whether a file exists"
},
{
"code": null,
"e": 5550,
"s": 5513,
"text": " Howto – Remove key from dictionary"
},
{
"code": null,
"e": 5572,
"s": 5550,
"text": " Howto – Sort Objects"
},
{
"code": null,
"e": 5610,
"s": 5572,
"text": " Howto – Create or Delete Directories"
},
{
"code": null,
"e": 5633,
"s": 5610,
"text": " Howto – Read CSV File"
},
{
"code": null,
"e": 5671,
"s": 5633,
"text": " Howto – Create Python Iterable class"
},
{
"code": null,
"e": 5702,
"s": 5671,
"text": " Howto – Access for loop index"
},
{
"code": null,
"e": 5740,
"s": 5702,
"text": " Howto – Clear all elements from List"
},
{
"code": null,
"e": 5780,
"s": 5740,
"text": " Howto – Remove empty lists from a List"
},
{
"code": null,
"e": 5827,
"s": 5780,
"text": " Howto – Remove special characters from String"
},
{
"code": null,
"e": 5859,
"s": 5827,
"text": " Howto – Sort dictionary by key"
}
] |
Find a form feed character with JavaScript RegExp. | To find a form feed character with JavaScript Regular Expression, use the following −
\f
You can try to run the following code to find a form feed character. It returns the position where the form feed (\f) character is found −
<html>
<head>
<title>JavaScript Regular Expression</title>
</head>
<body>
<script>
var myStr = "100% \f Responsive!";
var reg = /\f/;
var match = myStr.search(reg);
document.write(match);
</script>
</body>
</html> | [
{
"code": null,
"e": 1148,
"s": 1062,
"text": "To find a form feed character with JavaScript Regular Expression, use the following −"
},
{
"code": null,
"e": 1151,
"s": 1148,
"text": "\\f"
},
{
"code": null,
"e": 1290,
"s": 1151,
"text": "You can try to run the following code to find a form feed character. It returns the position where the form feed (\\f) character is found −"
},
{
"code": null,
"e": 1580,
"s": 1290,
"text": "<html>\n <head>\n <title>JavaScript Regular Expression</title>\n </head>\n <body>\n <script>\n var myStr = \"100% \\f Responsive!\";\n var reg = /\\f/;\n var match = myStr.search(reg);\n \n document.write(match);\n </script>\n </body>\n</html>"
}
] |
AngularJS | ng-form Directive - GeeksforGeeks | 29 Mar, 2019
The ng-form Directive in AngularJS is used to create nested form i.e. one form inside the other form. It specifies an inherit control from HTML form. It creates control group inside a form directive which can be used to determine the validity of a sub-group of controls.
Syntax:
<ng-form [name="string"]> Contents... </ng-form>
Example 1: This example uses ng-form Directive to hide the input text fields and display its content.
<!DOCTYPE html><html> <head> <title>ng-form Directive</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"> </script> </head> <body ng-app="" style="text-align:center"> <h1 style="color:green;">GeeksforGeeks</h1> <h2 style="">ng-form Directive</h2> <div> <ng-form ng-hide="isDetail"> Full Name: <input type="text" ng-model="fName"> <br><br> Username: <input type="text" ng-model="uName"> <br> </ng-form> <br> <input type="button" ng-click="isDetail=true" value="Click it!" /> <div ng-show="isDetail"> First Name:<b>{{fName}}</b><br /> User Name:<b>{{uName}}</b><br /> </div> </div></body> </html>
Output:Before Clicking the button:After Clicking the button:
Example 2: This example uses ng-form Directive to validate email and save it.
<!DOCTYPE html><html> <head> <title>ng-form Directive</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"> </script> </head> <body ng-app="" style="text-align:center"> <h1 style="color:green;">GeeksforGeeks</h1> <h2 style="">ng-form Directive</h2> <div> <ng-form ng-submit="save(user)" name="myForm" novalidate> Enter Email: <input type="email" name="uname" required ng-model="user.userName"><br> <span style="color:red" ng-show="myForm.uname.$error.required && myForm.uname.$dirty">Email is required</span> <br> <button ng-disabled="!myForm.$valid" type="submit"> save </button> </ng-form> </div></body> </html>
Output:Invalid Input:Valid Input:
AngularJS-Directives
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Angular Libraries For Web Developers
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular 10 (focus) Event
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25109,
"s": 25081,
"text": "\n29 Mar, 2019"
},
{
"code": null,
"e": 25380,
"s": 25109,
"text": "The ng-form Directive in AngularJS is used to create nested form i.e. one form inside the other form. It specifies an inherit control from HTML form. It creates control group inside a form directive which can be used to determine the validity of a sub-group of controls."
},
{
"code": null,
"e": 25388,
"s": 25380,
"text": "Syntax:"
},
{
"code": null,
"e": 25438,
"s": 25388,
"text": "<ng-form [name=\"string\"]> Contents... </ng-form>\n"
},
{
"code": null,
"e": 25540,
"s": 25438,
"text": "Example 1: This example uses ng-form Directive to hide the input text fields and display its content."
},
{
"code": "<!DOCTYPE html><html> <head> <title>ng-form Directive</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js\"> </script> </head> <body ng-app=\"\" style=\"text-align:center\"> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h2 style=\"\">ng-form Directive</h2> <div> <ng-form ng-hide=\"isDetail\"> Full Name: <input type=\"text\" ng-model=\"fName\"> <br><br> Username: <input type=\"text\" ng-model=\"uName\"> <br> </ng-form> <br> <input type=\"button\" ng-click=\"isDetail=true\" value=\"Click it!\" /> <div ng-show=\"isDetail\"> First Name:<b>{{fName}}</b><br /> User Name:<b>{{uName}}</b><br /> </div> </div></body> </html> ",
"e": 26396,
"s": 25540,
"text": null
},
{
"code": null,
"e": 26457,
"s": 26396,
"text": "Output:Before Clicking the button:After Clicking the button:"
},
{
"code": null,
"e": 26535,
"s": 26457,
"text": "Example 2: This example uses ng-form Directive to validate email and save it."
},
{
"code": "<!DOCTYPE html><html> <head> <title>ng-form Directive</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js\"> </script> </head> <body ng-app=\"\" style=\"text-align:center\"> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h2 style=\"\">ng-form Directive</h2> <div> <ng-form ng-submit=\"save(user)\" name=\"myForm\" novalidate> Enter Email: <input type=\"email\" name=\"uname\" required ng-model=\"user.userName\"><br> <span style=\"color:red\" ng-show=\"myForm.uname.$error.required && myForm.uname.$dirty\">Email is required</span> <br> <button ng-disabled=\"!myForm.$valid\" type=\"submit\"> save </button> </ng-form> </div></body> </html> ",
"e": 27416,
"s": 26535,
"text": null
},
{
"code": null,
"e": 27450,
"s": 27416,
"text": "Output:Invalid Input:Valid Input:"
},
{
"code": null,
"e": 27471,
"s": 27450,
"text": "AngularJS-Directives"
},
{
"code": null,
"e": 27481,
"s": 27471,
"text": "AngularJS"
},
{
"code": null,
"e": 27498,
"s": 27481,
"text": "Web Technologies"
},
{
"code": null,
"e": 27596,
"s": 27498,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27640,
"s": 27596,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 27675,
"s": 27640,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 27699,
"s": 27675,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 27752,
"s": 27699,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 27777,
"s": 27752,
"text": "Angular 10 (focus) Event"
},
{
"code": null,
"e": 27819,
"s": 27777,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27852,
"s": 27819,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27895,
"s": 27852,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27957,
"s": 27895,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
MongoDB query by sub-field? | You can use dot(.) notation to query by subfield. Let us create a collection with a document. The query to create a collection with a document is as follows −
> db.queryBySubFieldDemo.insertOne(
... {
... "StudentPersonalDetails" : {"StudentName" : "John","StudentHobby" :"Photography"},
... "StudentScores" : {"MathScore" : 56}
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5c92c2995259fcd195499808")
}
> db.queryBySubFieldDemo.insertOne(
... {
... "StudentPersonalDetails" : {"StudentName" : "Chris","StudentHobby" :"Reading"},
... "StudentScores" : {"MathScore" : 97}
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5c92c2df5259fcd195499809")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.queryBySubFieldDemo.find().pretty();
The following is the output −
{
"_id" : ObjectId("5c92c2995259fcd195499808"),
"StudentPersonalDetails" : {
"StudentName" : "John",
"StudentHobby" : "Photography"
},
"StudentScores" : {
"MathScore" : 56
}
}
{
"_id" : ObjectId("5c92c2df5259fcd195499809"),
"StudentPersonalDetails" : {
"StudentName" : "Chris",
"StudentHobby" : "Reading"
},
"StudentScores" : {
"MathScore" : 97
}
}
Here is the query by subfield −
> db.queryBySubFieldDemo.find({"StudentPersonalDetails.StudentName":"Chris"}).pretty();
The following is the output −
{
"_id" : ObjectId("5c92c2df5259fcd195499809"),
"StudentPersonalDetails" : {
"StudentName" : "Chris",
"StudentHobby" : "Reading"
},
"StudentScores" : {
"MathScore" : 97
}
} | [
{
"code": null,
"e": 1221,
"s": 1062,
"text": "You can use dot(.) notation to query by subfield. Let us create a collection with a document. The query to create a collection with a document is as follows −"
},
{
"code": null,
"e": 1790,
"s": 1221,
"text": "> db.queryBySubFieldDemo.insertOne(\n ... {\n ... \"StudentPersonalDetails\" : {\"StudentName\" : \"John\",\"StudentHobby\" :\"Photography\"},\n ... \"StudentScores\" : {\"MathScore\" : 56}\n ... }\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c92c2995259fcd195499808\")\n}\n> db.queryBySubFieldDemo.insertOne(\n ... {\n ... \"StudentPersonalDetails\" : {\"StudentName\" : \"Chris\",\"StudentHobby\" :\"Reading\"},\n ... \"StudentScores\" : {\"MathScore\" : 97}\n ... }\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c92c2df5259fcd195499809\")\n}"
},
{
"code": null,
"e": 1888,
"s": 1790,
"text": "Display all documents from a collection with the help of find() method. The query is as follows −"
},
{
"code": null,
"e": 1930,
"s": 1888,
"text": "> db.queryBySubFieldDemo.find().pretty();"
},
{
"code": null,
"e": 1960,
"s": 1930,
"text": "The following is the output −"
},
{
"code": null,
"e": 2375,
"s": 1960,
"text": "{\n \"_id\" : ObjectId(\"5c92c2995259fcd195499808\"),\n \"StudentPersonalDetails\" : {\n \"StudentName\" : \"John\",\n \"StudentHobby\" : \"Photography\"\n },\n \"StudentScores\" : {\n \"MathScore\" : 56\n }\n}\n{\n \"_id\" : ObjectId(\"5c92c2df5259fcd195499809\"),\n \"StudentPersonalDetails\" : {\n \"StudentName\" : \"Chris\",\n \"StudentHobby\" : \"Reading\"\n },\n \"StudentScores\" : {\n \"MathScore\" : 97\n }\n}"
},
{
"code": null,
"e": 2407,
"s": 2375,
"text": "Here is the query by subfield −"
},
{
"code": null,
"e": 2495,
"s": 2407,
"text": "> db.queryBySubFieldDemo.find({\"StudentPersonalDetails.StudentName\":\"Chris\"}).pretty();"
},
{
"code": null,
"e": 2525,
"s": 2495,
"text": "The following is the output −"
},
{
"code": null,
"e": 2731,
"s": 2525,
"text": "{\n \"_id\" : ObjectId(\"5c92c2df5259fcd195499809\"),\n \"StudentPersonalDetails\" : {\n \"StudentName\" : \"Chris\",\n \"StudentHobby\" : \"Reading\"\n },\n \"StudentScores\" : {\n \"MathScore\" : 97\n }\n}"
}
] |
SQL Server with Python. The world’s favorite database + the... | by James Briggs | Towards Data Science | Everyone uses SQL, and everyone uses Python. SQL is the de-facto standard for databases. Python on the other hand is an all-star, a top language for data analytics, machine learning, and web development. Imagine both, together.
This is actually incredibly easy to setup. We can quickly utilize the dynamic nature of Python, to control and build queries in SQL. The best part? After set-up, you don’t need to do anything.
Both of these amazing tools together, allow us to reach new heights of automation and efficiency.
Our bridge between the two technologies is pyodbc. This library allows easy access to ODBC databases.
ODBC, short for Open Database Connectivity, is a standardised application programming interface (API) for accessing databases, developed by the SQL Access group back in the early 90's.
Compliant database management systems (DBMS) include:
IBM Db2
MS Access
MS SQL Server
MySQL
Oracle
In this article, we will be using MS SQL Server. For the most part, this should be directly transferable for use with any ODBC compliant database. The only change required should be with the connection setup.
The first thing we need to do is create a connection to the SQL server. We can do this using pyodbc.connect. Within this function we must also pass a connection string.
This connection string must specify the DBMS Driver, the Server, a specific Database to connect to, and our connection settings.
So, lets assume we want to connect to server UKXXX00123,45600, database DB01 , to do this we want to use SQL Server Native Client 11.0.
We will be connecting from an internal, and thus trusted connection (we do not need to enter our username and password).
cnxn_str = ("Driver={SQL Server Native Client 11.0};" "Server=UKXXX00123,45600;" "Database=DB01;" "Trusted_Connection=yes;")
Our connection is now initialized with:
cnxn = pyodbc.connect(cnxn_str)
If we are not accessing the database via a trusted connection, we will need to enter the username and password that we would usually use to access the server via SQL Server Management Studio (SSMS).
For example, if our username is JoeBloggs, and our password is Password123, we should immediately change our password.
But before changing that horrible password, we can connect like so:
cnxn_str = ("Driver={SQL Server Native Client 11.0};" "Server=UKXXX00123,45600;" "Database=DB01;" "UID=JoeBloggs;" "PWD=Password123;")cnxn = pyodbc.connect(cnxn_str)
Now we are connected to the database, we can begin performing SQL queries via Python.
Every query we run on SQL Server now will consist of a cursor initialization, and query execution. Additionally, if we make any changes inside the server, we also need to commit these changes to the server (which we cover in the next section).
To initialize a cursor:
cursor = cnxn.cursor()
Now, whenever we want to perform a query, we use this cursor object.
Let’s first select the top 1000 rows from a table called customers:
cursor.execute("SELECT TOP(1000) * FROM customers")
This performs the operation, but within the server, and so nothing is actually returned to Python. So let’s look at extracting this data from SQL.
To extract our data from SQL into Python, we use pandas. Pandas provides us with a very convenient function called read_sql, this function, as you may have guessed, reads data from SQL.
read_sql requires both a query and the connection instance cnxn, like so:
data = pd.read_sql("SELECT TOP(1000) * FROM customers", cnxn)
This returns a dataframe containing the top 1000 rows from the customers table.
Now, if we wanted to change the data in SQL, we need to add another step to the original initialize connection, execute query process.
When we execute queries in SQL, these changes are kept in a temporarily existing space, they are not made directly to the data.
To make these changes permanent, we must commit them. Lets concatenate the firstName and lastName columns, to create a fullName column.
cursor = cnxn.cursor()# first alter the table, adding a columncursor.execute("ALTER TABLE customer " + "ADD fullName VARCHAR(20)")# now update that column to contain firstName + lastNamecursor.execute("UPDATE customer " + "SET fullName = firstName + " " + lastName")
At this point, fullName does not exist in our database. We must commit these changes to make them permanent:
cnxn.commit()
Once we have performed whichever manipulation tasks we needed to do. We can extract our data to Python — alternatively, we can extract the data to Python and manipulate it there too.
Whichever approach you take, once the data is there in Python, we can do a multitude of useful things with it that were simply not possible before.
Maybe we need to perform some daily reporting, with which we would usually query the newest batch of data in SQL server, calculate some basic statistics, and send the results via email.
Let’s automate that:
And with that, we are done! Running this code quickly extracts the prior week’s data, calculates our key measures, and sends a summary of this to our boss.
So, in a few simple, easy steps, we’ve taken a first look at quickly setting up a more efficient, automated workflow using an integration of both SQL and Python.
I have found this to be incredibly useful, and not just for the use-cases described above.
Python simply kicks open new routes that were impassable to us before with just SQL alone.
Let me know your opinions, ideas, or use-cases, I’d love to hear them! If you’d like more content like this, I post on YouTube too.
Thanks for reading!
If you enjoyed this article, you may be interested in a deeper look at email automation with Python. I covered this in a previous article, check it out if you’re interested:
towardsdatascience.com
This GitHub repo also contains documentation and code showing the implementation of a few useful methods. | [
{
"code": null,
"e": 400,
"s": 172,
"text": "Everyone uses SQL, and everyone uses Python. SQL is the de-facto standard for databases. Python on the other hand is an all-star, a top language for data analytics, machine learning, and web development. Imagine both, together."
},
{
"code": null,
"e": 593,
"s": 400,
"text": "This is actually incredibly easy to setup. We can quickly utilize the dynamic nature of Python, to control and build queries in SQL. The best part? After set-up, you don’t need to do anything."
},
{
"code": null,
"e": 691,
"s": 593,
"text": "Both of these amazing tools together, allow us to reach new heights of automation and efficiency."
},
{
"code": null,
"e": 793,
"s": 691,
"text": "Our bridge between the two technologies is pyodbc. This library allows easy access to ODBC databases."
},
{
"code": null,
"e": 978,
"s": 793,
"text": "ODBC, short for Open Database Connectivity, is a standardised application programming interface (API) for accessing databases, developed by the SQL Access group back in the early 90's."
},
{
"code": null,
"e": 1032,
"s": 978,
"text": "Compliant database management systems (DBMS) include:"
},
{
"code": null,
"e": 1040,
"s": 1032,
"text": "IBM Db2"
},
{
"code": null,
"e": 1050,
"s": 1040,
"text": "MS Access"
},
{
"code": null,
"e": 1064,
"s": 1050,
"text": "MS SQL Server"
},
{
"code": null,
"e": 1070,
"s": 1064,
"text": "MySQL"
},
{
"code": null,
"e": 1077,
"s": 1070,
"text": "Oracle"
},
{
"code": null,
"e": 1286,
"s": 1077,
"text": "In this article, we will be using MS SQL Server. For the most part, this should be directly transferable for use with any ODBC compliant database. The only change required should be with the connection setup."
},
{
"code": null,
"e": 1455,
"s": 1286,
"text": "The first thing we need to do is create a connection to the SQL server. We can do this using pyodbc.connect. Within this function we must also pass a connection string."
},
{
"code": null,
"e": 1584,
"s": 1455,
"text": "This connection string must specify the DBMS Driver, the Server, a specific Database to connect to, and our connection settings."
},
{
"code": null,
"e": 1720,
"s": 1584,
"text": "So, lets assume we want to connect to server UKXXX00123,45600, database DB01 , to do this we want to use SQL Server Native Client 11.0."
},
{
"code": null,
"e": 1841,
"s": 1720,
"text": "We will be connecting from an internal, and thus trusted connection (we do not need to enter our username and password)."
},
{
"code": null,
"e": 1999,
"s": 1841,
"text": "cnxn_str = (\"Driver={SQL Server Native Client 11.0};\" \"Server=UKXXX00123,45600;\" \"Database=DB01;\" \"Trusted_Connection=yes;\")"
},
{
"code": null,
"e": 2039,
"s": 1999,
"text": "Our connection is now initialized with:"
},
{
"code": null,
"e": 2071,
"s": 2039,
"text": "cnxn = pyodbc.connect(cnxn_str)"
},
{
"code": null,
"e": 2270,
"s": 2071,
"text": "If we are not accessing the database via a trusted connection, we will need to enter the username and password that we would usually use to access the server via SQL Server Management Studio (SSMS)."
},
{
"code": null,
"e": 2389,
"s": 2270,
"text": "For example, if our username is JoeBloggs, and our password is Password123, we should immediately change our password."
},
{
"code": null,
"e": 2457,
"s": 2389,
"text": "But before changing that horrible password, we can connect like so:"
},
{
"code": null,
"e": 2667,
"s": 2457,
"text": "cnxn_str = (\"Driver={SQL Server Native Client 11.0};\" \"Server=UKXXX00123,45600;\" \"Database=DB01;\" \"UID=JoeBloggs;\" \"PWD=Password123;\")cnxn = pyodbc.connect(cnxn_str)"
},
{
"code": null,
"e": 2753,
"s": 2667,
"text": "Now we are connected to the database, we can begin performing SQL queries via Python."
},
{
"code": null,
"e": 2997,
"s": 2753,
"text": "Every query we run on SQL Server now will consist of a cursor initialization, and query execution. Additionally, if we make any changes inside the server, we also need to commit these changes to the server (which we cover in the next section)."
},
{
"code": null,
"e": 3021,
"s": 2997,
"text": "To initialize a cursor:"
},
{
"code": null,
"e": 3044,
"s": 3021,
"text": "cursor = cnxn.cursor()"
},
{
"code": null,
"e": 3113,
"s": 3044,
"text": "Now, whenever we want to perform a query, we use this cursor object."
},
{
"code": null,
"e": 3181,
"s": 3113,
"text": "Let’s first select the top 1000 rows from a table called customers:"
},
{
"code": null,
"e": 3233,
"s": 3181,
"text": "cursor.execute(\"SELECT TOP(1000) * FROM customers\")"
},
{
"code": null,
"e": 3380,
"s": 3233,
"text": "This performs the operation, but within the server, and so nothing is actually returned to Python. So let’s look at extracting this data from SQL."
},
{
"code": null,
"e": 3566,
"s": 3380,
"text": "To extract our data from SQL into Python, we use pandas. Pandas provides us with a very convenient function called read_sql, this function, as you may have guessed, reads data from SQL."
},
{
"code": null,
"e": 3640,
"s": 3566,
"text": "read_sql requires both a query and the connection instance cnxn, like so:"
},
{
"code": null,
"e": 3702,
"s": 3640,
"text": "data = pd.read_sql(\"SELECT TOP(1000) * FROM customers\", cnxn)"
},
{
"code": null,
"e": 3782,
"s": 3702,
"text": "This returns a dataframe containing the top 1000 rows from the customers table."
},
{
"code": null,
"e": 3917,
"s": 3782,
"text": "Now, if we wanted to change the data in SQL, we need to add another step to the original initialize connection, execute query process."
},
{
"code": null,
"e": 4045,
"s": 3917,
"text": "When we execute queries in SQL, these changes are kept in a temporarily existing space, they are not made directly to the data."
},
{
"code": null,
"e": 4181,
"s": 4045,
"text": "To make these changes permanent, we must commit them. Lets concatenate the firstName and lastName columns, to create a fullName column."
},
{
"code": null,
"e": 4476,
"s": 4181,
"text": "cursor = cnxn.cursor()# first alter the table, adding a columncursor.execute(\"ALTER TABLE customer \" + \"ADD fullName VARCHAR(20)\")# now update that column to contain firstName + lastNamecursor.execute(\"UPDATE customer \" + \"SET fullName = firstName + \" \" + lastName\")"
},
{
"code": null,
"e": 4585,
"s": 4476,
"text": "At this point, fullName does not exist in our database. We must commit these changes to make them permanent:"
},
{
"code": null,
"e": 4599,
"s": 4585,
"text": "cnxn.commit()"
},
{
"code": null,
"e": 4782,
"s": 4599,
"text": "Once we have performed whichever manipulation tasks we needed to do. We can extract our data to Python — alternatively, we can extract the data to Python and manipulate it there too."
},
{
"code": null,
"e": 4930,
"s": 4782,
"text": "Whichever approach you take, once the data is there in Python, we can do a multitude of useful things with it that were simply not possible before."
},
{
"code": null,
"e": 5116,
"s": 4930,
"text": "Maybe we need to perform some daily reporting, with which we would usually query the newest batch of data in SQL server, calculate some basic statistics, and send the results via email."
},
{
"code": null,
"e": 5137,
"s": 5116,
"text": "Let’s automate that:"
},
{
"code": null,
"e": 5293,
"s": 5137,
"text": "And with that, we are done! Running this code quickly extracts the prior week’s data, calculates our key measures, and sends a summary of this to our boss."
},
{
"code": null,
"e": 5455,
"s": 5293,
"text": "So, in a few simple, easy steps, we’ve taken a first look at quickly setting up a more efficient, automated workflow using an integration of both SQL and Python."
},
{
"code": null,
"e": 5546,
"s": 5455,
"text": "I have found this to be incredibly useful, and not just for the use-cases described above."
},
{
"code": null,
"e": 5637,
"s": 5546,
"text": "Python simply kicks open new routes that were impassable to us before with just SQL alone."
},
{
"code": null,
"e": 5769,
"s": 5637,
"text": "Let me know your opinions, ideas, or use-cases, I’d love to hear them! If you’d like more content like this, I post on YouTube too."
},
{
"code": null,
"e": 5789,
"s": 5769,
"text": "Thanks for reading!"
},
{
"code": null,
"e": 5963,
"s": 5789,
"text": "If you enjoyed this article, you may be interested in a deeper look at email automation with Python. I covered this in a previous article, check it out if you’re interested:"
},
{
"code": null,
"e": 5986,
"s": 5963,
"text": "towardsdatascience.com"
}
] |
find_element_by_xpath() driver method - Selenium Python - GeeksforGeeks | 22 Nov, 2021
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provide a simple API to write functional/acceptance tests using Selenium WebDriver. After you have installed selenium and checked out – Navigating links using the get method, you might want to play more with Selenium Python. After one has opened a page using selenium such as geeksforgeeks, one might want to click some buttons automatically or fill a form automatically or any such automated task. This article revolves around how to grab or locate elements in a webpage using locating strategies of Selenium Web Driver. More specifically, find_element_by_xpath() is discussed in this article. XPath is the language used for locating nodes in an XML document. As HTML can be an implementation of XML (XHTML), Selenium users can leverage this powerful language to target elements in their web applications. XPath extends beyond (as well as supporting) the simple methods of locating by id or name attributes, and opens up all sorts of new possibilities such as locating the third checkbox on the page.
Syntax –
driver.find_element_by_xpath("xpath")
Example – For instance, consider this page source:
html
<html> <body> <form id="loginForm"> <input name="username" type="text" /> <input name="password" type="password" /> <input name="continue" type="submit" value="Login" /> </form> </body><html>
Now after you have created a driver, you can grab an element using –
login_form = driver.find_element_by_xpath("/html/body/form[1]")
login_form = driver.find_element_by_xpath("//form[1]")
Let’s try to practically implement this method and get an element instance for “https://www.geeksforgeeks.org/”. Let’s try to grab search form input using its name “search”. Create a file called run.py to demonstrate the find_element_by_xpath method –
Python3
# Python program to demonstrate# selenium # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # enter keyword to searchkeyword = "geeksforgeeks" # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get elementelement = driver.find_element_by_xpath("//form[input/@name ='search']") # print complete elementprint(element)
Now run using –
Python run.py
First, it will open the firefox window with geeksforgeeks, and then select the element and print it on the terminal as shown below. Browser Output –
Terminal Output –
.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; }
NaveenArora
surinderdawra388
gulshankumarar231
kumaripunam984122
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python | [
{
"code": null,
"e": 24800,
"s": 24772,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 25904,
"s": 24800,
"text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provide a simple API to write functional/acceptance tests using Selenium WebDriver. After you have installed selenium and checked out – Navigating links using the get method, you might want to play more with Selenium Python. After one has opened a page using selenium such as geeksforgeeks, one might want to click some buttons automatically or fill a form automatically or any such automated task. This article revolves around how to grab or locate elements in a webpage using locating strategies of Selenium Web Driver. More specifically, find_element_by_xpath() is discussed in this article. XPath is the language used for locating nodes in an XML document. As HTML can be an implementation of XML (XHTML), Selenium users can leverage this powerful language to target elements in their web applications. XPath extends beyond (as well as supporting) the simple methods of locating by id or name attributes, and opens up all sorts of new possibilities such as locating the third checkbox on the page. "
},
{
"code": null,
"e": 25915,
"s": 25904,
"text": "Syntax – "
},
{
"code": null,
"e": 25953,
"s": 25915,
"text": "driver.find_element_by_xpath(\"xpath\")"
},
{
"code": null,
"e": 26005,
"s": 25953,
"text": "Example – For instance, consider this page source: "
},
{
"code": null,
"e": 26010,
"s": 26005,
"text": "html"
},
{
"code": "<html> <body> <form id=\"loginForm\"> <input name=\"username\" type=\"text\" /> <input name=\"password\" type=\"password\" /> <input name=\"continue\" type=\"submit\" value=\"Login\" /> </form> </body><html>",
"e": 26210,
"s": 26010,
"text": null
},
{
"code": null,
"e": 26280,
"s": 26210,
"text": "Now after you have created a driver, you can grab an element using – "
},
{
"code": null,
"e": 26399,
"s": 26280,
"text": "login_form = driver.find_element_by_xpath(\"/html/body/form[1]\")\nlogin_form = driver.find_element_by_xpath(\"//form[1]\")"
},
{
"code": null,
"e": 26654,
"s": 26401,
"text": "Let’s try to practically implement this method and get an element instance for “https://www.geeksforgeeks.org/”. Let’s try to grab search form input using its name “search”. Create a file called run.py to demonstrate the find_element_by_xpath method – "
},
{
"code": null,
"e": 26662,
"s": 26654,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# selenium # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # enter keyword to searchkeyword = \"geeksforgeeks\" # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get elementelement = driver.find_element_by_xpath(\"//form[input/@name ='search']\") # print complete elementprint(element)",
"e": 27050,
"s": 26662,
"text": null
},
{
"code": null,
"e": 27067,
"s": 27050,
"text": "Now run using – "
},
{
"code": null,
"e": 27081,
"s": 27067,
"text": "Python run.py"
},
{
"code": null,
"e": 27231,
"s": 27081,
"text": "First, it will open the firefox window with geeksforgeeks, and then select the element and print it on the terminal as shown below. Browser Output – "
},
{
"code": null,
"e": 27250,
"s": 27231,
"text": "Terminal Output – "
},
{
"code": null,
"e": 27594,
"s": 27252,
"text": ".math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } "
},
{
"code": null,
"e": 27606,
"s": 27594,
"text": "NaveenArora"
},
{
"code": null,
"e": 27623,
"s": 27606,
"text": "surinderdawra388"
},
{
"code": null,
"e": 27641,
"s": 27623,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 27659,
"s": 27641,
"text": "kumaripunam984122"
},
{
"code": null,
"e": 27675,
"s": 27659,
"text": "Python-selenium"
},
{
"code": null,
"e": 27684,
"s": 27675,
"text": "selenium"
},
{
"code": null,
"e": 27691,
"s": 27684,
"text": "Python"
},
{
"code": null,
"e": 27789,
"s": 27691,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27807,
"s": 27789,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27842,
"s": 27807,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27864,
"s": 27842,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27896,
"s": 27864,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27926,
"s": 27896,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27968,
"s": 27926,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27994,
"s": 27968,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28031,
"s": 27994,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28074,
"s": 28031,
"text": "Python program to convert a list to string"
}
] |
Angular 8 - Http Client Programming | Http client programming is a must needed feature in every modern web application. Nowadays, lot of application exposes their functionality through REST API (functionality over HTTP protocol). With this in mind, Angular Team provides extensive support to access HTTP server. Angular provides a separate module, HttpClientModule and a service, HttpClient to do HTTP programming.
Let us learn how to how to use HttpClient service in this chapter. Developer should have a basic knowledge in Http programming to understand this chapter.
The prerequisite to do Http programming is the basic knowledge of Http protocol and REST API technique. Http programming involves two part, server and client. Angular provides support to create client side application. Express a popular web framework provides support to create server side application.
Let us create an Expense Rest API using express framework and then access it from our ExpenseManager application using Angular HttpClient service.
Open a command prompt and create a new folder, express-rest-api.
cd /go/to/workspace
mkdir express-rest-api
cd expense-rest-api
Initialise a new node application using below command −
npm init
npm init will ask some basic questions like project name (express-rest-api), entry point (server.js), etc., as mentioned below −
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (expense-rest-api)
version: (1.0.0)
description: Rest api for Expense Application
entry point: (index.js) server.js
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to \path\to\workspace\expense-rest-api\package.json: {
"name": "expense-rest-api",
"version": "1.0.0",
"description": "Rest api for Expense Application",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this OK? (yes) yes
Install express, sqlite and cors modules using below command −
npm install express sqlite3 cors
Create a new file sqlitedb.js and place below code −
var sqlite3 = require('sqlite3').verbose()
const DBSOURCE = "expensedb.sqlite"
let db = new sqlite3.Database(DBSOURCE, (err) => {
if (err) {
console.error(err.message)
throw err
}else{
console.log('Connected to the SQLite database.')
db.run(`CREATE TABLE expense (
id INTEGER PRIMARY KEY AUTOINCREMENT,
item text,
amount real,
category text,
location text,
spendOn text,
createdOn text
)`,
(err) => {
if (err) {
console.log(err);
}else{
var insert = 'INSERT INTO expense (item, amount, category, location, spendOn, createdOn) VALUES (?,?,?,?,?,?)'
db.run(insert, ['Pizza', 10, 'Food', 'KFC', '2020-05-26 10:10', '2020-05-26 10:10'])
db.run(insert, ['Pizza', 9, 'Food', 'Mcdonald', '2020-05-28 11:10', '2020-05-28 11:10'])
db.run(insert, ['Pizza', 12, 'Food', 'Mcdonald', '2020-05-29 09:22', '2020-05-29 09:22'])
db.run(insert, ['Pizza', 15, 'Food', 'KFC', '2020-06-06 16:18', '2020-06-06 16:18'])
db.run(insert, ['Pizza', 14, 'Food', 'Mcdonald', '2020-06-01 18:14', '2020-05-01 18:14'])
}
}
);
}
});
module.exports = db
Here, we are creating a new sqlite database and load some sample data.
Open server.js and place below code −
var express = require("express")
var cors = require('cors')
var db = require("./sqlitedb.js")
var app = express()
app.use(cors());
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var HTTP_PORT = 8000
app.listen(HTTP_PORT, () => {
console.log("Server running on port %PORT%".replace("%PORT%",HTTP_PORT))
});
app.get("/", (req, res, next) => {
res.json({"message":"Ok"})
});
app.get("/api/expense", (req, res, next) => {
var sql = "select * from expense"
var params = []
db.all(sql, params, (err, rows) => {
if (err) {
res.status(400).json({"error":err.message});
return;
}
res.json(rows)
});
});
app.get("/api/expense/:id", (req, res, next) => {
var sql = "select * from expense where id = ?"
var params = [req.params.id]
db.get(sql, params, (err, row) => {
if (err) {
res.status(400).json({"error":err.message});
return;
}
res.json(row)
});
});
app.post("/api/expense/", (req, res, next) => {
var errors=[]
if (!req.body.item){
errors.push("No item specified");
}
var data = {
item : req.body.item,
amount: req.body.amount,
category: req.body.category,
location : req.body.location,
spendOn: req.body.spendOn,
createdOn: req.body.createdOn,
}
var sql = 'INSERT INTO expense (item, amount, category, location, spendOn, createdOn) VALUES (?,?,?,?,?,?)'
var params =[data.item, data.amount, data.category, data.location, data.spendOn, data.createdOn]
db.run(sql, params, function (err, result) {
if (err){
res.status(400).json({"error": err.message})
return;
}
data.id = this.lastID;
res.json(data);
});
})
app.put("/api/expense/:id", (req, res, next) => {
var data = {
item : req.body.item,
amount: req.body.amount,
category: req.body.category,
location : req.body.location,
spendOn: req.body.spendOn
}
db.run(
`UPDATE expense SET
item = ?,
amount = ?,
category = ?,
location = ?,
spendOn = ?
WHERE id = ?`,
[data.item, data.amount, data.category, data.location,data.spendOn, req.params.id],
function (err, result) {
if (err){
console.log(err);
res.status(400).json({"error": res.message})
return;
}
res.json(data)
});
})
app.delete("/api/expense/:id", (req, res, next) => {
db.run(
'DELETE FROM expense WHERE id = ?',
req.params.id,
function (err, result) {
if (err){
res.status(400).json({"error": res.message})
return;
}
res.json({"message":"deleted", changes: this.changes})
});
})
app.use(function(req, res){
res.status(404);
});
Here, we create a basic CURD rest api to select, insert, update and delete expense entry.
Run the application using below command −
npm run start
Open a browser, enter http://localhost:8000/ and press enter. You will see below response −
{
"message": "Ok"
}
It confirms our application is working fine.
Change the url to http://localhost:8000/api/expense and you will see all the expense entries in JSON format.
[
{
"id": 1,
"item": "Pizza",
"amount": 10,
"category": "Food",
"location": "KFC",
"spendOn": "2020-05-26 10:10",
"createdOn": "2020-05-26 10:10"
},
{
"id": 2,
"item": "Pizza",
"amount": 14,
"category": "Food",
"location": "Mcdonald",
"spendOn": "2020-06-01 18:14",
"createdOn": "2020-05-01 18:14"
},
{
"id": 3,
"item": "Pizza",
"amount": 15,
"category": "Food",
"location": "KFC",
"spendOn": "2020-06-06 16:18",
"createdOn": "2020-06-06 16:18"
},
{
"id": 4,
"item": "Pizza",
"amount": 9,
"category": "Food",
"location": "Mcdonald",
"spendOn": "2020-05-28 11:10",
"createdOn": "2020-05-28 11:10"
},
{
"id": 5,
"item": "Pizza",
"amount": 12,
"category": "Food",
"location": "Mcdonald",
"spendOn": "2020-05-29 09:22",
"createdOn": "2020-05-29 09:22"
}
]
Finally, we created a simple CURD REST API for expense entry and we can access the REST API from our Angular application to learn HttpClient module.
Let us learn how to configure HttpClient service in this chapter.
HttpClient service is available inside the HttpClientModule module, which is available inside the @angular/common/http package.
To register HttpClientModule module −
Import the HttpClientModule in AppComponent
import { HttpClientModule } from '@angular/common/http';
Include HttpClientModule in imports meta data of AppComponent.
@NgModule({
imports: [
BrowserModule,
// import HttpClientModule after BrowserModule.
HttpClientModule,
]
})
export class AppModule {}
Let us create a new service ExpenseEntryService in our ExpenseManager application to interact with Expense REST API. ExpenseEntryService will get the latest expense entries, insert new expense entries, modify existing expense entries and delete the unwanted expense entries.
Open command prompt and go to project root folder.
cd /go/to/expense-manager
Start the application.
ng serve
Run the below command to generate an Angular service, ExpenseService.
ng generate service ExpenseEntry
This will create two Typescript files (expense entry service & its test) as specified below −
CREATE src/app/expense-entry.service.spec.ts (364 bytes)
CREATE src/app/expense-entry.service.ts (141 bytes)
Open ExpenseEntryService (src/app/expense-entry.service.ts) and import ExpenseEntry, throwError and catchError from rxjs library and import HttpClient, HttpHeaders and HttpErrorResponse from @angular/common/http package.
import { Injectable } from '@angular/core';
import { ExpenseEntry } from './expense-entry'; import { throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { HttpClient, HttpHeaders, HttpErrorResponse } from
'@angular/common/http';
Inject the HttpClient service into our service.
constructor(private httpClient : HttpClient) { }
Create a variable, expenseRestUrl to specify the Expense Rest API endpoints.
private expenseRestUrl = 'http://localhost:8000/api/expense';
Create a variable, httpOptions to set the Http Header option. This will be used during the Http Rest API call by Angular HttpClient service.
private httpOptions = {
headers: new HttpHeaders( { 'Content-Type': 'application/json' })
};
The complete code is as follows −
import { Injectable } from '@angular/core';
import { ExpenseEntry } from './expense-entry';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ExpenseEntryService {
private expenseRestUrl = 'api/expense';
private httpOptions = {
headers: new HttpHeaders( { 'Content-Type': 'application/json' })
};
constructor(
private httpClient : HttpClient) { }
}
HttpClient provides get() method to fetch data from a web page. The main argument is the target web url. Another optional argument is the option object with below format −
{
headers?: HttpHeaders | {[header: string]: string | string[]},
observe?: 'body' | 'events' | 'response',
params?: HttpParams|{[param: string]: string | string[]},
reportProgress?: boolean,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
}
Here,
headers − HTTP Headers of the request, either as string, array of string or array of HttpHeaders.
headers − HTTP Headers of the request, either as string, array of string or array of HttpHeaders.
observe − Process the response and return the specific content of the response. Possible values are body, response and events. The default option of observer is body.
observe − Process the response and return the specific content of the response. Possible values are body, response and events. The default option of observer is body.
params − HTTP parameters of the request, either as string, array of string or array of HttpParams.
params − HTTP parameters of the request, either as string, array of string or array of HttpParams.
reportProgress − Whether to report the progress of the process or not (true or false).
reportProgress − Whether to report the progress of the process or not (true or false).
responseType − Refers the format of the response. Possible values are arraybuffer, blob, json and text.
responseType − Refers the format of the response. Possible values are arraybuffer, blob, json and text.
withCredentials − Whether the request has credentials or not (true or false).
withCredentials − Whether the request has credentials or not (true or false).
All options are optional.
get() method returns the response of the request as Observable. The returned Observable emit the data when the response is received from the server.
The sample code to use get() method is as follows −
httpClient.get(url, options)
.subscribe( (data) => console.log(data) );
get() method has an option to return observables, which emits typed response as well. The sample code to get typed response (ExpenseEntry) is as follows:
httpClient.get<T>(url, options) .subscribe( (data: T) => console.log(data) );
Error handling is one of the important aspect in the HTTP programming. Encountering error is one of the common scenario in HTTP programming.
Errors in HTTP Programming can be categories into two groups −
Client side issues can occur due to network failure, misconfiguration, etc., If client side error happens, then the get() method throws ErrorEvent object.
Client side issues can occur due to network failure, misconfiguration, etc., If client side error happens, then the get() method throws ErrorEvent object.
Server side issues can occur due to wrong url, server unavailability, server programming errors, etc.,
Server side issues can occur due to wrong url, server unavailability, server programming errors, etc.,
Let us write a simple error handling for our ExpenseEntryService service.
private httpErrorHandler (error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
console.error("A client side error occurs. The error message is " + error.message);
} else {
console.error(
"An error happened in server. The HTTP status code is " + error.status + " and the error returned is " + error.message);
}
return throwError("Error occurred. Pleas try again");
}
The error function can be called in get() as specified below −
httpClient.get(url, options)
.pipe(catchError(this.httpErrorHandler)
.subscribe( (data) => console.log(data) )
As we mentioned earlier, errors can happen and one way is to handle it. Another option is to try for certain number of times. If the request failed due to network issue or the HTTP server is temporarily offline, the next request may succeed.
We can use rxjs library’s retry operator in this scenario as specified below
httpClient.get(url, options)
.pipe(
retry(5),
catchError(this.httpErrorHandler))
.subscribe( (data) => console.log(data) )
Let us do the actual coding to fetch the expenses from Expense Rest API in our ExpenseManager application.
Open command prompt and go to project root folder.
cd /go/to/expense-manager
Start the application.
ng serve
Add getExpenseEntries() and httpErrorHandler() method in ExpenseEntryService (src/app/expense-entry.service.ts) service.
getExpenseEntries() : Observable<ExpenseEntry[]> {
return this.httpClient.get<ExpenseEntry[]>(this.expenseRestUrl, this.httpOptions)
.pipe(retry(3),catchError(this.httpErrorHandler));
}
getExpenseEntry(id: number) : Observable<ExpenseEntry> {
return this.httpClient.get<ExpenseEntry>(this.expenseRestUrl + "/" + id, this.httpOptions)
.pipe(
retry(3),
catchError(this.httpErrorHandler)
);
}
private httpErrorHandler (error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
console.error("A client side error occurs. The error message is " + error.message);
} else {
console.error(
"An error happened in server. The HTTP status code is " + error.status + " and the error returned is " + error.message);
}
return throwError("Error occurred. Pleas try again");
}
Here,
getExpenseEntries() calls the get() method using expense end point and also configures the error handler. Also, it configures httpClient to try for maximum of 3 times in case of failure. Finally, it returns the response from server as typed (ExpenseEntry[]) Observable object.
getExpenseEntries() calls the get() method using expense end point and also configures the error handler. Also, it configures httpClient to try for maximum of 3 times in case of failure. Finally, it returns the response from server as typed (ExpenseEntry[]) Observable object.
getExpenseEntry is similar to getExpenseEntries() except it passes the id of the ExpenseEntry object and gets ExpenseEntry Observable object.
getExpenseEntry is similar to getExpenseEntries() except it passes the id of the ExpenseEntry object and gets ExpenseEntry Observable object.
The complete coding of ExpenseEntryService is as follows −
import { Injectable } from '@angular/core';
import { ExpenseEntry } from './expense-entry';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ExpenseEntryService {
private expenseRestUrl = 'http://localhost:8000/api/expense';
private httpOptions = {
headers: new HttpHeaders( { 'Content-Type': 'application/json' })
};
constructor(private httpClient : HttpClient) { }
getExpenseEntries() : Observable {
return this.httpClient.get(this.expenseRestUrl, this.httpOptions)
.pipe(
retry(3),
catchError(this.httpErrorHandler)
);
}
getExpenseEntry(id: number) : Observable {
return this.httpClient.get(this.expenseRestUrl + "/" + id, this.httpOptions)
.pipe(
retry(3),
catchError(this.httpErrorHandler)
);
}
private httpErrorHandler (error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
console.error("A client side error occurs. The error message is " + error.message);
} else {
console.error(
"An error happened in server. The HTTP status code is " + error.status + " and the error returned is " + error.message);
}
return throwError("Error occurred. Pleas try again");
}
}
Open ExpenseEntryListComponent (src-entry-list-entry-list.component.ts) and inject ExpenseEntryService through constructor as specified below:
constructor(private debugService: DebugService, private restService :
ExpenseEntryService ) { }
Change the getExpenseEntries() function. Call getExpenseEntries() method from ExpenseEntryService instead of returning the mock items.
getExpenseItems() {
this.restService.getExpenseEntries()
.subscribe( data =− this.expenseEntries = data );
}
The complete ExpenseEntryListComponent coding is as follows −
import { Component, OnInit } from '@angular/core';
import { ExpenseEntry } from '../expense-entry';
import { DebugService } from '../debug.service';
import { ExpenseEntryService } from '../expense-entry.service';
@Component({
selector: 'app-expense-entry-list',
templateUrl: './expense-entry-list.component.html',
styleUrls: ['./expense-entry-list.component.css'],
providers: [DebugService]
})
export class ExpenseEntryListComponent implements OnInit {
title: string;
expenseEntries: ExpenseEntry[];
constructor(private debugService: DebugService, private restService : ExpenseEntryService ) { }
ngOnInit() {
this.debugService.info("Expense Entry List component initialized");
this.title = "Expense Entry List";
this.getExpenseItems();
}
getExpenseItems() {
this.restService.getExpenseEntries()
.subscribe( data => this.expenseEntries = data );
}
}
Finally, check the application and you will see the below response.
HTTP POST is similar to HTTP GET except that the post request will send the necessary data as posted content along with the request. HTTP POST is used to insert new record into the system.
HttpClient provides post() method, which is similar to get() except it support extra argument to send the data to the server.
Let us add a new method, addExpenseEntry() in our ExpenseEntryService to add new expense entry as mentioned below −
addExpenseEntry(expenseEntry: ExpenseEntry): Observable<ExpenseEntry> {
return this.httpClient.post<ExpenseEntry>(this.expenseRestUrl, expenseEntry, this.httpOptions)
.pipe(
retry(3),
catchError(this.httpErrorHandler)
);
}
HTTP PUT is similar to HTTP POST request. HTTP PUT is used to update existing record in the system.
httpClient provides put() method, which is similar to post().
Let us add a new method, updateExpenseEntry() in our ExpenseEntryService to update existing expense entry as mentioned below:
updateExpenseEntry(expenseEntry: ExpenseEntry): Observable<ExpenseEntry> {
return this.httpClient.put<ExpenseEntry>(this.expenseRestUrl + "/" + expenseEntry.id, expenseEntry, this.httpOptions)
.pipe(
retry(3),
catchError(this.httpErrorHandler)
);
}
HTTP DELETE is similar to http GET request. HTTP DELETE is used to delete entries in the system.
httpclient provides delete() method, which is similar to get().
Let us add a new method, deleteExpenseEntry() in our ExpenseEntryService to delete existing expense entry as mentioned below −
deleteExpenseEntry(expenseEntry: ExpenseEntry | number) : Observable<ExpenseEntry> {
const id = typeof expenseEntry == 'number' ? expenseEntry : expenseEntry.id
const url = `${this.expenseRestUrl}/${id}`;
return this.httpClient.delete<ExpenseEntry>(url, this.httpOptions)
.pipe(
retry(3),
catchError(this.httpErrorHandler)
);
}
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2765,
"s": 2388,
"text": "Http client programming is a must needed feature in every modern web application. Nowadays, lot of application exposes their functionality through REST API (functionality over HTTP protocol). With this in mind, Angular Team provides extensive support to access HTTP server. Angular provides a separate module, HttpClientModule and a service, HttpClient to do HTTP programming."
},
{
"code": null,
"e": 2920,
"s": 2765,
"text": "Let us learn how to how to use HttpClient service in this chapter. Developer should have a basic knowledge in Http programming to understand this chapter."
},
{
"code": null,
"e": 3223,
"s": 2920,
"text": "The prerequisite to do Http programming is the basic knowledge of Http protocol and REST API technique. Http programming involves two part, server and client. Angular provides support to create client side application. Express a popular web framework provides support to create server side application."
},
{
"code": null,
"e": 3370,
"s": 3223,
"text": "Let us create an Expense Rest API using express framework and then access it from our ExpenseManager application using Angular HttpClient service."
},
{
"code": null,
"e": 3435,
"s": 3370,
"text": "Open a command prompt and create a new folder, express-rest-api."
},
{
"code": null,
"e": 3501,
"s": 3435,
"text": "cd /go/to/workspace \nmkdir express-rest-api \ncd expense-rest-api\n"
},
{
"code": null,
"e": 3557,
"s": 3501,
"text": "Initialise a new node application using below command −"
},
{
"code": null,
"e": 3567,
"s": 3557,
"text": "npm init\n"
},
{
"code": null,
"e": 3696,
"s": 3567,
"text": "npm init will ask some basic questions like project name (express-rest-api), entry point (server.js), etc., as mentioned below −"
},
{
"code": null,
"e": 4630,
"s": 3696,
"text": "This utility will walk you through creating a package.json file. \nIt only covers the most common items, and tries to guess sensible defaults. \nSee `npm help json` for definitive documentation on these fields and exactly what they do. \nUse `npm install <pkg>` afterwards to install a package and save it as a dependency in the package.json file. \nPress ^C at any time to quit. \npackage name: (expense-rest-api) \nversion: (1.0.0) \ndescription: Rest api for Expense Application \nentry point: (index.js) server.js \ntest command:\ngit repository: \nkeywords: \nauthor: \nlicense: (ISC) \nAbout to write to \\path\\to\\workspace\\expense-rest-api\\package.json: { \n \"name\": \"expense-rest-api\", \n \"version\": \"1.0.0\", \n \"description\": \"Rest api for Expense Application\", \n \"main\": \"server.js\", \n \"scripts\": { \n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\" \n }, \n \"author\": \"\", \n \"license\": \"ISC\" \n} \nIs this OK? (yes) yes"
},
{
"code": null,
"e": 4693,
"s": 4630,
"text": "Install express, sqlite and cors modules using below command −"
},
{
"code": null,
"e": 4727,
"s": 4693,
"text": "npm install express sqlite3 cors\n"
},
{
"code": null,
"e": 4780,
"s": 4727,
"text": "Create a new file sqlitedb.js and place below code −"
},
{
"code": null,
"e": 6117,
"s": 4780,
"text": "var sqlite3 = require('sqlite3').verbose()\nconst DBSOURCE = \"expensedb.sqlite\"\n\nlet db = new sqlite3.Database(DBSOURCE, (err) => {\n if (err) {\n console.error(err.message)\n throw err\n }else{\n console.log('Connected to the SQLite database.')\n db.run(`CREATE TABLE expense (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n item text, \n amount real, \n category text, \n location text, \n spendOn text, \n createdOn text \n )`,\n (err) => {\n if (err) {\n console.log(err);\n }else{\n var insert = 'INSERT INTO expense (item, amount, category, location, spendOn, createdOn) VALUES (?,?,?,?,?,?)'\n\n db.run(insert, ['Pizza', 10, 'Food', 'KFC', '2020-05-26 10:10', '2020-05-26 10:10'])\n db.run(insert, ['Pizza', 9, 'Food', 'Mcdonald', '2020-05-28 11:10', '2020-05-28 11:10'])\n db.run(insert, ['Pizza', 12, 'Food', 'Mcdonald', '2020-05-29 09:22', '2020-05-29 09:22'])\n db.run(insert, ['Pizza', 15, 'Food', 'KFC', '2020-06-06 16:18', '2020-06-06 16:18'])\n db.run(insert, ['Pizza', 14, 'Food', 'Mcdonald', '2020-06-01 18:14', '2020-05-01 18:14'])\n }\n }\n ); \n }\n});\n\nmodule.exports = db"
},
{
"code": null,
"e": 6188,
"s": 6117,
"text": "Here, we are creating a new sqlite database and load some sample data."
},
{
"code": null,
"e": 6226,
"s": 6188,
"text": "Open server.js and place below code −"
},
{
"code": null,
"e": 9126,
"s": 6226,
"text": "var express = require(\"express\")\nvar cors = require('cors')\nvar db = require(\"./sqlitedb.js\")\n\nvar app = express()\napp.use(cors());\n\nvar bodyParser = require(\"body-parser\");\napp.use(bodyParser.urlencoded({ extended: false }));\napp.use(bodyParser.json());\n\nvar HTTP_PORT = 8000 \napp.listen(HTTP_PORT, () => {\n console.log(\"Server running on port %PORT%\".replace(\"%PORT%\",HTTP_PORT))\n});\n\napp.get(\"/\", (req, res, next) => {\n res.json({\"message\":\"Ok\"})\n});\n\napp.get(\"/api/expense\", (req, res, next) => {\n var sql = \"select * from expense\"\n var params = []\n db.all(sql, params, (err, rows) => {\n if (err) {\n res.status(400).json({\"error\":err.message});\n return;\n }\n res.json(rows)\n });\n\n});\n\napp.get(\"/api/expense/:id\", (req, res, next) => {\n var sql = \"select * from expense where id = ?\"\n var params = [req.params.id]\n db.get(sql, params, (err, row) => {\n if (err) {\n res.status(400).json({\"error\":err.message});\n return;\n }\n res.json(row)\n });\n});\n\napp.post(\"/api/expense/\", (req, res, next) => {\n var errors=[]\n if (!req.body.item){\n errors.push(\"No item specified\");\n }\n var data = {\n item : req.body.item,\n amount: req.body.amount,\n category: req.body.category,\n location : req.body.location,\n spendOn: req.body.spendOn,\n createdOn: req.body.createdOn,\n }\n var sql = 'INSERT INTO expense (item, amount, category, location, spendOn, createdOn) VALUES (?,?,?,?,?,?)'\n var params =[data.item, data.amount, data.category, data.location, data.spendOn, data.createdOn]\n db.run(sql, params, function (err, result) {\n if (err){\n res.status(400).json({\"error\": err.message})\n return;\n }\n data.id = this.lastID;\n res.json(data);\n });\n})\n\napp.put(\"/api/expense/:id\", (req, res, next) => {\n var data = {\n item : req.body.item,\n amount: req.body.amount,\n category: req.body.category,\n location : req.body.location,\n spendOn: req.body.spendOn\n }\n db.run(\n `UPDATE expense SET\n item = ?, \n\n amount = ?,\n category = ?, \n location = ?, \n\n spendOn = ? \n WHERE id = ?`,\n [data.item, data.amount, data.category, data.location,data.spendOn, req.params.id],\n function (err, result) {\n if (err){\n console.log(err);\n res.status(400).json({\"error\": res.message})\n return;\n }\n res.json(data)\n });\n})\n\napp.delete(\"/api/expense/:id\", (req, res, next) => {\n db.run(\n 'DELETE FROM expense WHERE id = ?',\n req.params.id,\n function (err, result) {\n if (err){\n res.status(400).json({\"error\": res.message})\n return;\n }\n res.json({\"message\":\"deleted\", changes: this.changes})\n });\n})\n\napp.use(function(req, res){\n res.status(404);\n});"
},
{
"code": null,
"e": 9216,
"s": 9126,
"text": "Here, we create a basic CURD rest api to select, insert, update and delete expense entry."
},
{
"code": null,
"e": 9258,
"s": 9216,
"text": "Run the application using below command −"
},
{
"code": null,
"e": 9273,
"s": 9258,
"text": "npm run start\n"
},
{
"code": null,
"e": 9365,
"s": 9273,
"text": "Open a browser, enter http://localhost:8000/ and press enter. You will see below response −"
},
{
"code": null,
"e": 9391,
"s": 9365,
"text": "{ \n \"message\": \"Ok\" \n}\n"
},
{
"code": null,
"e": 9436,
"s": 9391,
"text": "It confirms our application is working fine."
},
{
"code": null,
"e": 9545,
"s": 9436,
"text": "Change the url to http://localhost:8000/api/expense and you will see all the expense entries in JSON format."
},
{
"code": null,
"e": 10538,
"s": 9545,
"text": "[\n {\n \"id\": 1,\n\n \"item\": \"Pizza\",\n \"amount\": 10,\n \"category\": \"Food\",\n \"location\": \"KFC\",\n \"spendOn\": \"2020-05-26 10:10\",\n \"createdOn\": \"2020-05-26 10:10\"\n },\n {\n \"id\": 2,\n \"item\": \"Pizza\",\n \"amount\": 14,\n \"category\": \"Food\",\n \"location\": \"Mcdonald\",\n \"spendOn\": \"2020-06-01 18:14\",\n \"createdOn\": \"2020-05-01 18:14\"\n },\n {\n \"id\": 3,\n \"item\": \"Pizza\",\n \"amount\": 15,\n \"category\": \"Food\",\n \"location\": \"KFC\",\n \"spendOn\": \"2020-06-06 16:18\",\n \"createdOn\": \"2020-06-06 16:18\"\n },\n {\n \"id\": 4,\n \"item\": \"Pizza\",\n \"amount\": 9,\n \"category\": \"Food\",\n \"location\": \"Mcdonald\",\n \"spendOn\": \"2020-05-28 11:10\",\n \"createdOn\": \"2020-05-28 11:10\"\n },\n {\n \"id\": 5,\n \"item\": \"Pizza\",\n \"amount\": 12,\n \"category\": \"Food\",\n \"location\": \"Mcdonald\",\n \"spendOn\": \"2020-05-29 09:22\",\n \"createdOn\": \"2020-05-29 09:22\"\n }\n]"
},
{
"code": null,
"e": 10687,
"s": 10538,
"text": "Finally, we created a simple CURD REST API for expense entry and we can access the REST API from our Angular application to learn HttpClient module."
},
{
"code": null,
"e": 10753,
"s": 10687,
"text": "Let us learn how to configure HttpClient service in this chapter."
},
{
"code": null,
"e": 10881,
"s": 10753,
"text": "HttpClient service is available inside the HttpClientModule module, which is available inside the @angular/common/http package."
},
{
"code": null,
"e": 10919,
"s": 10881,
"text": "To register HttpClientModule module −"
},
{
"code": null,
"e": 10963,
"s": 10919,
"text": "Import the HttpClientModule in AppComponent"
},
{
"code": null,
"e": 11021,
"s": 10963,
"text": "import { HttpClientModule } from '@angular/common/http';\n"
},
{
"code": null,
"e": 11084,
"s": 11021,
"text": "Include HttpClientModule in imports meta data of AppComponent."
},
{
"code": null,
"e": 11251,
"s": 11084,
"text": "@NgModule({ \n imports: [ \n BrowserModule, \n // import HttpClientModule after BrowserModule. \n HttpClientModule, \n ] \n}) \nexport class AppModule {}\n"
},
{
"code": null,
"e": 11526,
"s": 11251,
"text": "Let us create a new service ExpenseEntryService in our ExpenseManager application to interact with Expense REST API. ExpenseEntryService will get the latest expense entries, insert new expense entries, modify existing expense entries and delete the unwanted expense entries."
},
{
"code": null,
"e": 11577,
"s": 11526,
"text": "Open command prompt and go to project root folder."
},
{
"code": null,
"e": 11604,
"s": 11577,
"text": "cd /go/to/expense-manager\n"
},
{
"code": null,
"e": 11627,
"s": 11604,
"text": "Start the application."
},
{
"code": null,
"e": 11637,
"s": 11627,
"text": "ng serve\n"
},
{
"code": null,
"e": 11707,
"s": 11637,
"text": "Run the below command to generate an Angular service, ExpenseService."
},
{
"code": null,
"e": 11741,
"s": 11707,
"text": "ng generate service ExpenseEntry\n"
},
{
"code": null,
"e": 11835,
"s": 11741,
"text": "This will create two Typescript files (expense entry service & its test) as specified below −"
},
{
"code": null,
"e": 11946,
"s": 11835,
"text": "CREATE src/app/expense-entry.service.spec.ts (364 bytes) \nCREATE src/app/expense-entry.service.ts (141 bytes)\n"
},
{
"code": null,
"e": 12167,
"s": 11946,
"text": "Open ExpenseEntryService (src/app/expense-entry.service.ts) and import ExpenseEntry, throwError and catchError from rxjs library and import HttpClient, HttpHeaders and HttpErrorResponse from @angular/common/http package."
},
{
"code": null,
"e": 12426,
"s": 12167,
"text": "import { Injectable } from '@angular/core'; \nimport { ExpenseEntry } from './expense-entry'; import { throwError } from 'rxjs';\nimport { catchError } from 'rxjs/operators'; \nimport { HttpClient, HttpHeaders, HttpErrorResponse } from \n'@angular/common/http';\n"
},
{
"code": null,
"e": 12474,
"s": 12426,
"text": "Inject the HttpClient service into our service."
},
{
"code": null,
"e": 12524,
"s": 12474,
"text": "constructor(private httpClient : HttpClient) { }\n"
},
{
"code": null,
"e": 12601,
"s": 12524,
"text": "Create a variable, expenseRestUrl to specify the Expense Rest API endpoints."
},
{
"code": null,
"e": 12664,
"s": 12601,
"text": "private expenseRestUrl = 'http://localhost:8000/api/expense';\n"
},
{
"code": null,
"e": 12805,
"s": 12664,
"text": "Create a variable, httpOptions to set the Http Header option. This will be used during the Http Rest API call by Angular HttpClient service."
},
{
"code": null,
"e": 12904,
"s": 12805,
"text": "private httpOptions = { \n headers: new HttpHeaders( { 'Content-Type': 'application/json' }) \n};\n"
},
{
"code": null,
"e": 12938,
"s": 12904,
"text": "The complete code is as follows −"
},
{
"code": null,
"e": 13498,
"s": 12938,
"text": "import { Injectable } from '@angular/core';\nimport { ExpenseEntry } from './expense-entry';\nimport { Observable, throwError } from 'rxjs';\nimport { catchError, retry } from 'rxjs/operators';\nimport { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';\n\n@Injectable({\n providedIn: 'root'\n})\nexport class ExpenseEntryService {\n private expenseRestUrl = 'api/expense';\n private httpOptions = {\n headers: new HttpHeaders( { 'Content-Type': 'application/json' })\n };\n\n constructor(\n private httpClient : HttpClient) { }\n}\n"
},
{
"code": null,
"e": 13670,
"s": 13498,
"text": "HttpClient provides get() method to fetch data from a web page. The main argument is the target web url. Another optional argument is the option object with below format −"
},
{
"code": null,
"e": 13961,
"s": 13670,
"text": "{\n headers?: HttpHeaders | {[header: string]: string | string[]},\n observe?: 'body' | 'events' | 'response',\n\n params?: HttpParams|{[param: string]: string | string[]},\n reportProgress?: boolean,\n responseType?: 'arraybuffer'|'blob'|'json'|'text',\n withCredentials?: boolean,\n}\n"
},
{
"code": null,
"e": 13967,
"s": 13961,
"text": "Here,"
},
{
"code": null,
"e": 14065,
"s": 13967,
"text": "headers − HTTP Headers of the request, either as string, array of string or array of HttpHeaders."
},
{
"code": null,
"e": 14163,
"s": 14065,
"text": "headers − HTTP Headers of the request, either as string, array of string or array of HttpHeaders."
},
{
"code": null,
"e": 14330,
"s": 14163,
"text": "observe − Process the response and return the specific content of the response. Possible values are body, response and events. The default option of observer is body."
},
{
"code": null,
"e": 14497,
"s": 14330,
"text": "observe − Process the response and return the specific content of the response. Possible values are body, response and events. The default option of observer is body."
},
{
"code": null,
"e": 14596,
"s": 14497,
"text": "params − HTTP parameters of the request, either as string, array of string or array of HttpParams."
},
{
"code": null,
"e": 14695,
"s": 14596,
"text": "params − HTTP parameters of the request, either as string, array of string or array of HttpParams."
},
{
"code": null,
"e": 14782,
"s": 14695,
"text": "reportProgress − Whether to report the progress of the process or not (true or false)."
},
{
"code": null,
"e": 14869,
"s": 14782,
"text": "reportProgress − Whether to report the progress of the process or not (true or false)."
},
{
"code": null,
"e": 14973,
"s": 14869,
"text": "responseType − Refers the format of the response. Possible values are arraybuffer, blob, json and text."
},
{
"code": null,
"e": 15077,
"s": 14973,
"text": "responseType − Refers the format of the response. Possible values are arraybuffer, blob, json and text."
},
{
"code": null,
"e": 15155,
"s": 15077,
"text": "withCredentials − Whether the request has credentials or not (true or false)."
},
{
"code": null,
"e": 15233,
"s": 15155,
"text": "withCredentials − Whether the request has credentials or not (true or false)."
},
{
"code": null,
"e": 15259,
"s": 15233,
"text": "All options are optional."
},
{
"code": null,
"e": 15408,
"s": 15259,
"text": "get() method returns the response of the request as Observable. The returned Observable emit the data when the response is received from the server."
},
{
"code": null,
"e": 15460,
"s": 15408,
"text": "The sample code to use get() method is as follows −"
},
{
"code": null,
"e": 15534,
"s": 15460,
"text": "httpClient.get(url, options) \n.subscribe( (data) => console.log(data) );\n"
},
{
"code": null,
"e": 15688,
"s": 15534,
"text": "get() method has an option to return observables, which emits typed response as well. The sample code to get typed response (ExpenseEntry) is as follows:"
},
{
"code": null,
"e": 15767,
"s": 15688,
"text": "httpClient.get<T>(url, options) .subscribe( (data: T) => console.log(data) );\n"
},
{
"code": null,
"e": 15908,
"s": 15767,
"text": "Error handling is one of the important aspect in the HTTP programming. Encountering error is one of the common scenario in HTTP programming."
},
{
"code": null,
"e": 15971,
"s": 15908,
"text": "Errors in HTTP Programming can be categories into two groups −"
},
{
"code": null,
"e": 16126,
"s": 15971,
"text": "Client side issues can occur due to network failure, misconfiguration, etc., If client side error happens, then the get() method throws ErrorEvent object."
},
{
"code": null,
"e": 16281,
"s": 16126,
"text": "Client side issues can occur due to network failure, misconfiguration, etc., If client side error happens, then the get() method throws ErrorEvent object."
},
{
"code": null,
"e": 16384,
"s": 16281,
"text": "Server side issues can occur due to wrong url, server unavailability, server programming errors, etc.,"
},
{
"code": null,
"e": 16487,
"s": 16384,
"text": "Server side issues can occur due to wrong url, server unavailability, server programming errors, etc.,"
},
{
"code": null,
"e": 16561,
"s": 16487,
"text": "Let us write a simple error handling for our ExpenseEntryService service."
},
{
"code": null,
"e": 16991,
"s": 16561,
"text": "private httpErrorHandler (error: HttpErrorResponse) {\n if (error.error instanceof ErrorEvent) {\n console.error(\"A client side error occurs. The error message is \" + error.message);\n } else {\n console.error(\n \"An error happened in server. The HTTP status code is \" + error.status + \" and the error returned is \" + error.message);\n }\n\n return throwError(\"Error occurred. Pleas try again\");\n}\n"
},
{
"code": null,
"e": 17054,
"s": 16991,
"text": "The error function can be called in get() as specified below −"
},
{
"code": null,
"e": 17175,
"s": 17054,
"text": "httpClient.get(url, options) \n .pipe(catchError(this.httpErrorHandler) \n .subscribe( (data) => console.log(data) )\n"
},
{
"code": null,
"e": 17417,
"s": 17175,
"text": "As we mentioned earlier, errors can happen and one way is to handle it. Another option is to try for certain number of times. If the request failed due to network issue or the HTTP server is temporarily offline, the next request may succeed."
},
{
"code": null,
"e": 17494,
"s": 17417,
"text": "We can use rxjs library’s retry operator in this scenario as specified below"
},
{
"code": null,
"e": 17640,
"s": 17494,
"text": "httpClient.get(url, options) \n .pipe( \n retry(5), \n catchError(this.httpErrorHandler)) \n .subscribe( (data) => console.log(data) )\n"
},
{
"code": null,
"e": 17747,
"s": 17640,
"text": "Let us do the actual coding to fetch the expenses from Expense Rest API in our ExpenseManager application."
},
{
"code": null,
"e": 17798,
"s": 17747,
"text": "Open command prompt and go to project root folder."
},
{
"code": null,
"e": 17825,
"s": 17798,
"text": "cd /go/to/expense-manager\n"
},
{
"code": null,
"e": 17848,
"s": 17825,
"text": "Start the application."
},
{
"code": null,
"e": 17858,
"s": 17848,
"text": "ng serve\n"
},
{
"code": null,
"e": 17979,
"s": 17858,
"text": "Add getExpenseEntries() and httpErrorHandler() method in ExpenseEntryService (src/app/expense-entry.service.ts) service."
},
{
"code": null,
"e": 18815,
"s": 17979,
"text": "getExpenseEntries() : Observable<ExpenseEntry[]> {\n return this.httpClient.get<ExpenseEntry[]>(this.expenseRestUrl, this.httpOptions)\n .pipe(retry(3),catchError(this.httpErrorHandler));\n}\n\ngetExpenseEntry(id: number) : Observable<ExpenseEntry> {\n return this.httpClient.get<ExpenseEntry>(this.expenseRestUrl + \"/\" + id, this.httpOptions)\n .pipe(\n retry(3),\n catchError(this.httpErrorHandler)\n );\n}\n\nprivate httpErrorHandler (error: HttpErrorResponse) {\n if (error.error instanceof ErrorEvent) {\n console.error(\"A client side error occurs. The error message is \" + error.message);\n } else {\n console.error(\n \"An error happened in server. The HTTP status code is \" + error.status + \" and the error returned is \" + error.message);\n }\n\n return throwError(\"Error occurred. Pleas try again\");\n}"
},
{
"code": null,
"e": 18821,
"s": 18815,
"text": "Here,"
},
{
"code": null,
"e": 19098,
"s": 18821,
"text": "getExpenseEntries() calls the get() method using expense end point and also configures the error handler. Also, it configures httpClient to try for maximum of 3 times in case of failure. Finally, it returns the response from server as typed (ExpenseEntry[]) Observable object."
},
{
"code": null,
"e": 19375,
"s": 19098,
"text": "getExpenseEntries() calls the get() method using expense end point and also configures the error handler. Also, it configures httpClient to try for maximum of 3 times in case of failure. Finally, it returns the response from server as typed (ExpenseEntry[]) Observable object."
},
{
"code": null,
"e": 19517,
"s": 19375,
"text": "getExpenseEntry is similar to getExpenseEntries() except it passes the id of the ExpenseEntry object and gets ExpenseEntry Observable object."
},
{
"code": null,
"e": 19659,
"s": 19517,
"text": "getExpenseEntry is similar to getExpenseEntries() except it passes the id of the ExpenseEntry object and gets ExpenseEntry Observable object."
},
{
"code": null,
"e": 19718,
"s": 19659,
"text": "The complete coding of ExpenseEntryService is as follows −"
},
{
"code": null,
"e": 21159,
"s": 19718,
"text": "import { Injectable } from '@angular/core';\nimport { ExpenseEntry } from './expense-entry';\n\nimport { Observable, throwError } from 'rxjs';\nimport { catchError, retry } from 'rxjs/operators';\nimport { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';\n\n@Injectable({\n\n providedIn: 'root'\n})\nexport class ExpenseEntryService {\n private expenseRestUrl = 'http://localhost:8000/api/expense';\n private httpOptions = {\n headers: new HttpHeaders( { 'Content-Type': 'application/json' })\n };\n\n constructor(private httpClient : HttpClient) { } \n\n getExpenseEntries() : Observable {\n return this.httpClient.get(this.expenseRestUrl, this.httpOptions)\n .pipe(\n retry(3),\n catchError(this.httpErrorHandler)\n );\n }\n\n getExpenseEntry(id: number) : Observable {\n return this.httpClient.get(this.expenseRestUrl + \"/\" + id, this.httpOptions)\n .pipe(\n retry(3),\n catchError(this.httpErrorHandler)\n );\n }\n\n private httpErrorHandler (error: HttpErrorResponse) {\n if (error.error instanceof ErrorEvent) {\n console.error(\"A client side error occurs. The error message is \" + error.message);\n } else {\n console.error(\n \"An error happened in server. The HTTP status code is \" + error.status + \" and the error returned is \" + error.message);\n }\n\n return throwError(\"Error occurred. Pleas try again\");\n }\n}"
},
{
"code": null,
"e": 21302,
"s": 21159,
"text": "Open ExpenseEntryListComponent (src-entry-list-entry-list.component.ts) and inject ExpenseEntryService through constructor as specified below:"
},
{
"code": null,
"e": 21400,
"s": 21302,
"text": "constructor(private debugService: DebugService, private restService : \nExpenseEntryService ) { }\n"
},
{
"code": null,
"e": 21535,
"s": 21400,
"text": "Change the getExpenseEntries() function. Call getExpenseEntries() method from ExpenseEntryService instead of returning the mock items."
},
{
"code": null,
"e": 21658,
"s": 21535,
"text": "getExpenseItems() { \n this.restService.getExpenseEntries() \n .subscribe( data =− this.expenseEntries = data ); \n}\n"
},
{
"code": null,
"e": 21720,
"s": 21658,
"text": "The complete ExpenseEntryListComponent coding is as follows −"
},
{
"code": null,
"e": 22636,
"s": 21720,
"text": "import { Component, OnInit } from '@angular/core';\nimport { ExpenseEntry } from '../expense-entry';\nimport { DebugService } from '../debug.service';\nimport { ExpenseEntryService } from '../expense-entry.service';\n\n@Component({\n selector: 'app-expense-entry-list',\n templateUrl: './expense-entry-list.component.html',\n styleUrls: ['./expense-entry-list.component.css'],\n providers: [DebugService]\n})\nexport class ExpenseEntryListComponent implements OnInit {\n title: string;\n expenseEntries: ExpenseEntry[];\n constructor(private debugService: DebugService, private restService : ExpenseEntryService ) { }\n\n ngOnInit() {\n this.debugService.info(\"Expense Entry List component initialized\");\n this.title = \"Expense Entry List\";\n\n this.getExpenseItems();\n }\n\n getExpenseItems() {\n this.restService.getExpenseEntries()\n .subscribe( data => this.expenseEntries = data );\n }\n}"
},
{
"code": null,
"e": 22704,
"s": 22636,
"text": "Finally, check the application and you will see the below response."
},
{
"code": null,
"e": 22893,
"s": 22704,
"text": "HTTP POST is similar to HTTP GET except that the post request will send the necessary data as posted content along with the request. HTTP POST is used to insert new record into the system."
},
{
"code": null,
"e": 23019,
"s": 22893,
"text": "HttpClient provides post() method, which is similar to get() except it support extra argument to send the data to the server."
},
{
"code": null,
"e": 23135,
"s": 23019,
"text": "Let us add a new method, addExpenseEntry() in our ExpenseEntryService to add new expense entry as mentioned below −"
},
{
"code": null,
"e": 23379,
"s": 23135,
"text": "addExpenseEntry(expenseEntry: ExpenseEntry): Observable<ExpenseEntry> {\n return this.httpClient.post<ExpenseEntry>(this.expenseRestUrl, expenseEntry, this.httpOptions)\n .pipe(\n retry(3),\n catchError(this.httpErrorHandler)\n );\n}"
},
{
"code": null,
"e": 23479,
"s": 23379,
"text": "HTTP PUT is similar to HTTP POST request. HTTP PUT is used to update existing record in the system."
},
{
"code": null,
"e": 23541,
"s": 23479,
"text": "httpClient provides put() method, which is similar to post()."
},
{
"code": null,
"e": 23667,
"s": 23541,
"text": "Let us add a new method, updateExpenseEntry() in our ExpenseEntryService to update existing expense entry as mentioned below:"
},
{
"code": null,
"e": 23937,
"s": 23667,
"text": "updateExpenseEntry(expenseEntry: ExpenseEntry): Observable<ExpenseEntry> {\n return this.httpClient.put<ExpenseEntry>(this.expenseRestUrl + \"/\" + expenseEntry.id, expenseEntry, this.httpOptions)\n .pipe(\n retry(3),\n catchError(this.httpErrorHandler)\n );\n}"
},
{
"code": null,
"e": 24034,
"s": 23937,
"text": "HTTP DELETE is similar to http GET request. HTTP DELETE is used to delete entries in the system."
},
{
"code": null,
"e": 24098,
"s": 24034,
"text": "httpclient provides delete() method, which is similar to get()."
},
{
"code": null,
"e": 24225,
"s": 24098,
"text": "Let us add a new method, deleteExpenseEntry() in our ExpenseEntryService to delete existing expense entry as mentioned below −"
},
{
"code": null,
"e": 24581,
"s": 24225,
"text": "deleteExpenseEntry(expenseEntry: ExpenseEntry | number) : Observable<ExpenseEntry> {\n const id = typeof expenseEntry == 'number' ? expenseEntry : expenseEntry.id\n const url = `${this.expenseRestUrl}/${id}`;\n\n return this.httpClient.delete<ExpenseEntry>(url, this.httpOptions)\n .pipe(\n retry(3),\n catchError(this.httpErrorHandler)\n );\n}"
},
{
"code": null,
"e": 24616,
"s": 24581,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 24630,
"s": 24616,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 24665,
"s": 24630,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 24679,
"s": 24665,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 24714,
"s": 24679,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 24734,
"s": 24714,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 24769,
"s": 24734,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 24786,
"s": 24769,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 24819,
"s": 24786,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 24831,
"s": 24819,
"text": " Senol Atac"
},
{
"code": null,
"e": 24866,
"s": 24831,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 24878,
"s": 24866,
"text": " Senol Atac"
},
{
"code": null,
"e": 24885,
"s": 24878,
"text": " Print"
},
{
"code": null,
"e": 24896,
"s": 24885,
"text": " Add Notes"
}
] |
Tools to Securely Delete Files from Linux - GeeksforGeeks | 16 Feb, 2021
Every time you delete a file from your Linux system using the shift + delete or rm command, it doesn’t actually permanently and securely delete the file from the hard disk. When you delete a file with the rm command, the file system just frees up the appropriate inode but the contents of the old file are still in that space until it is overwritten which pave a way to recover the files.
The space that was used by the file that you deleted is now free to be used by other new files. But the contents of the old files are still in the hard disk, Until and unless that space is overwritten by something else, so there is a good chance that the file can be recovered by anyone (maybe by some data thieves) with good knowledge of recovering data. It is like removing the index page of a book, where the chapters are still there, it just becomes much hard to find, but we can find it.
Shred will help you to overwrite a deleted file, so it becomes difficult to recover it. It is like tearing a paper into as many pieces as you want or overwriting over the paper so that it becomes impossible to find out the original data.
manual of shred
shred
In the above output, the meaning of the letters are:
-u: deallocates and removes file after overwriting
-v: enables the display of operation progress
-z: adds a final overwrite with zeros to hide shredding
-n: total number of times the file content will be overwritten(I gave 6).
Secure-delete is a command containing a set of secure file deletion tools containing srm (secure_deletion) tool which is used to delete or overwrite the files securely in Linux. At first, we have to install it by typing:
sudo apt-get install secure-delete
install secure-delete
There is a total of 4 different types of tools consisting of this whole package and each of them performs a different type of securely delete operation. They are as follows:-
srm : It is a secure rm that is used to erase files by overwriting their hard disk space and deleting them.
sfill : It is used to overwrite free space on the hard disk.
sswap : It is used to overwrite swap space.
sdmem : It is used to wipe the RAM Once secure-delete is installed.
# srm Command:srm command deletes anything just like rm command but securely i.e by overwriting the file and its inode with random bytes. The larger the file, the longer it takes to wipe and rewrite it.
srm tool
Type srm man to get more information:
manual
The Linux wipe command allows us to securely erase data from our hard disk permanently. The wipe command erases files from magnetic memory and rewrites the space repeatedly and wipe away the caches which make the data nearly impossible to be recovered.
At first, we have to install a wipe:
sudo apt-get install wipe
Now you can use wipe for secure deletion
wipe
To know more about each function check wipe -h:
manual of wipe command
dd command is especially used to convert or copy files. We can use this command to completely overwrite your hard drive with zeros, but DD will not zero a drive currently in use
The syntax is :
- dd if=<source> of=<target> [Options]
In the above menu:
lsblk: Lists all the disks
/dev/urandom (input): The random data used for overwriting
/dev/sda (output): the disk that will be overwritten. This disk will be replaced with random garbage data.
See the help menu of the “dd” command for more details:
dd help menu
Linux-Tools
Picked
Technical Scripter 2020
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
Array Basics in Shell Scripting | Set 1
scp command in Linux with Examples
nohup Command in Linux with Examples
chown command in Linux with Examples
mv command in Linux with examples
Named Pipe or FIFO with example C program
SED command in Linux | Set 2
Basic Operators in Shell Scripting
Start/Stop/Restart Services Using Systemctl in Linux | [
{
"code": null,
"e": 24350,
"s": 24322,
"text": "\n16 Feb, 2021"
},
{
"code": null,
"e": 24739,
"s": 24350,
"text": "Every time you delete a file from your Linux system using the shift + delete or rm command, it doesn’t actually permanently and securely delete the file from the hard disk. When you delete a file with the rm command, the file system just frees up the appropriate inode but the contents of the old file are still in that space until it is overwritten which pave a way to recover the files."
},
{
"code": null,
"e": 25233,
"s": 24739,
"text": "The space that was used by the file that you deleted is now free to be used by other new files. But the contents of the old files are still in the hard disk, Until and unless that space is overwritten by something else, so there is a good chance that the file can be recovered by anyone (maybe by some data thieves) with good knowledge of recovering data. It is like removing the index page of a book, where the chapters are still there, it just becomes much hard to find, but we can find it. "
},
{
"code": null,
"e": 25471,
"s": 25233,
"text": "Shred will help you to overwrite a deleted file, so it becomes difficult to recover it. It is like tearing a paper into as many pieces as you want or overwriting over the paper so that it becomes impossible to find out the original data."
},
{
"code": null,
"e": 25487,
"s": 25471,
"text": "manual of shred"
},
{
"code": null,
"e": 25493,
"s": 25487,
"text": "shred"
},
{
"code": null,
"e": 25546,
"s": 25493,
"text": "In the above output, the meaning of the letters are:"
},
{
"code": null,
"e": 25597,
"s": 25546,
"text": "-u: deallocates and removes file after overwriting"
},
{
"code": null,
"e": 25643,
"s": 25597,
"text": "-v: enables the display of operation progress"
},
{
"code": null,
"e": 25699,
"s": 25643,
"text": "-z: adds a final overwrite with zeros to hide shredding"
},
{
"code": null,
"e": 25773,
"s": 25699,
"text": "-n: total number of times the file content will be overwritten(I gave 6)."
},
{
"code": null,
"e": 25994,
"s": 25773,
"text": "Secure-delete is a command containing a set of secure file deletion tools containing srm (secure_deletion) tool which is used to delete or overwrite the files securely in Linux. At first, we have to install it by typing:"
},
{
"code": null,
"e": 26030,
"s": 25994,
"text": "sudo apt-get install secure-delete "
},
{
"code": null,
"e": 26052,
"s": 26030,
"text": "install secure-delete"
},
{
"code": null,
"e": 26227,
"s": 26052,
"text": "There is a total of 4 different types of tools consisting of this whole package and each of them performs a different type of securely delete operation. They are as follows:-"
},
{
"code": null,
"e": 26335,
"s": 26227,
"text": "srm : It is a secure rm that is used to erase files by overwriting their hard disk space and deleting them."
},
{
"code": null,
"e": 26396,
"s": 26335,
"text": "sfill : It is used to overwrite free space on the hard disk."
},
{
"code": null,
"e": 26440,
"s": 26396,
"text": "sswap : It is used to overwrite swap space."
},
{
"code": null,
"e": 26508,
"s": 26440,
"text": "sdmem : It is used to wipe the RAM Once secure-delete is installed."
},
{
"code": null,
"e": 26711,
"s": 26508,
"text": "# srm Command:srm command deletes anything just like rm command but securely i.e by overwriting the file and its inode with random bytes. The larger the file, the longer it takes to wipe and rewrite it."
},
{
"code": null,
"e": 26720,
"s": 26711,
"text": "srm tool"
},
{
"code": null,
"e": 26758,
"s": 26720,
"text": "Type srm man to get more information:"
},
{
"code": null,
"e": 26766,
"s": 26758,
"text": " manual"
},
{
"code": null,
"e": 27020,
"s": 26766,
"text": "The Linux wipe command allows us to securely erase data from our hard disk permanently. The wipe command erases files from magnetic memory and rewrites the space repeatedly and wipe away the caches which make the data nearly impossible to be recovered. "
},
{
"code": null,
"e": 27057,
"s": 27020,
"text": "At first, we have to install a wipe:"
},
{
"code": null,
"e": 27083,
"s": 27057,
"text": "sudo apt-get install wipe"
},
{
"code": null,
"e": 27125,
"s": 27083,
"text": "Now you can use wipe for secure deletion "
},
{
"code": null,
"e": 27130,
"s": 27125,
"text": "wipe"
},
{
"code": null,
"e": 27178,
"s": 27130,
"text": "To know more about each function check wipe -h:"
},
{
"code": null,
"e": 27201,
"s": 27178,
"text": "manual of wipe command"
},
{
"code": null,
"e": 27379,
"s": 27201,
"text": "dd command is especially used to convert or copy files. We can use this command to completely overwrite your hard drive with zeros, but DD will not zero a drive currently in use"
},
{
"code": null,
"e": 27395,
"s": 27379,
"text": "The syntax is :"
},
{
"code": null,
"e": 27434,
"s": 27395,
"text": "- dd if=<source> of=<target> [Options]"
},
{
"code": null,
"e": 27453,
"s": 27434,
"text": "In the above menu:"
},
{
"code": null,
"e": 27480,
"s": 27453,
"text": "lsblk: Lists all the disks"
},
{
"code": null,
"e": 27540,
"s": 27480,
"text": "/dev/urandom (input): The random data used for overwriting"
},
{
"code": null,
"e": 27648,
"s": 27540,
"text": "/dev/sda (output): the disk that will be overwritten. This disk will be replaced with random garbage data. "
},
{
"code": null,
"e": 27704,
"s": 27648,
"text": "See the help menu of the “dd” command for more details:"
},
{
"code": null,
"e": 27717,
"s": 27704,
"text": "dd help menu"
},
{
"code": null,
"e": 27729,
"s": 27717,
"text": "Linux-Tools"
},
{
"code": null,
"e": 27736,
"s": 27729,
"text": "Picked"
},
{
"code": null,
"e": 27760,
"s": 27736,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 27771,
"s": 27760,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27790,
"s": 27771,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27888,
"s": 27790,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27897,
"s": 27888,
"text": "Comments"
},
{
"code": null,
"e": 27910,
"s": 27897,
"text": "Old Comments"
},
{
"code": null,
"e": 27936,
"s": 27910,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 27976,
"s": 27936,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 28011,
"s": 27976,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 28048,
"s": 28011,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 28085,
"s": 28048,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 28119,
"s": 28085,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 28161,
"s": 28119,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 28190,
"s": 28161,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 28225,
"s": 28190,
"text": "Basic Operators in Shell Scripting"
}
] |
Palindrome array - JavaScript | We are required to write a JavaScript function that takes in an array of literals and checks if elements are the same or not if read from front or back i.e. palindrome.
Let’s write the code for this function −
const arr = [1, 5, 7, 4, 15, 4, 7, 5, 1];
const isPalindrome = arr => {
const { length: l } = arr;
const mid = Math.floor(l / 2);
for(let i = 0; i <= mid; i++){
if(arr[i] !== arr[l-i-1]){
return false;
};
};
return true;
};
console.log(isPalindrome(arr));
The output in the console: −
true | [
{
"code": null,
"e": 1231,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in an array of literals and checks if elements are the same or not if read from front or back i.e. palindrome."
},
{
"code": null,
"e": 1272,
"s": 1231,
"text": "Let’s write the code for this function −"
},
{
"code": null,
"e": 1564,
"s": 1272,
"text": "const arr = [1, 5, 7, 4, 15, 4, 7, 5, 1];\nconst isPalindrome = arr => {\n const { length: l } = arr;\n const mid = Math.floor(l / 2);\n for(let i = 0; i <= mid; i++){\n if(arr[i] !== arr[l-i-1]){\n return false;\n };\n };\n return true;\n};\nconsole.log(isPalindrome(arr));"
},
{
"code": null,
"e": 1593,
"s": 1564,
"text": "The output in the console: −"
},
{
"code": null,
"e": 1598,
"s": 1593,
"text": "true"
}
] |
SQL GROUP BY Statement | The GROUP BY statement groups rows that have the same values into summary
rows, like "find the number of customers in each country".
The GROUP BY statement is often used with aggregate functions (COUNT(),
MAX(),
MIN(), SUM(),
AVG()) to group the result-set by one or more columns.
Below is a selection from the "Customers" table in the Northwind sample
database:
The following SQL statement lists the number of customers in each country:
The following SQL statement lists the number of customers in each country,
sorted high to low:
Below is a selection from the "Orders" table in the Northwind sample database:
And a selection from the "Shippers" table:
The following SQL statement lists the number of orders sent by each shipper:
List the number of customers in each country.
SELECT (CustomerID),
Country
FROM Customers
;
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 134,
"s": 0,
"text": "The GROUP BY statement groups rows that have the same values into summary \nrows, like \"find the number of customers in each country\"."
},
{
"code": null,
"e": 285,
"s": 134,
"text": "The GROUP BY statement is often used with aggregate functions (COUNT(), \nMAX(), \nMIN(), SUM(), \nAVG()) to group the result-set by one or more columns."
},
{
"code": null,
"e": 368,
"s": 285,
"text": "Below is a selection from the \"Customers\" table in the Northwind sample \ndatabase:"
},
{
"code": null,
"e": 443,
"s": 368,
"text": "The following SQL statement lists the number of customers in each country:"
},
{
"code": null,
"e": 539,
"s": 443,
"text": "The following SQL statement lists the number of customers in each country, \nsorted high to low:"
},
{
"code": null,
"e": 618,
"s": 539,
"text": "Below is a selection from the \"Orders\" table in the Northwind sample database:"
},
{
"code": null,
"e": 661,
"s": 618,
"text": "And a selection from the \"Shippers\" table:"
},
{
"code": null,
"e": 738,
"s": 661,
"text": "The following SQL statement lists the number of orders sent by each shipper:"
},
{
"code": null,
"e": 784,
"s": 738,
"text": "List the number of customers in each country."
},
{
"code": null,
"e": 831,
"s": 784,
"text": "SELECT (CustomerID),\nCountry\nFROM Customers\n;\n"
},
{
"code": null,
"e": 850,
"s": 831,
"text": "Start the Exercise"
},
{
"code": null,
"e": 883,
"s": 850,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 925,
"s": 883,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1032,
"s": 925,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1051,
"s": 1032,
"text": "help@w3schools.com"
}
] |
How to valid DateofBirth using fluent Validation in C# if it exceeds current year? | To specify a validation rule for a particular property, call the RuleFor method, passing a lambda expression that indicates the property that you wish to validate
To run the validator, instantiate the validator object and call the Validate method, passing in the object to validate.
The Validate method returns a ValidationResult object. This contains two properties
IsValid - a boolean that says whether the validation suceeded.
Errors - a collection of ValidationFailure objects containing details about any validation failures
static void Main(string[] args) {
List errors = new List();
PersonModel person = new PersonModel();
person.FirstName = "TestUser";
person.LastName = "TestUser";
person.AccountBalance = 100;
person.DateOfBirth = DateTime.Now.Date.AddYears(1);
PersonValidator validator = new PersonValidator();
ValidationResult results = validator.Validate(person);
if (results.IsValid == false) {
foreach (ValidationFailure failure in results.Errors){
errors.Add(failure.ErrorMessage);
}
}
foreach (var item in errors){
Console.WriteLine(item);
}
Console.ReadLine();
}
}
public class PersonModel {
public string FirstName { get; set; }
public string LastName { get; set; }
public decimal AccountBalance { get; set; }
public DateTime DateOfBirth { get; set; }
}
public class PersonValidator : AbstractValidator{
public PersonValidator(){
RuleFor(p => p.DateOfBirth)
.Must(BeAValidAge).WithMessage("Invalid {PropertyName}");
}
protected bool BeAValidAge(DateTime date){
int currentYear = DateTime.Now.Year;
int dobYear = date.Year;
if (dobYear <= currentYear && dobYear > (currentYear - 120)){
return true;
}
return false;
}
}
Invalid Date Of Birth | [
{
"code": null,
"e": 1225,
"s": 1062,
"text": "To specify a validation rule for a particular property, call the RuleFor method, passing a lambda expression that indicates the property that you wish to validate"
},
{
"code": null,
"e": 1345,
"s": 1225,
"text": "To run the validator, instantiate the validator object and call the Validate method, passing in the object to validate."
},
{
"code": null,
"e": 1429,
"s": 1345,
"text": "The Validate method returns a ValidationResult object. This contains two properties"
},
{
"code": null,
"e": 1492,
"s": 1429,
"text": "IsValid - a boolean that says whether the validation suceeded."
},
{
"code": null,
"e": 1592,
"s": 1492,
"text": "Errors - a collection of ValidationFailure objects containing details about any validation failures"
},
{
"code": null,
"e": 2855,
"s": 1592,
"text": "static void Main(string[] args) {\n List errors = new List();\n\n PersonModel person = new PersonModel();\n person.FirstName = \"TestUser\";\n person.LastName = \"TestUser\";\n person.AccountBalance = 100;\n person.DateOfBirth = DateTime.Now.Date.AddYears(1);\n\n PersonValidator validator = new PersonValidator();\n\n ValidationResult results = validator.Validate(person);\n\n if (results.IsValid == false) {\n foreach (ValidationFailure failure in results.Errors){\n errors.Add(failure.ErrorMessage);\n }\n }\n\n foreach (var item in errors){\n Console.WriteLine(item);\n }\n Console.ReadLine();\n\n }\n}\n\npublic class PersonModel {\n public string FirstName { get; set; }\n public string LastName { get; set; }\n public decimal AccountBalance { get; set; }\n public DateTime DateOfBirth { get; set; }\n}\n\npublic class PersonValidator : AbstractValidator{\n public PersonValidator(){\n RuleFor(p => p.DateOfBirth)\n .Must(BeAValidAge).WithMessage(\"Invalid {PropertyName}\");\n }\n\n protected bool BeAValidAge(DateTime date){\n int currentYear = DateTime.Now.Year;\n int dobYear = date.Year;\n\n if (dobYear <= currentYear && dobYear > (currentYear - 120)){\n return true;\n }\n\n return false;\n }\n}"
},
{
"code": null,
"e": 2877,
"s": 2855,
"text": "Invalid Date Of Birth"
}
] |
Feature Selection: How to Throw Away 95% of Your Features and Get 95% Accuracy | by Samuele Mazzanti | Towards Data Science | Can you recognize these handwritten digits?
You probably had no trouble spotting respectively a 0, a 3 and an 8.
If so, you were able to classify them correctly even if only 25% of the original image was shown, while the remaining 75% was covered with red pixels. This was an easy task because the “relevant” pixels were visible, while only the “irrelevant” and “redundant” ones had been hidden.
This was a simple example of “feature selection”.
Feature selection is a process that is carried out in machine learning when, before feeding the data to a predictive model, some features are removed. If your data is in the form of a table, this simply means dropping many columns from your table.
Why bothering with feature selection? Can’t I just throw all the data inside my predictive model and let him doing the dirty work?
Actually, there are several reasons for which you may want to do feature selection:
Memory. Big data take big space. Dropping features means that you need less memory to handle your data. Sometimes there are also external constraints (for instance, Google’s AutoML allows you to use no more than 1,000 columns. Thus, if you have more than 1,000 columns, you will be forced to keep only some of them).
Time. Training a model on less data can save you much time.
Accuracy. Less is more: this also goes for machine learning. Including redundant or irrelevant features means including unnecessary noise. Frequently, it happens that a model trained on less data performs better.
Interpretability. A smaller model means also a more interpretable model. Just picture if you had to explain a model based on thousands of different factors: it would be unfeasible.
Debugging. A smaller model is easier to mantain and troubleshoot.
In this article, we will compare some methods for feature selection. Our playground dataset will be the world-famous “MNIST”.
MNIST is a dataset consisting of 70,000 black-and-white images of handwritten digits. Each image is 28 x 28 (= 784) pixels. Each pixel is encoded as an integer from 1 (white) to 255 (black): the higher this value the darker the color. As a convention, 60,000 images are used as train set and 10,000 as test set.
The data can be imported into Python through a Keras command (we’ll also reshape the dataset to make it 2-dimensional, as a table):
from keras.datasets import mnist(X_train, y_train), (X_test, y_test) = mnist.load_data()X_train = X_train.reshape(60000, 28 * 28)X_test = X_test.reshape(10000, 28 * 28)
For instance, let’s print out the values of the 8th row:
print(X_train[7, :])
This is the outcome:
Through Matplotlib, we can also display the corresponding image:
import matplotlib.pyplot as pltplt.imshow(X_train[7, :].reshape(28, 28), cmap = 'binary', vmin = 0, vmax = 255)
Our task is to select a small number of columns (i.e. pixels) that are sufficient to achieve a good level of accuracy when fed to a predictive model.
There are many possible strategies and algorithms to perform feature selection. In this article, we will put to the test 6 of them:
3.1 F-Statistic
F-Statistic is the outcome of the ANOVA F-test. This test is computed as the ratio: between-group variability / within-group variability, where the group is the target class.
The idea is that a pixel is relevant when the variability between the groups (images in class 0, images in class 1, ..., images in class 9) is high and the variability within the same groups is low.
from sklearn.feature_selection import f_classiff = f_classif(X_train, y_train)[0]
3.2 Mutual Information
Mutual information is a measure of the mutual dependence between two variables.
Since the formula of MI requires knowing the probability distribution of each variable (and normally we don’t know distributions), the scikit-learn implementation employs a nonparametric approximation based on k-nearest neighbors distances.
from sklearn.feature_selection import mutual_info_classifmi = mutual_info_classif(X_train, y_train)
3.3 Logistic Regression
If the target variable is categorical (as in our case), a logistic regression may be fitted to the data. Then, the relative importance of the features can be used to rank them from the most to the least relevant.
from sklearn.linear_model import LogisticRegressionlogreg = LogisticRegression().fit(X_train, y_train)
3.4 LightGBM
The same can be done with any predictive model. For instance, LightGBM.
from lightgbm import LGBMClassifierlgbm = LGBMClassifier( objective = 'multiclass', metric = 'multi_logloss', importance_type = 'gain').fit(X_train, y_train)
3.5 Boruta
Boruta is an elegant algorithm designed in 2010 as a package for R. The aim of Boruta is to tell whether or not each feature has some kind of relationship with the target variable. So, the output of Boruta is more a yes/no for each feature, rather than a ranking of features.
(If you are curious to know more about the functioning of Boruta, I wrote a post about it: Boruta Explained Exactly How You Wished Someone Explained to You).
from boruta import BorutaPyfrom sklearn.ensemble import RandomForestClassifierboruta = BorutaPy( estimator = RandomForestClassifier(max_depth = 5), n_estimators = 'auto', max_iter = 100).fit(X_train, y_train)
3.6 MRMR
MRMR (which stands for “Maximum Relevance Minimum Redundancy”) is an algorithm designed in 2005 for feature selection. The idea behind MRMR is to identify a subset of features having a high relevance with respect to the target variable and a small redundancy with each other.
(If you are curious to know more about the functioning of MRMR, I wrote a post about it: MRMR Explained Exactly How You Wished Someone Explained to You).
from mrmr import mrmr_classifmrmr = mrmr_classif(X_train, y_train)
All these algorithms provide a “ranking” of the features (except for Boruta, which has a yes/no outcome). Let’s see how the rankings change according to the different algorithms.
At this point, a natural question is:
What method should I choose for feature selection?
As always in data science, the best choice is to test different approaches, and see which one gives better results on your data. Therefore, let’s try them on MNIST.
We will take the feature rankings provided by the 5 methods (since Boruta does not provide a ranking) and see what accuracy can be achieved when training a predictive model on the first K features (for K up to 40).
import pandas as pdfrom catboost import CatBoostClassifierfrom sklearn.metrics import accuracy_scorealgos = ['f', 'mi', 'logreg', 'lightgbm', 'mrmr']ks = [1, 2, 5, 10, 15, 20, 30, 40]accuracy = pd.DataFrame(index = ks, columns = algos)for algo in algos: for nfeats in ks: feats = ranking[algo][:n_feats] clf = CatBoostClassifier().fit( X_train[:, feats], y_train, eval_set = (X_test[:, feats], y_test), early_stopping_rounds = 20 ) accuracy.loc[k, algo] = accuracy_score( y_true = y_test, y_pred = clf.predict(X_test[:, cols])))
These are the outcomes:
In this case, MRMR outperformed the other algorithms.
As the plot shows, a predictor trained on the most relevant 40 pixels identified by MRMR reached 95.54% accuracy on test images!
This is pretty impressive, especially if we consider that:
40 pixels are only 5% of the whole image (which consists of 28 x 28 = 784 pixels);
we have used a predictive model (CatBoost) with no further tuning, thus this performance can probably be improved further.
Thus, in the case of MNIST, we could throw away 95% of our data and still get more than 95% accuracy (which corresponds to an area under ROC of 99.85%!).
Even if MNIST is a “simple” dataset, the main takeaways are valid for most real-world datasets. Often, a high level of accuracy can be achieved with just a small portion of features. An effective feature selection allows you to build data pipelines that are more efficient in terms of memory, time, accuracy, interpretability and ease of debugging.
Thank you for reading! I hope you found this post useful.
The results shown in this article are fully reproducible through this code: https://github.com/smazzanti/mrmr/blob/main/notebooks/mnist.ipynb.
I appreciate feedback and constructive criticism. If you want to talk about this article or other related topics, you can text me at my Linkedin contact. | [
{
"code": null,
"e": 216,
"s": 172,
"text": "Can you recognize these handwritten digits?"
},
{
"code": null,
"e": 285,
"s": 216,
"text": "You probably had no trouble spotting respectively a 0, a 3 and an 8."
},
{
"code": null,
"e": 568,
"s": 285,
"text": "If so, you were able to classify them correctly even if only 25% of the original image was shown, while the remaining 75% was covered with red pixels. This was an easy task because the “relevant” pixels were visible, while only the “irrelevant” and “redundant” ones had been hidden."
},
{
"code": null,
"e": 618,
"s": 568,
"text": "This was a simple example of “feature selection”."
},
{
"code": null,
"e": 866,
"s": 618,
"text": "Feature selection is a process that is carried out in machine learning when, before feeding the data to a predictive model, some features are removed. If your data is in the form of a table, this simply means dropping many columns from your table."
},
{
"code": null,
"e": 997,
"s": 866,
"text": "Why bothering with feature selection? Can’t I just throw all the data inside my predictive model and let him doing the dirty work?"
},
{
"code": null,
"e": 1081,
"s": 997,
"text": "Actually, there are several reasons for which you may want to do feature selection:"
},
{
"code": null,
"e": 1398,
"s": 1081,
"text": "Memory. Big data take big space. Dropping features means that you need less memory to handle your data. Sometimes there are also external constraints (for instance, Google’s AutoML allows you to use no more than 1,000 columns. Thus, if you have more than 1,000 columns, you will be forced to keep only some of them)."
},
{
"code": null,
"e": 1458,
"s": 1398,
"text": "Time. Training a model on less data can save you much time."
},
{
"code": null,
"e": 1671,
"s": 1458,
"text": "Accuracy. Less is more: this also goes for machine learning. Including redundant or irrelevant features means including unnecessary noise. Frequently, it happens that a model trained on less data performs better."
},
{
"code": null,
"e": 1852,
"s": 1671,
"text": "Interpretability. A smaller model means also a more interpretable model. Just picture if you had to explain a model based on thousands of different factors: it would be unfeasible."
},
{
"code": null,
"e": 1918,
"s": 1852,
"text": "Debugging. A smaller model is easier to mantain and troubleshoot."
},
{
"code": null,
"e": 2044,
"s": 1918,
"text": "In this article, we will compare some methods for feature selection. Our playground dataset will be the world-famous “MNIST”."
},
{
"code": null,
"e": 2356,
"s": 2044,
"text": "MNIST is a dataset consisting of 70,000 black-and-white images of handwritten digits. Each image is 28 x 28 (= 784) pixels. Each pixel is encoded as an integer from 1 (white) to 255 (black): the higher this value the darker the color. As a convention, 60,000 images are used as train set and 10,000 as test set."
},
{
"code": null,
"e": 2488,
"s": 2356,
"text": "The data can be imported into Python through a Keras command (we’ll also reshape the dataset to make it 2-dimensional, as a table):"
},
{
"code": null,
"e": 2657,
"s": 2488,
"text": "from keras.datasets import mnist(X_train, y_train), (X_test, y_test) = mnist.load_data()X_train = X_train.reshape(60000, 28 * 28)X_test = X_test.reshape(10000, 28 * 28)"
},
{
"code": null,
"e": 2714,
"s": 2657,
"text": "For instance, let’s print out the values of the 8th row:"
},
{
"code": null,
"e": 2735,
"s": 2714,
"text": "print(X_train[7, :])"
},
{
"code": null,
"e": 2756,
"s": 2735,
"text": "This is the outcome:"
},
{
"code": null,
"e": 2821,
"s": 2756,
"text": "Through Matplotlib, we can also display the corresponding image:"
},
{
"code": null,
"e": 2933,
"s": 2821,
"text": "import matplotlib.pyplot as pltplt.imshow(X_train[7, :].reshape(28, 28), cmap = 'binary', vmin = 0, vmax = 255)"
},
{
"code": null,
"e": 3083,
"s": 2933,
"text": "Our task is to select a small number of columns (i.e. pixels) that are sufficient to achieve a good level of accuracy when fed to a predictive model."
},
{
"code": null,
"e": 3215,
"s": 3083,
"text": "There are many possible strategies and algorithms to perform feature selection. In this article, we will put to the test 6 of them:"
},
{
"code": null,
"e": 3231,
"s": 3215,
"text": "3.1 F-Statistic"
},
{
"code": null,
"e": 3406,
"s": 3231,
"text": "F-Statistic is the outcome of the ANOVA F-test. This test is computed as the ratio: between-group variability / within-group variability, where the group is the target class."
},
{
"code": null,
"e": 3605,
"s": 3406,
"text": "The idea is that a pixel is relevant when the variability between the groups (images in class 0, images in class 1, ..., images in class 9) is high and the variability within the same groups is low."
},
{
"code": null,
"e": 3687,
"s": 3605,
"text": "from sklearn.feature_selection import f_classiff = f_classif(X_train, y_train)[0]"
},
{
"code": null,
"e": 3710,
"s": 3687,
"text": "3.2 Mutual Information"
},
{
"code": null,
"e": 3790,
"s": 3710,
"text": "Mutual information is a measure of the mutual dependence between two variables."
},
{
"code": null,
"e": 4031,
"s": 3790,
"text": "Since the formula of MI requires knowing the probability distribution of each variable (and normally we don’t know distributions), the scikit-learn implementation employs a nonparametric approximation based on k-nearest neighbors distances."
},
{
"code": null,
"e": 4131,
"s": 4031,
"text": "from sklearn.feature_selection import mutual_info_classifmi = mutual_info_classif(X_train, y_train)"
},
{
"code": null,
"e": 4155,
"s": 4131,
"text": "3.3 Logistic Regression"
},
{
"code": null,
"e": 4368,
"s": 4155,
"text": "If the target variable is categorical (as in our case), a logistic regression may be fitted to the data. Then, the relative importance of the features can be used to rank them from the most to the least relevant."
},
{
"code": null,
"e": 4471,
"s": 4368,
"text": "from sklearn.linear_model import LogisticRegressionlogreg = LogisticRegression().fit(X_train, y_train)"
},
{
"code": null,
"e": 4484,
"s": 4471,
"text": "3.4 LightGBM"
},
{
"code": null,
"e": 4556,
"s": 4484,
"text": "The same can be done with any predictive model. For instance, LightGBM."
},
{
"code": null,
"e": 4723,
"s": 4556,
"text": "from lightgbm import LGBMClassifierlgbm = LGBMClassifier( objective = 'multiclass', metric = 'multi_logloss', importance_type = 'gain').fit(X_train, y_train)"
},
{
"code": null,
"e": 4734,
"s": 4723,
"text": "3.5 Boruta"
},
{
"code": null,
"e": 5010,
"s": 4734,
"text": "Boruta is an elegant algorithm designed in 2010 as a package for R. The aim of Boruta is to tell whether or not each feature has some kind of relationship with the target variable. So, the output of Boruta is more a yes/no for each feature, rather than a ranking of features."
},
{
"code": null,
"e": 5168,
"s": 5010,
"text": "(If you are curious to know more about the functioning of Boruta, I wrote a post about it: Boruta Explained Exactly How You Wished Someone Explained to You)."
},
{
"code": null,
"e": 5388,
"s": 5168,
"text": "from boruta import BorutaPyfrom sklearn.ensemble import RandomForestClassifierboruta = BorutaPy( estimator = RandomForestClassifier(max_depth = 5), n_estimators = 'auto', max_iter = 100).fit(X_train, y_train)"
},
{
"code": null,
"e": 5397,
"s": 5388,
"text": "3.6 MRMR"
},
{
"code": null,
"e": 5673,
"s": 5397,
"text": "MRMR (which stands for “Maximum Relevance Minimum Redundancy”) is an algorithm designed in 2005 for feature selection. The idea behind MRMR is to identify a subset of features having a high relevance with respect to the target variable and a small redundancy with each other."
},
{
"code": null,
"e": 5827,
"s": 5673,
"text": "(If you are curious to know more about the functioning of MRMR, I wrote a post about it: MRMR Explained Exactly How You Wished Someone Explained to You)."
},
{
"code": null,
"e": 5894,
"s": 5827,
"text": "from mrmr import mrmr_classifmrmr = mrmr_classif(X_train, y_train)"
},
{
"code": null,
"e": 6073,
"s": 5894,
"text": "All these algorithms provide a “ranking” of the features (except for Boruta, which has a yes/no outcome). Let’s see how the rankings change according to the different algorithms."
},
{
"code": null,
"e": 6111,
"s": 6073,
"text": "At this point, a natural question is:"
},
{
"code": null,
"e": 6162,
"s": 6111,
"text": "What method should I choose for feature selection?"
},
{
"code": null,
"e": 6327,
"s": 6162,
"text": "As always in data science, the best choice is to test different approaches, and see which one gives better results on your data. Therefore, let’s try them on MNIST."
},
{
"code": null,
"e": 6542,
"s": 6327,
"text": "We will take the feature rankings provided by the 5 methods (since Boruta does not provide a ranking) and see what accuracy can be achieved when training a predictive model on the first K features (for K up to 40)."
},
{
"code": null,
"e": 7126,
"s": 6542,
"text": "import pandas as pdfrom catboost import CatBoostClassifierfrom sklearn.metrics import accuracy_scorealgos = ['f', 'mi', 'logreg', 'lightgbm', 'mrmr']ks = [1, 2, 5, 10, 15, 20, 30, 40]accuracy = pd.DataFrame(index = ks, columns = algos)for algo in algos: for nfeats in ks: feats = ranking[algo][:n_feats] clf = CatBoostClassifier().fit( X_train[:, feats], y_train, eval_set = (X_test[:, feats], y_test), early_stopping_rounds = 20 ) accuracy.loc[k, algo] = accuracy_score( y_true = y_test, y_pred = clf.predict(X_test[:, cols])))"
},
{
"code": null,
"e": 7150,
"s": 7126,
"text": "These are the outcomes:"
},
{
"code": null,
"e": 7204,
"s": 7150,
"text": "In this case, MRMR outperformed the other algorithms."
},
{
"code": null,
"e": 7333,
"s": 7204,
"text": "As the plot shows, a predictor trained on the most relevant 40 pixels identified by MRMR reached 95.54% accuracy on test images!"
},
{
"code": null,
"e": 7392,
"s": 7333,
"text": "This is pretty impressive, especially if we consider that:"
},
{
"code": null,
"e": 7475,
"s": 7392,
"text": "40 pixels are only 5% of the whole image (which consists of 28 x 28 = 784 pixels);"
},
{
"code": null,
"e": 7598,
"s": 7475,
"text": "we have used a predictive model (CatBoost) with no further tuning, thus this performance can probably be improved further."
},
{
"code": null,
"e": 7752,
"s": 7598,
"text": "Thus, in the case of MNIST, we could throw away 95% of our data and still get more than 95% accuracy (which corresponds to an area under ROC of 99.85%!)."
},
{
"code": null,
"e": 8101,
"s": 7752,
"text": "Even if MNIST is a “simple” dataset, the main takeaways are valid for most real-world datasets. Often, a high level of accuracy can be achieved with just a small portion of features. An effective feature selection allows you to build data pipelines that are more efficient in terms of memory, time, accuracy, interpretability and ease of debugging."
},
{
"code": null,
"e": 8159,
"s": 8101,
"text": "Thank you for reading! I hope you found this post useful."
},
{
"code": null,
"e": 8302,
"s": 8159,
"text": "The results shown in this article are fully reproducible through this code: https://github.com/smazzanti/mrmr/blob/main/notebooks/mnist.ipynb."
}
] |
Java - equals() Method | The method determines whether the Number object that invokes the method is equal to the object that is passed as an argument.
public boolean equals(Object o)
Here is the detail of parameters −
Any object.
The method returns True if the argument is not null and is an object of the same type and with the same numeric value. There are some extra requirements for Double and Float objects that are described in the Java API documentation.
The method returns True if the argument is not null and is an object of the same type and with the same numeric value. There are some extra requirements for Double and Float objects that are described in the Java API documentation.
public class Test {
public static void main(String args[]) {
Integer x = 5;
Integer y = 10;
Integer z =5;
Short a = 5;
System.out.println(x.equals(y));
System.out.println(x.equals(z));
System.out.println(x.equals(a));
}
}
This will produce the following result −
false
true
false
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2503,
"s": 2377,
"text": "The method determines whether the Number object that invokes the method is equal to the object that is passed as an argument."
},
{
"code": null,
"e": 2536,
"s": 2503,
"text": "public boolean equals(Object o)\n"
},
{
"code": null,
"e": 2571,
"s": 2536,
"text": "Here is the detail of parameters −"
},
{
"code": null,
"e": 2583,
"s": 2571,
"text": "Any object."
},
{
"code": null,
"e": 2815,
"s": 2583,
"text": "The method returns True if the argument is not null and is an object of the same type and with the same numeric value. There are some extra requirements for Double and Float objects that are described in the Java API documentation."
},
{
"code": null,
"e": 3047,
"s": 2815,
"text": "The method returns True if the argument is not null and is an object of the same type and with the same numeric value. There are some extra requirements for Double and Float objects that are described in the Java API documentation."
},
{
"code": null,
"e": 3323,
"s": 3047,
"text": "public class Test { \n\n public static void main(String args[]) {\n Integer x = 5;\n Integer y = 10;\n Integer z =5;\n Short a = 5;\n\n System.out.println(x.equals(y)); \n System.out.println(x.equals(z)); \n System.out.println(x.equals(a));\n }\n}"
},
{
"code": null,
"e": 3364,
"s": 3323,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3382,
"s": 3364,
"text": "false\ntrue\nfalse\n"
},
{
"code": null,
"e": 3415,
"s": 3382,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3431,
"s": 3415,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3464,
"s": 3431,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3480,
"s": 3464,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3515,
"s": 3480,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3529,
"s": 3515,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3563,
"s": 3529,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3577,
"s": 3563,
"text": " Tushar Kale"
},
{
"code": null,
"e": 3614,
"s": 3577,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3629,
"s": 3614,
"text": " Monica Mittal"
},
{
"code": null,
"e": 3662,
"s": 3629,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3681,
"s": 3662,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3688,
"s": 3681,
"text": " Print"
},
{
"code": null,
"e": 3699,
"s": 3688,
"text": " Add Notes"
}
] |
Can Github Copilot Make You a Better Data Scientist? | by Manfye Goh | Towards Data Science | Github Copilot is the recent hype in the programming world, and many articles and youtube videos show the amazing capability of Copilot. I obtained access to Github Copilot Technical Preview recently and I’m curious about how Copilot can help data scientists in data science projects.
GitHub Copilot is an AI pair programmer that helps you write code faster and with less work. GitHub Copilot draws context from comments and code and suggests individual lines and whole functions instantly. [3]
Copilot has been trained on huge amounts of coding data publicly available, from GitHub repositories and other sites [2]. So basically it is a better programmer than you and me.
Currently, Copilot technical preview is available as VS code extension and is only limited to a small group of testers for previewing the extension. You can try to sign up here. Upon success approval, you will obtain a screen as below:
Copilot works just like your Google autocomplete. Code suggestions will appear as dimmer color phrases and you will get a mouseover tab when pointing to the suggested code.
Copilot will provide you tons of code suggestions, simply press Alt + ] and Alt + [ to change the suggested code and press “Tab” to accept it. You can preview multiple suggestion codes simply pressing Ctrl+Enter and get the view like below:
Copilot is able to identify your comments and generate the function according to your comment, you can give instruction to the copilot to generate out the function just like the example below:
P.s: you can also chat with Copilot when you are bored by typing ME: and AI: for the Q&A model.
That ends our short intro on Copilot, so let’s proceed with our main question:
Can Copilot help data scientists make better data science projects?
Let's try it!
In this experiment, we will use the famous Iris dataset; our target is to use Copilot to perform exploratory data analysis and train a k-NN model with purely the suggested code. We will put rules as below:
Use only the suggested code, fix typos and data-specific issues only.Every action should be accompanied by a clear comment/command to Copilot.Only 3 Top code suggestions will be taken.
Use only the suggested code, fix typos and data-specific issues only.
Every action should be accompanied by a clear comment/command to Copilot.
Only 3 Top code suggestions will be taken.
As of the time of writing, the Python notebook in VS code is relatively unstable with Copilot, so I will be using Streamlit as my platform. Streamlit provides a Jupyter notebook-like real-time code updates web application that can help us in exploring the data science project. For more information on Streamlit, you can read my article here.
Import the library packages:
import streamlit as stimport pandas as pdimport numpy as npimport plotly.express as px
# load iris.csv into dataframe
# print the dataframe column names and shape
It impressed me that Copilot auto-understands the printing mechanism in Streamlit which uses st.write() instead of print() as streamlit is a relatively new package in python.
Next, I try with:
# create a scatter plot of the petal length and petal width using plotly express
And this is what I get, looks like Copilot is not clever enough to understand the context inside the data frame 😂:
Next, I try with exact naming, and a nice exact graph is obtained:
# create a scatter plot of the petalLengthCm with SepalLengthCm using plotly express
Next for creating a test and train dataset, I write this:
# splitting the data into training and testing sets (80:20)
and these are the suggestion I get back:
Impressive! Copilot even knows which one is my target class and writes the full code for me, what I need to do is just select the suggestion!
The full code suggestion return is as below:
Next, I try my luck with this command:
# check for optimal K value using testing set
And out of my expectation, Copilot can return me this code:
That’s tons of time saved in coding; Copilot even helps you plot a chart in the end. Well, the chart didn’t work out, so I have to modify the code a bit on my end using the list is created. But it still saves me lots of time going to stack overflow checking for codes.
Out of my curiosity, I asked Copilot, “What is the optimal K value?”
The copilot returns me the answer without the need to plot the graph 😲😲
So this inspired my next command, I want:
# create a classifier using the optimal K value
and then, I just press enter and accept the suggested comment and codes to proceed. here is my resulted code:
Note that I only type 1 command, and the rest is suggested by Copilot.
Out of 5 suggested codes, 3 work perfectly and 2 suggestions: metrics.f1_score and metrics.precision_score doesn't work out.
That’s the end of my simple code testing with Copilot. I had published the suggested in Github, feel free to see it.
In this article, I demonstrated how copilot can help in the data science process and a few mistakes were done by Copilot, but the advantage of using it is more. Another concern is that the dataset I used was the Iris dataset, so it might work less effectively in a bigger dataset.
The new paradigm of programming is coming, instead of searching in Q&A websites such as StackOverflow, Copilot will save most of your googling time and give you multiple solutions directly. I guess it will reduce the reliance on StackOverflow and Google for programming-related questions in the future.
Well, at the current stages, our job is still secured as Copilot still needs some basic knowledge to execute, such as guiding the direction of the projects and telling Copilot what to do.
In my opinion, Copilot definitely will make you a better data scientist currently. But will it take over your job as a data scientist in the future? With the feedbacks and vast amount of data input into Copilot, it will definitely become a better AI in the future, and who knows will it take over the programmer and data scientist job? 🤔🤔
Lastly, I’m still in #TeamHumanity: with our creativity, we will take over the control toward AI, and use AI for our betterment. Thank you very much for reading my articles.
Here are some of my articles, hope you like them too:
towardsdatascience.com
towardsdatascience.com
Iris dataset from Kagglehttps://towardsdatascience.com/github-copilot-a-new-generation-of-ai-programmers-327e3c7ef3aehttps://copilot.github.com/
Iris dataset from Kaggle | [
{
"code": null,
"e": 457,
"s": 172,
"text": "Github Copilot is the recent hype in the programming world, and many articles and youtube videos show the amazing capability of Copilot. I obtained access to Github Copilot Technical Preview recently and I’m curious about how Copilot can help data scientists in data science projects."
},
{
"code": null,
"e": 667,
"s": 457,
"text": "GitHub Copilot is an AI pair programmer that helps you write code faster and with less work. GitHub Copilot draws context from comments and code and suggests individual lines and whole functions instantly. [3]"
},
{
"code": null,
"e": 845,
"s": 667,
"text": "Copilot has been trained on huge amounts of coding data publicly available, from GitHub repositories and other sites [2]. So basically it is a better programmer than you and me."
},
{
"code": null,
"e": 1081,
"s": 845,
"text": "Currently, Copilot technical preview is available as VS code extension and is only limited to a small group of testers for previewing the extension. You can try to sign up here. Upon success approval, you will obtain a screen as below:"
},
{
"code": null,
"e": 1254,
"s": 1081,
"text": "Copilot works just like your Google autocomplete. Code suggestions will appear as dimmer color phrases and you will get a mouseover tab when pointing to the suggested code."
},
{
"code": null,
"e": 1495,
"s": 1254,
"text": "Copilot will provide you tons of code suggestions, simply press Alt + ] and Alt + [ to change the suggested code and press “Tab” to accept it. You can preview multiple suggestion codes simply pressing Ctrl+Enter and get the view like below:"
},
{
"code": null,
"e": 1688,
"s": 1495,
"text": "Copilot is able to identify your comments and generate the function according to your comment, you can give instruction to the copilot to generate out the function just like the example below:"
},
{
"code": null,
"e": 1784,
"s": 1688,
"text": "P.s: you can also chat with Copilot when you are bored by typing ME: and AI: for the Q&A model."
},
{
"code": null,
"e": 1863,
"s": 1784,
"text": "That ends our short intro on Copilot, so let’s proceed with our main question:"
},
{
"code": null,
"e": 1931,
"s": 1863,
"text": "Can Copilot help data scientists make better data science projects?"
},
{
"code": null,
"e": 1945,
"s": 1931,
"text": "Let's try it!"
},
{
"code": null,
"e": 2151,
"s": 1945,
"text": "In this experiment, we will use the famous Iris dataset; our target is to use Copilot to perform exploratory data analysis and train a k-NN model with purely the suggested code. We will put rules as below:"
},
{
"code": null,
"e": 2336,
"s": 2151,
"text": "Use only the suggested code, fix typos and data-specific issues only.Every action should be accompanied by a clear comment/command to Copilot.Only 3 Top code suggestions will be taken."
},
{
"code": null,
"e": 2406,
"s": 2336,
"text": "Use only the suggested code, fix typos and data-specific issues only."
},
{
"code": null,
"e": 2480,
"s": 2406,
"text": "Every action should be accompanied by a clear comment/command to Copilot."
},
{
"code": null,
"e": 2523,
"s": 2480,
"text": "Only 3 Top code suggestions will be taken."
},
{
"code": null,
"e": 2866,
"s": 2523,
"text": "As of the time of writing, the Python notebook in VS code is relatively unstable with Copilot, so I will be using Streamlit as my platform. Streamlit provides a Jupyter notebook-like real-time code updates web application that can help us in exploring the data science project. For more information on Streamlit, you can read my article here."
},
{
"code": null,
"e": 2895,
"s": 2866,
"text": "Import the library packages:"
},
{
"code": null,
"e": 2982,
"s": 2895,
"text": "import streamlit as stimport pandas as pdimport numpy as npimport plotly.express as px"
},
{
"code": null,
"e": 3013,
"s": 2982,
"text": "# load iris.csv into dataframe"
},
{
"code": null,
"e": 3058,
"s": 3013,
"text": "# print the dataframe column names and shape"
},
{
"code": null,
"e": 3233,
"s": 3058,
"text": "It impressed me that Copilot auto-understands the printing mechanism in Streamlit which uses st.write() instead of print() as streamlit is a relatively new package in python."
},
{
"code": null,
"e": 3251,
"s": 3233,
"text": "Next, I try with:"
},
{
"code": null,
"e": 3332,
"s": 3251,
"text": "# create a scatter plot of the petal length and petal width using plotly express"
},
{
"code": null,
"e": 3447,
"s": 3332,
"text": "And this is what I get, looks like Copilot is not clever enough to understand the context inside the data frame 😂:"
},
{
"code": null,
"e": 3514,
"s": 3447,
"text": "Next, I try with exact naming, and a nice exact graph is obtained:"
},
{
"code": null,
"e": 3599,
"s": 3514,
"text": "# create a scatter plot of the petalLengthCm with SepalLengthCm using plotly express"
},
{
"code": null,
"e": 3657,
"s": 3599,
"text": "Next for creating a test and train dataset, I write this:"
},
{
"code": null,
"e": 3717,
"s": 3657,
"text": "# splitting the data into training and testing sets (80:20)"
},
{
"code": null,
"e": 3758,
"s": 3717,
"text": "and these are the suggestion I get back:"
},
{
"code": null,
"e": 3900,
"s": 3758,
"text": "Impressive! Copilot even knows which one is my target class and writes the full code for me, what I need to do is just select the suggestion!"
},
{
"code": null,
"e": 3945,
"s": 3900,
"text": "The full code suggestion return is as below:"
},
{
"code": null,
"e": 3984,
"s": 3945,
"text": "Next, I try my luck with this command:"
},
{
"code": null,
"e": 4030,
"s": 3984,
"text": "# check for optimal K value using testing set"
},
{
"code": null,
"e": 4090,
"s": 4030,
"text": "And out of my expectation, Copilot can return me this code:"
},
{
"code": null,
"e": 4359,
"s": 4090,
"text": "That’s tons of time saved in coding; Copilot even helps you plot a chart in the end. Well, the chart didn’t work out, so I have to modify the code a bit on my end using the list is created. But it still saves me lots of time going to stack overflow checking for codes."
},
{
"code": null,
"e": 4428,
"s": 4359,
"text": "Out of my curiosity, I asked Copilot, “What is the optimal K value?”"
},
{
"code": null,
"e": 4500,
"s": 4428,
"text": "The copilot returns me the answer without the need to plot the graph 😲😲"
},
{
"code": null,
"e": 4542,
"s": 4500,
"text": "So this inspired my next command, I want:"
},
{
"code": null,
"e": 4590,
"s": 4542,
"text": "# create a classifier using the optimal K value"
},
{
"code": null,
"e": 4700,
"s": 4590,
"text": "and then, I just press enter and accept the suggested comment and codes to proceed. here is my resulted code:"
},
{
"code": null,
"e": 4771,
"s": 4700,
"text": "Note that I only type 1 command, and the rest is suggested by Copilot."
},
{
"code": null,
"e": 4896,
"s": 4771,
"text": "Out of 5 suggested codes, 3 work perfectly and 2 suggestions: metrics.f1_score and metrics.precision_score doesn't work out."
},
{
"code": null,
"e": 5013,
"s": 4896,
"text": "That’s the end of my simple code testing with Copilot. I had published the suggested in Github, feel free to see it."
},
{
"code": null,
"e": 5294,
"s": 5013,
"text": "In this article, I demonstrated how copilot can help in the data science process and a few mistakes were done by Copilot, but the advantage of using it is more. Another concern is that the dataset I used was the Iris dataset, so it might work less effectively in a bigger dataset."
},
{
"code": null,
"e": 5597,
"s": 5294,
"text": "The new paradigm of programming is coming, instead of searching in Q&A websites such as StackOverflow, Copilot will save most of your googling time and give you multiple solutions directly. I guess it will reduce the reliance on StackOverflow and Google for programming-related questions in the future."
},
{
"code": null,
"e": 5785,
"s": 5597,
"text": "Well, at the current stages, our job is still secured as Copilot still needs some basic knowledge to execute, such as guiding the direction of the projects and telling Copilot what to do."
},
{
"code": null,
"e": 6124,
"s": 5785,
"text": "In my opinion, Copilot definitely will make you a better data scientist currently. But will it take over your job as a data scientist in the future? With the feedbacks and vast amount of data input into Copilot, it will definitely become a better AI in the future, and who knows will it take over the programmer and data scientist job? 🤔🤔"
},
{
"code": null,
"e": 6298,
"s": 6124,
"text": "Lastly, I’m still in #TeamHumanity: with our creativity, we will take over the control toward AI, and use AI for our betterment. Thank you very much for reading my articles."
},
{
"code": null,
"e": 6352,
"s": 6298,
"text": "Here are some of my articles, hope you like them too:"
},
{
"code": null,
"e": 6375,
"s": 6352,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6398,
"s": 6375,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6543,
"s": 6398,
"text": "Iris dataset from Kagglehttps://towardsdatascience.com/github-copilot-a-new-generation-of-ai-programmers-327e3c7ef3aehttps://copilot.github.com/"
}
] |
What are the different ways of handling authentication popup window using Selenium? | We can handle authentication pop-up window using Selenium webdriver by incorporating the username and password within the application URL. The format of an URL along with credential should be − https://username:password@URL
Let us launch a web page having the authentication pop-up generated at page load −
The user Name and Password fields are having value as admin.
If we ignore this pop-up on clicking the Cancel button, we shall be navigated to the below page.
If proper credentials are entered and then the OK button is clicked, we shall be navigated to the below page.
In the above example, to handle the authentication pop-up, using the get method, the URL to be passed as a parameter should be - https://admin:admin@the−nternet.herokuapp.com/basic_auth.
from selenium import webdriver
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
#implicit wait
driver.implicitly_wait(0.5)
#maximize browser
driver.maximize_window()
#username, password value
p = "admin"
#url format
url = "https://" + p + ":" + p + "@" + "the-internet.herokuapp.com/basic_auth"
#launch URL
driver.get(url)
#identify element
l = driver.find_element_by_tag_name("p")
#obtain text
s = l.text
print("Text is: ")
print(s)
#close browser
driver.close() | [
{
"code": null,
"e": 1286,
"s": 1062,
"text": "We can handle authentication pop-up window using Selenium webdriver by incorporating the username and password within the application URL. The format of an URL along with credential should be − https://username:password@URL"
},
{
"code": null,
"e": 1369,
"s": 1286,
"text": "Let us launch a web page having the authentication pop-up generated at page load −"
},
{
"code": null,
"e": 1430,
"s": 1369,
"text": "The user Name and Password fields are having value as admin."
},
{
"code": null,
"e": 1527,
"s": 1430,
"text": "If we ignore this pop-up on clicking the Cancel button, we shall be navigated to the below page."
},
{
"code": null,
"e": 1637,
"s": 1527,
"text": "If proper credentials are entered and then the OK button is clicked, we shall be navigated to the below page."
},
{
"code": null,
"e": 1824,
"s": 1637,
"text": "In the above example, to handle the authentication pop-up, using the get method, the URL to be passed as a parameter should be - https://admin:admin@the−nternet.herokuapp.com/basic_auth."
},
{
"code": null,
"e": 2332,
"s": 1824,
"text": "from selenium import webdriver\n#set chromodriver.exe path\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n#implicit wait\ndriver.implicitly_wait(0.5)\n#maximize browser\ndriver.maximize_window()\n#username, password value\np = \"admin\"\n#url format\nurl = \"https://\" + p + \":\" + p + \"@\" + \"the-internet.herokuapp.com/basic_auth\"\n#launch URL\ndriver.get(url)\n#identify element\nl = driver.find_element_by_tag_name(\"p\")\n#obtain text\ns = l.text\nprint(\"Text is: \")\nprint(s)\n#close browser\ndriver.close()"
}
] |
Beautiful Soup - Navigating by Tags | In this chapter, we shall discuss about Navigating by Tags.
Below is our html document −
>>> html_doc = """
<html><head><title>Tutorials Point</title></head>
<body>
<p class="title"><b>The Biggest Online Tutorials Library, It's all Free</b></p>
<p class="prog">Top 5 most used Programming Languages are:
<a href="https://www.tutorialspoint.com/java/java_overview.htm" class="prog" id="link1">Java</a>,
<a href="https://www.tutorialspoint.com/cprogramming/index.htm" class="prog" id="link2">C</a>,
<a href="https://www.tutorialspoint.com/python/index.htm" class="prog" id="link3">Python</a>,
<a href="https://www.tutorialspoint.com/javascript/javascript_overview.htm" class="prog" id="link4">JavaScript</a> and
<a href="https://www.tutorialspoint.com/ruby/index.htm" class="prog" id="link5">C</a>;
as per online survey.</p>
<p class="prog">Programming Languages</p>
"""
>>>
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(html_doc, 'html.parser')
>>>
Based on the above document, we will try to move from one part of document to another.
One of the important pieces of element in any piece of HTML document are tags, which may contain other tags/strings (tag’s children). Beautiful Soup provides different ways to navigate and iterate over’s tag’s children.
Easiest way to search a parse tree is to search the tag by its name. If you want the <head> tag, use soup.head −
>>> soup.head
<head>&t;title>Tutorials Point</title></head>
>>> soup.title
<title>Tutorials Point</title>
To get specific tag (like first <b> tag) in the <body> tag.
>>> soup.body.b
<b>The Biggest Online Tutorials Library, It's all Free</b>
Using a tag name as an attribute will give you only the first tag by that name −
>>> soup.a
<a class="prog" href="https://www.tutorialspoint.com/java/java_overview.htm" id="link1">Java</a>
To get all the tag’s attribute, you can use find_all() method −
>>> soup.find_all("a")
[<a class="prog" href="https://www.tutorialspoint.com/java/java_overview.htm" id="link1">Java</a>, <a class="prog" href="https://www.tutorialspoint.com/cprogramming/index.htm" id="link2">C</a>, <a class="prog" href="https://www.tutorialspoint.com/python/index.htm" id="link3">Python</a>, <a class="prog" href="https://www.tutorialspoint.com/javascript/javascript_overview.htm" id="link4">JavaScript</a>, <a class="prog" href="https://www.tutorialspoint.com/ruby/index.htm" id="link5">C</a>]>>> soup.find_all("a")
[<a class="prog" href="https://www.tutorialspoint.com/java/java_overview.htm" id="link1">Java</a>, <a class="prog" href="https://www.tutorialspoint.com/cprogramming/index.htm" id="link2">C</a>, <a class="prog" href="https://www.tutorialspoint.com/python/index.htm" id="link3">Python</a>, <a class="prog" href="https://www.tutorialspoint.com/javascript/javascript_overview.htm" id="link4">JavaScript</a>, <a class="prog" href="https://www.tutorialspoint.com/ruby/index.htm" id="link5">C</a>]
We can search tag’s children in a list by its .contents −
>>> head_tag = soup.head
>>> head_tag
<head><title>Tutorials Point</title></head>
>>> Htag = soup.head
>>> Htag
<head><title>Tutorials Point</title></head>
>>>
>>> Htag.contents
[<title>Tutorials Point</title>
>>>
>>> Ttag = head_tag.contents[0]
>>> Ttag
<title>Tutorials Point</title>
>>> Ttag.contents
['Tutorials Point']
The BeautifulSoup object itself has children. In this case, the <html> tag is the child of the BeautifulSoup object −
>>> len(soup.contents)
2
>>> soup.contents[1].name
'html'
A string does not have .contents, because it can’t contain anything −
>>> text = Ttag.contents[0]
>>> text.contents
self.__class__.__name__, attr))
AttributeError: 'NavigableString' object has no attribute 'contents'
Instead of getting them as a list, use .children generator to access tag’s children −
>>> for child in Ttag.children:
print(child)
Tutorials Point
The .descendants attribute allows you to iterate over all of a tag’s children, recursively −
its direct children and the children of its direct children and so on −
>>> for child in Htag.descendants:
print(child)
<title>Tutorials Point</title>
Tutorials Point
The <head> tag has only one child, but it has two descendants: the <title> tag and the <title> tag’s child. The beautifulsoup object has only one direct child (the <html> tag), but it has a whole lot of descendants −
>>> len(list(soup.children))
2
>>> len(list(soup.descendants))
33
If the tag has only one child, and that child is a NavigableString, the child is made available as .string −
>>> Ttag.string
'Tutorials Point'
If a tag’s only child is another tag, and that tag has a .string, then the parent tag is considered to have the same .string as its child −
>>> Htag.contents
[<title>Tutorials Point</title>]
>>>
>>> Htag.string
'Tutorials Point'
However, if a tag contains more than one thing, then it’s not clear what .string should refer to, so .string is defined to None −
>>> print(soup.html.string)
None
If there’s more than one thing inside a tag, you can still look at just the strings. Use the .strings generator −
>>> for string in soup.strings:
print(repr(string))
'\n'
'Tutorials Point'
'\n'
'\n'
"The Biggest Online Tutorials Library, It's all Free"
'\n'
'Top 5 most used Programming Languages are: \n'
'Java'
',\n'
'C'
',\n'
'Python'
',\n'
'JavaScript'
' and\n'
'C'
';\n \nas per online survey.'
'\n'
'Programming Languages'
'\n'
To remove extra whitespace, use .stripped_strings generator −
>>> for string in soup.stripped_strings:
print(repr(string))
'Tutorials Point'
"The Biggest Online Tutorials Library, It's all Free"
'Top 5 most used Programming Languages are:'
'Java'
','
'C'
','
'Python'
','
'JavaScript'
'and'
'C'
';\n \nas per online survey.'
'Programming Languages'
In a “family tree” analogy, every tag and every string has a parent: the tag that contain it:
To access the element’s parent element, use .parent attribute.
>>> Ttag = soup.title
>>> Ttag
<title>Tutorials Point</title>
>>> Ttag.parent
<head>title>Tutorials Point</title></head>
In our html_doc, the title string itself has a parent: the <title> tag that contain it−
>>> Ttag.string.parent
<title>Tutorials Point</title>
The parent of a top-level tag like <html> is the Beautifulsoup object itself −
>>> htmltag = soup.html
>>> type(htmltag.parent)
<class 'bs4.BeautifulSoup'>
The .parent of a Beautifulsoup object is defined as None −
>>> print(soup.parent)
None
To iterate over all the parents elements, use .parents attribute.
>>> link = soup.a
>>> link
<a class="prog" href="https://www.tutorialspoint.com/java/java_overview.htm" id="link1">Java</a>
>>>
>>> for parent in link.parents:
if parent is None:
print(parent)
else:
print(parent.name)
p
body
html
[document]
Below is one simple document −
>>> sibling_soup = BeautifulSoup("<a><b>TutorialsPoint</b><c><strong>The Biggest Online Tutorials Library, It's all Free</strong></b></a>")
>>> print(sibling_soup.prettify())
<html>
<body>
<a>
<b>
TutorialsPoint
</b>
<c>
<strong>
The Biggest Online Tutorials Library, It's all Free
</strong>
</c>
</a>
</body>
</html>
In the above doc, <b> and <c> tag is at the same level and they are both children of the same tag. Both <b> and <c> tag are siblings.
Use .next_sibling and .previous_sibling to navigate between page elements that are on the same level of the parse tree:
>>> sibling_soup.b.next_sibling
<c><strong>The Biggest Online Tutorials Library, It's all Free</strong></c>
>>>
>>> sibling_soup.c.previous_sibling
<b>TutorialsPoint</b>
The <b> tag has a .next_sibling but no .previous_sibling, as there is nothing before the <b> tag on the same level of the tree, same case is with <c> tag.
>>> print(sibling_soup.b.previous_sibling)
None
>>> print(sibling_soup.c.next_sibling)
None
The two strings are not siblings, as they don’t have the same parent.
>>> sibling_soup.b.string
'TutorialsPoint'
>>>
>>> print(sibling_soup.b.string.next_sibling)
None
To iterate over a tag’s siblings use .next_siblings and .previous_siblings.
>>> for sibling in soup.a.next_siblings:
print(repr(sibling))
',\n'
<a class="prog" href="https://www.tutorialspoint.com/cprogramming/index.htm" id="link2">C</a>
',\n'
>a class="prog" href="https://www.tutorialspoint.com/python/index.htm" id="link3">Python</a>
',\n'
<a class="prog" href="https://www.tutorialspoint.com/javascript/javascript_overview.htm" id="link4">JavaScript</a>
' and\n'
<a class="prog" href="https://www.tutorialspoint.com/ruby/index.htm"
id="link5">C</a>
';\n \nas per online survey.'
>>> for sibling in soup.find(id="link3").previous_siblings:
print(repr(sibling))
',\n'
<a class="prog" href="https://www.tutorialspoint.com/cprogramming/index.htm" id="link2">C</a>
',\n'
<a class="prog" href="https://www.tutorialspoint.com/java/java_overview.htm" id="link1">Java</a>
'Top 5 most used Programming Languages are: \n'
Now let us get back to first two lines in our previous “html_doc” example −
&t;html><head><title>Tutorials Point</title></head>
<body>
<h4 class="tagLine"><b>The Biggest Online Tutorials Library, It's all Free</b></h4>
An HTML parser takes above string of characters and turns it into a series of events like “open an <html> tag”, “open an <head> tag”, “open the <title> tag”, “add a string”, “close the </title> tag”, “close the </head> tag”, “open a <h4> tag” and so on. BeautifulSoup offers different methods to reconstructs the initial parse of the document.
The .next_element attribute of a tag or string points to whatever was parsed immediately afterwards. Sometimes it looks similar to .next_sibling, however it is not same entirely.
Below is the final <a> tag in our “html_doc” example document.
>>> last_a_tag = soup.find("a", id="link5")
>>> last_a_tag
<a class="prog" href="https://www.tutorialspoint.com/ruby/index.htm" id="link5">C</a>
>>> last_a_tag.next_sibling
';\n \nas per online survey.'
However the .next_element of that <a> tag, the thing that was parsed immediately after the <a> tag, is not the rest of that sentence: it is the word “C”:
>>> last_a_tag.next_element
'C'
Above behavior is because in the original markup, the letter “C” appeared before that semicolon. The parser encountered an <a> tag, then the letter “C”, then the closing </a> tag, then the semicolon and rest of the sentence. The semicolon is on the same level as the <a> tag, but the letter “C” was encountered first.
The .previous_element attribute is the exact opposite of .next_element. It points to whatever element was parsed immediately before this one.
>>> last_a_tag.previous_element
' and\n'
>>>
>>> last_a_tag.previous_element.next_element
<a class="prog" href="https://www.tutorialspoint.com/ruby/index.htm" id="link5">C</a>
We use these iterators to move forward and backward to an element.
>>> for element in last_a_tag.next_e lements:
print(repr(element))
'C'
';\n \nas per online survey.'
'\n'
<p class="prog">Programming Languages</p>
'Programming Languages'
'\n'
38 Lectures
3.5 hours
Chandramouli Jayendran
22 Lectures
1 hours
TELCOMA Global
6 Lectures
1 hours
AlexanderSchlee
6 Lectures
1 hours
AlexanderSchlee
6 Lectures
1 hours
AlexanderSchlee
22 Lectures
4 hours
AlexanderSchlee
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2045,
"s": 1985,
"text": "In this chapter, we shall discuss about Navigating by Tags."
},
{
"code": null,
"e": 2074,
"s": 2045,
"text": "Below is our html document −"
},
{
"code": null,
"e": 2946,
"s": 2074,
"text": ">>> html_doc = \"\"\"\n<html><head><title>Tutorials Point</title></head>\n<body>\n<p class=\"title\"><b>The Biggest Online Tutorials Library, It's all Free</b></p>\n<p class=\"prog\">Top 5 most used Programming Languages are:\n<a href=\"https://www.tutorialspoint.com/java/java_overview.htm\" class=\"prog\" id=\"link1\">Java</a>,\n<a href=\"https://www.tutorialspoint.com/cprogramming/index.htm\" class=\"prog\" id=\"link2\">C</a>,\n<a href=\"https://www.tutorialspoint.com/python/index.htm\" class=\"prog\" id=\"link3\">Python</a>,\n<a href=\"https://www.tutorialspoint.com/javascript/javascript_overview.htm\" class=\"prog\" id=\"link4\">JavaScript</a> and\n<a href=\"https://www.tutorialspoint.com/ruby/index.htm\" class=\"prog\" id=\"link5\">C</a>;\nas per online survey.</p>\n<p class=\"prog\">Programming Languages</p>\n\"\"\"\n>>>\n>>> from bs4 import BeautifulSoup\n>>> soup = BeautifulSoup(html_doc, 'html.parser')\n>>>"
},
{
"code": null,
"e": 3033,
"s": 2946,
"text": "Based on the above document, we will try to move from one part of document to another."
},
{
"code": null,
"e": 3253,
"s": 3033,
"text": "One of the important pieces of element in any piece of HTML document are tags, which may contain other tags/strings (tag’s children). Beautiful Soup provides different ways to navigate and iterate over’s tag’s children."
},
{
"code": null,
"e": 3366,
"s": 3253,
"text": "Easiest way to search a parse tree is to search the tag by its name. If you want the <head> tag, use soup.head −"
},
{
"code": null,
"e": 3472,
"s": 3366,
"text": ">>> soup.head\n<head>&t;title>Tutorials Point</title></head>\n>>> soup.title\n<title>Tutorials Point</title>"
},
{
"code": null,
"e": 3532,
"s": 3472,
"text": "To get specific tag (like first <b> tag) in the <body> tag."
},
{
"code": null,
"e": 3607,
"s": 3532,
"text": ">>> soup.body.b\n<b>The Biggest Online Tutorials Library, It's all Free</b>"
},
{
"code": null,
"e": 3688,
"s": 3607,
"text": "Using a tag name as an attribute will give you only the first tag by that name −"
},
{
"code": null,
"e": 3797,
"s": 3688,
"text": ">>> soup.a\n<a class=\"prog\" href=\"https://www.tutorialspoint.com/java/java_overview.htm\" id=\"link1\">Java</a>\n"
},
{
"code": null,
"e": 3861,
"s": 3797,
"text": "To get all the tag’s attribute, you can use find_all() method −"
},
{
"code": null,
"e": 4888,
"s": 3861,
"text": ">>> soup.find_all(\"a\")\n[<a class=\"prog\" href=\"https://www.tutorialspoint.com/java/java_overview.htm\" id=\"link1\">Java</a>, <a class=\"prog\" href=\"https://www.tutorialspoint.com/cprogramming/index.htm\" id=\"link2\">C</a>, <a class=\"prog\" href=\"https://www.tutorialspoint.com/python/index.htm\" id=\"link3\">Python</a>, <a class=\"prog\" href=\"https://www.tutorialspoint.com/javascript/javascript_overview.htm\" id=\"link4\">JavaScript</a>, <a class=\"prog\" href=\"https://www.tutorialspoint.com/ruby/index.htm\" id=\"link5\">C</a>]>>> soup.find_all(\"a\")\n[<a class=\"prog\" href=\"https://www.tutorialspoint.com/java/java_overview.htm\" id=\"link1\">Java</a>, <a class=\"prog\" href=\"https://www.tutorialspoint.com/cprogramming/index.htm\" id=\"link2\">C</a>, <a class=\"prog\" href=\"https://www.tutorialspoint.com/python/index.htm\" id=\"link3\">Python</a>, <a class=\"prog\" href=\"https://www.tutorialspoint.com/javascript/javascript_overview.htm\" id=\"link4\">JavaScript</a>, <a class=\"prog\" href=\"https://www.tutorialspoint.com/ruby/index.htm\" id=\"link5\">C</a>]"
},
{
"code": null,
"e": 4946,
"s": 4888,
"text": "We can search tag’s children in a list by its .contents −"
},
{
"code": null,
"e": 5270,
"s": 4946,
"text": ">>> head_tag = soup.head\n>>> head_tag\n<head><title>Tutorials Point</title></head>\n>>> Htag = soup.head\n>>> Htag\n<head><title>Tutorials Point</title></head>\n>>>\n>>> Htag.contents\n[<title>Tutorials Point</title>\n>>>\n>>> Ttag = head_tag.contents[0]\n>>> Ttag\n<title>Tutorials Point</title>\n>>> Ttag.contents\n['Tutorials Point']"
},
{
"code": null,
"e": 5388,
"s": 5270,
"text": "The BeautifulSoup object itself has children. In this case, the <html> tag is the child of the BeautifulSoup object −"
},
{
"code": null,
"e": 5446,
"s": 5388,
"text": ">>> len(soup.contents)\n2\n>>> soup.contents[1].name\n'html'"
},
{
"code": null,
"e": 5516,
"s": 5446,
"text": "A string does not have .contents, because it can’t contain anything −"
},
{
"code": null,
"e": 5663,
"s": 5516,
"text": ">>> text = Ttag.contents[0]\n>>> text.contents\nself.__class__.__name__, attr))\nAttributeError: 'NavigableString' object has no attribute 'contents'"
},
{
"code": null,
"e": 5749,
"s": 5663,
"text": "Instead of getting them as a list, use .children generator to access tag’s children −"
},
{
"code": null,
"e": 5811,
"s": 5749,
"text": ">>> for child in Ttag.children:\nprint(child)\nTutorials Point\n"
},
{
"code": null,
"e": 5904,
"s": 5811,
"text": "The .descendants attribute allows you to iterate over all of a tag’s children, recursively −"
},
{
"code": null,
"e": 5976,
"s": 5904,
"text": "its direct children and the children of its direct children and so on −"
},
{
"code": null,
"e": 6072,
"s": 5976,
"text": ">>> for child in Htag.descendants:\nprint(child)\n<title>Tutorials Point</title>\nTutorials Point\n"
},
{
"code": null,
"e": 6289,
"s": 6072,
"text": "The <head> tag has only one child, but it has two descendants: the <title> tag and the <title> tag’s child. The beautifulsoup object has only one direct child (the <html> tag), but it has a whole lot of descendants −"
},
{
"code": null,
"e": 6356,
"s": 6289,
"text": ">>> len(list(soup.children))\n2\n>>> len(list(soup.descendants))\n33\n"
},
{
"code": null,
"e": 6465,
"s": 6356,
"text": "If the tag has only one child, and that child is a NavigableString, the child is made available as .string −"
},
{
"code": null,
"e": 6500,
"s": 6465,
"text": ">>> Ttag.string\n'Tutorials Point'\n"
},
{
"code": null,
"e": 6640,
"s": 6500,
"text": "If a tag’s only child is another tag, and that tag has a .string, then the parent tag is considered to have the same .string as its child −"
},
{
"code": null,
"e": 6729,
"s": 6640,
"text": ">>> Htag.contents\n[<title>Tutorials Point</title>]\n>>>\n>>> Htag.string\n'Tutorials Point'"
},
{
"code": null,
"e": 6859,
"s": 6729,
"text": "However, if a tag contains more than one thing, then it’s not clear what .string should refer to, so .string is defined to None −"
},
{
"code": null,
"e": 6893,
"s": 6859,
"text": ">>> print(soup.html.string)\nNone\n"
},
{
"code": null,
"e": 7007,
"s": 6893,
"text": "If there’s more than one thing inside a tag, you can still look at just the strings. Use the .strings generator −"
},
{
"code": null,
"e": 7327,
"s": 7007,
"text": ">>> for string in soup.strings:\nprint(repr(string))\n'\\n'\n'Tutorials Point'\n'\\n'\n'\\n'\n\"The Biggest Online Tutorials Library, It's all Free\"\n'\\n'\n'Top 5 most used Programming Languages are: \\n'\n'Java'\n',\\n'\n'C'\n',\\n'\n'Python'\n',\\n'\n'JavaScript'\n' and\\n'\n'C'\n';\\n \\nas per online survey.'\n'\\n'\n'Programming Languages'\n'\\n'"
},
{
"code": null,
"e": 7389,
"s": 7327,
"text": "To remove extra whitespace, use .stripped_strings generator −"
},
{
"code": null,
"e": 7676,
"s": 7389,
"text": ">>> for string in soup.stripped_strings:\nprint(repr(string))\n'Tutorials Point'\n\"The Biggest Online Tutorials Library, It's all Free\"\n'Top 5 most used Programming Languages are:'\n'Java'\n','\n'C'\n','\n'Python'\n','\n'JavaScript'\n'and'\n'C'\n';\\n \\nas per online survey.'\n'Programming Languages'"
},
{
"code": null,
"e": 7770,
"s": 7676,
"text": "In a “family tree” analogy, every tag and every string has a parent: the tag that contain it:"
},
{
"code": null,
"e": 7833,
"s": 7770,
"text": "To access the element’s parent element, use .parent attribute."
},
{
"code": null,
"e": 7954,
"s": 7833,
"text": ">>> Ttag = soup.title\n>>> Ttag\n<title>Tutorials Point</title>\n>>> Ttag.parent\n<head>title>Tutorials Point</title></head>"
},
{
"code": null,
"e": 8042,
"s": 7954,
"text": "In our html_doc, the title string itself has a parent: the <title> tag that contain it−"
},
{
"code": null,
"e": 8097,
"s": 8042,
"text": ">>> Ttag.string.parent\n<title>Tutorials Point</title>\n"
},
{
"code": null,
"e": 8176,
"s": 8097,
"text": "The parent of a top-level tag like <html> is the Beautifulsoup object itself −"
},
{
"code": null,
"e": 8254,
"s": 8176,
"text": ">>> htmltag = soup.html\n>>> type(htmltag.parent)\n<class 'bs4.BeautifulSoup'>\n"
},
{
"code": null,
"e": 8313,
"s": 8254,
"text": "The .parent of a Beautifulsoup object is defined as None −"
},
{
"code": null,
"e": 8342,
"s": 8313,
"text": ">>> print(soup.parent)\nNone\n"
},
{
"code": null,
"e": 8408,
"s": 8342,
"text": "To iterate over all the parents elements, use .parents attribute."
},
{
"code": null,
"e": 8649,
"s": 8408,
"text": ">>> link = soup.a\n>>> link\n<a class=\"prog\" href=\"https://www.tutorialspoint.com/java/java_overview.htm\" id=\"link1\">Java</a>\n>>>\n>>> for parent in link.parents:\nif parent is None:\nprint(parent)\nelse:\nprint(parent.name)\np\nbody\nhtml\n[document]"
},
{
"code": null,
"e": 8680,
"s": 8649,
"text": "Below is one simple document −"
},
{
"code": null,
"e": 9067,
"s": 8680,
"text": ">>> sibling_soup = BeautifulSoup(\"<a><b>TutorialsPoint</b><c><strong>The Biggest Online Tutorials Library, It's all Free</strong></b></a>\")\n>>> print(sibling_soup.prettify())\n<html>\n<body>\n <a>\n <b>\n TutorialsPoint\n </b>\n <c>\n <strong>\n The Biggest Online Tutorials Library, It's all Free\n </strong>\n </c>\n </a>\n</body>\n</html>"
},
{
"code": null,
"e": 9201,
"s": 9067,
"text": "In the above doc, <b> and <c> tag is at the same level and they are both children of the same tag. Both <b> and <c> tag are siblings."
},
{
"code": null,
"e": 9321,
"s": 9201,
"text": "Use .next_sibling and .previous_sibling to navigate between page elements that are on the same level of the parse tree:"
},
{
"code": null,
"e": 9491,
"s": 9321,
"text": ">>> sibling_soup.b.next_sibling\n<c><strong>The Biggest Online Tutorials Library, It's all Free</strong></c>\n>>>\n>>> sibling_soup.c.previous_sibling\n<b>TutorialsPoint</b>"
},
{
"code": null,
"e": 9646,
"s": 9491,
"text": "The <b> tag has a .next_sibling but no .previous_sibling, as there is nothing before the <b> tag on the same level of the tree, same case is with <c> tag."
},
{
"code": null,
"e": 9739,
"s": 9646,
"text": ">>> print(sibling_soup.b.previous_sibling)\nNone\n>>> print(sibling_soup.c.next_sibling)\nNone\n"
},
{
"code": null,
"e": 9809,
"s": 9739,
"text": "The two strings are not siblings, as they don’t have the same parent."
},
{
"code": null,
"e": 9907,
"s": 9809,
"text": ">>> sibling_soup.b.string\n'TutorialsPoint'\n>>>\n>>> print(sibling_soup.b.string.next_sibling)\nNone"
},
{
"code": null,
"e": 9983,
"s": 9907,
"text": "To iterate over a tag’s siblings use .next_siblings and .previous_siblings."
},
{
"code": null,
"e": 10822,
"s": 9983,
"text": ">>> for sibling in soup.a.next_siblings:\nprint(repr(sibling))\n',\\n'\n<a class=\"prog\" href=\"https://www.tutorialspoint.com/cprogramming/index.htm\" id=\"link2\">C</a>\n',\\n'\n>a class=\"prog\" href=\"https://www.tutorialspoint.com/python/index.htm\" id=\"link3\">Python</a>\n',\\n'\n<a class=\"prog\" href=\"https://www.tutorialspoint.com/javascript/javascript_overview.htm\" id=\"link4\">JavaScript</a>\n' and\\n'\n<a class=\"prog\" href=\"https://www.tutorialspoint.com/ruby/index.htm\"\nid=\"link5\">C</a>\n';\\n \\nas per online survey.'\n>>> for sibling in soup.find(id=\"link3\").previous_siblings:\nprint(repr(sibling))\n',\\n'\n<a class=\"prog\" href=\"https://www.tutorialspoint.com/cprogramming/index.htm\" id=\"link2\">C</a>\n',\\n'\n<a class=\"prog\" href=\"https://www.tutorialspoint.com/java/java_overview.htm\" id=\"link1\">Java</a>\n'Top 5 most used Programming Languages are: \\n'"
},
{
"code": null,
"e": 10898,
"s": 10822,
"text": "Now let us get back to first two lines in our previous “html_doc” example −"
},
{
"code": null,
"e": 11041,
"s": 10898,
"text": "&t;html><head><title>Tutorials Point</title></head>\n<body>\n<h4 class=\"tagLine\"><b>The Biggest Online Tutorials Library, It's all Free</b></h4>"
},
{
"code": null,
"e": 11385,
"s": 11041,
"text": "An HTML parser takes above string of characters and turns it into a series of events like “open an <html> tag”, “open an <head> tag”, “open the <title> tag”, “add a string”, “close the </title> tag”, “close the </head> tag”, “open a <h4> tag” and so on. BeautifulSoup offers different methods to reconstructs the initial parse of the document."
},
{
"code": null,
"e": 11627,
"s": 11385,
"text": "The .next_element attribute of a tag or string points to whatever was parsed immediately afterwards. Sometimes it looks similar to .next_sibling, however it is not same entirely.\nBelow is the final <a> tag in our “html_doc” example document."
},
{
"code": null,
"e": 11830,
"s": 11627,
"text": ">>> last_a_tag = soup.find(\"a\", id=\"link5\")\n>>> last_a_tag\n<a class=\"prog\" href=\"https://www.tutorialspoint.com/ruby/index.htm\" id=\"link5\">C</a>\n>>> last_a_tag.next_sibling\n';\\n \\nas per online survey.'"
},
{
"code": null,
"e": 11984,
"s": 11830,
"text": "However the .next_element of that <a> tag, the thing that was parsed immediately after the <a> tag, is not the rest of that sentence: it is the word “C”:"
},
{
"code": null,
"e": 12017,
"s": 11984,
"text": ">>> last_a_tag.next_element\n'C'\n"
},
{
"code": null,
"e": 12335,
"s": 12017,
"text": "Above behavior is because in the original markup, the letter “C” appeared before that semicolon. The parser encountered an <a> tag, then the letter “C”, then the closing </a> tag, then the semicolon and rest of the sentence. The semicolon is on the same level as the <a> tag, but the letter “C” was encountered first."
},
{
"code": null,
"e": 12477,
"s": 12335,
"text": "The .previous_element attribute is the exact opposite of .next_element. It points to whatever element was parsed immediately before this one."
},
{
"code": null,
"e": 12653,
"s": 12477,
"text": ">>> last_a_tag.previous_element\n' and\\n'\n>>>\n>>> last_a_tag.previous_element.next_element\n<a class=\"prog\" href=\"https://www.tutorialspoint.com/ruby/index.htm\" id=\"link5\">C</a>"
},
{
"code": null,
"e": 12720,
"s": 12653,
"text": "We use these iterators to move forward and backward to an element."
},
{
"code": null,
"e": 12898,
"s": 12720,
"text": ">>> for element in last_a_tag.next_e lements:\nprint(repr(element))\n'C'\n';\\n \\nas per online survey.'\n'\\n'\n<p class=\"prog\">Programming Languages</p>\n'Programming Languages'\n'\\n'\n"
},
{
"code": null,
"e": 12933,
"s": 12898,
"text": "\n 38 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 12957,
"s": 12933,
"text": " Chandramouli Jayendran"
},
{
"code": null,
"e": 12990,
"s": 12957,
"text": "\n 22 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 13006,
"s": 12990,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 13038,
"s": 13006,
"text": "\n 6 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 13055,
"s": 13038,
"text": " AlexanderSchlee"
},
{
"code": null,
"e": 13087,
"s": 13055,
"text": "\n 6 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 13104,
"s": 13087,
"text": " AlexanderSchlee"
},
{
"code": null,
"e": 13136,
"s": 13104,
"text": "\n 6 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 13153,
"s": 13136,
"text": " AlexanderSchlee"
},
{
"code": null,
"e": 13186,
"s": 13153,
"text": "\n 22 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 13203,
"s": 13186,
"text": " AlexanderSchlee"
},
{
"code": null,
"e": 13210,
"s": 13203,
"text": " Print"
},
{
"code": null,
"e": 13221,
"s": 13210,
"text": " Add Notes"
}
] |
Static vs Dynamic Binding in Java | In Java static binding refers to the execution of a program where type of object is determined/known at compile time i.e when compiler executes the code it know the type of object or class to which object belongs.While in case of dynamic binding the type of object is determined at runtime.
Also static binding uses type of class to bind while dynamic binding uses type of object as the resolution happens only at runtime because object only created during runtime due to which dynamic binding becomes slower than in case of static binding.
As private,final and static modifiers binds to the class level so methods and variables uses static binding and bonded by compiler while the other methods are bonded during runtime based upon runtime object.
In general we can say that overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding.
Live Demo
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
public class StaticDynamicBinding {
public static void main(String[] args) {
Collection<String> col = new HashSet<>();
col.add("hello");
StaticDynamicBinding sdObj = new StaticDynamicBinding();
sdObj.print(col);
StaticDynamicBinding sdObj1 = new StaticDynamicBindingClass();
sdObj1.print(col);
}
void print(Collection<String> col) {
System.out.println("in collection method");
}
void print(HashSet<String> hs) {
System.out.println("in hashset method");
}
}
class StaticDynamicBindingClass extends StaticDynamicBinding {
void print(Collection<String> col) {
System.out.println("in collection method of child class");
}
}
in collection method
in collection method of child class | [
{
"code": null,
"e": 1353,
"s": 1062,
"text": "In Java static binding refers to the execution of a program where type of object is determined/known at compile time i.e when compiler executes the code it know the type of object or class to which object belongs.While in case of dynamic binding the type of object is determined at runtime."
},
{
"code": null,
"e": 1603,
"s": 1353,
"text": "Also static binding uses type of class to bind while dynamic binding uses type of object as the resolution happens only at runtime because object only created during runtime due to which dynamic binding becomes slower than in case of static binding."
},
{
"code": null,
"e": 1811,
"s": 1603,
"text": "As private,final and static modifiers binds to the class level so methods and variables uses static binding and bonded by compiler while the other methods are bonded during runtime based upon runtime object."
},
{
"code": null,
"e": 1948,
"s": 1811,
"text": "In general we can say that overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding."
},
{
"code": null,
"e": 1959,
"s": 1948,
"text": " Live Demo"
},
{
"code": null,
"e": 2742,
"s": 1959,
"text": "import java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashSet;\npublic class StaticDynamicBinding {\n public static void main(String[] args) {\n Collection<String> col = new HashSet<>();\n col.add(\"hello\");\n StaticDynamicBinding sdObj = new StaticDynamicBinding();\n sdObj.print(col);\n StaticDynamicBinding sdObj1 = new StaticDynamicBindingClass();\n sdObj1.print(col);\n }\n void print(Collection<String> col) {\n System.out.println(\"in collection method\");\n }\n void print(HashSet<String> hs) {\n System.out.println(\"in hashset method\");\n }\n}\nclass StaticDynamicBindingClass extends StaticDynamicBinding {\n void print(Collection<String> col) {\n System.out.println(\"in collection method of child class\");\n }\n}"
},
{
"code": null,
"e": 2800,
"s": 2742,
"text": "in collection method\nin collection method of child class\n"
}
] |
DBMS - Quick Guide | Database is a collection of related data and data is a collection of facts and figures that can be processed to produce information.
Mostly data represents recordable facts. Data aids in producing information, which is based on facts. For example, if we have data about marks obtained by all students, we can then conclude about toppers and average marks.
A database management system stores data in such a way that it becomes easier to retrieve, manipulate, and produce information.
Traditionally, data was organized in file formats. DBMS was a new concept then, and all the research was done to make it overcome the deficiencies in traditional style of data management. A modern DBMS has the following characteristics −
Real-world entity − A modern DBMS is more realistic and uses real-world entities to design its architecture. It uses the behavior and attributes too. For example, a school database may use students as an entity and their age as an attribute.
Real-world entity − A modern DBMS is more realistic and uses real-world entities to design its architecture. It uses the behavior and attributes too. For example, a school database may use students as an entity and their age as an attribute.
Relation-based tables − DBMS allows entities and relations among them to form tables. A user can understand the architecture of a database just by looking at the table names.
Relation-based tables − DBMS allows entities and relations among them to form tables. A user can understand the architecture of a database just by looking at the table names.
Isolation of data and application − A database system is entirely different than its data. A database is an active entity, whereas data is said to be passive, on which the database works and organizes. DBMS also stores metadata, which is data about data, to ease its own process.
Isolation of data and application − A database system is entirely different than its data. A database is an active entity, whereas data is said to be passive, on which the database works and organizes. DBMS also stores metadata, which is data about data, to ease its own process.
Less redundancy − DBMS follows the rules of normalization, which splits a relation when any of its attributes is having redundancy in values. Normalization is a mathematically rich and scientific process that reduces data redundancy.
Less redundancy − DBMS follows the rules of normalization, which splits a relation when any of its attributes is having redundancy in values. Normalization is a mathematically rich and scientific process that reduces data redundancy.
Consistency − Consistency is a state where every relation in a database remains consistent. There exist methods and techniques, which can detect attempt of leaving database in inconsistent state. A DBMS can provide greater consistency as compared to earlier forms of data storing applications like file-processing systems.
Consistency − Consistency is a state where every relation in a database remains consistent. There exist methods and techniques, which can detect attempt of leaving database in inconsistent state. A DBMS can provide greater consistency as compared to earlier forms of data storing applications like file-processing systems.
Query Language − DBMS is equipped with query language, which makes it more efficient to retrieve and manipulate data. A user can apply as many and as different filtering options as required to retrieve a set of data. Traditionally it was not possible where file-processing system was used.
Query Language − DBMS is equipped with query language, which makes it more efficient to retrieve and manipulate data. A user can apply as many and as different filtering options as required to retrieve a set of data. Traditionally it was not possible where file-processing system was used.
ACID Properties − DBMS follows the concepts of Atomicity, Consistency, Isolation, and Durability (normally shortened as ACID). These concepts are applied on transactions, which manipulate data in a database. ACID properties help the database stay healthy in multi-transactional environments and in case of failure.
ACID Properties − DBMS follows the concepts of Atomicity, Consistency, Isolation, and Durability (normally shortened as ACID). These concepts are applied on transactions, which manipulate data in a database. ACID properties help the database stay healthy in multi-transactional environments and in case of failure.
Multiuser and Concurrent Access − DBMS supports multi-user environment and allows them to access and manipulate data in parallel. Though there are restrictions on transactions when users attempt to handle the same data item, but users are always unaware of them.
Multiuser and Concurrent Access − DBMS supports multi-user environment and allows them to access and manipulate data in parallel. Though there are restrictions on transactions when users attempt to handle the same data item, but users are always unaware of them.
Multiple views − DBMS offers multiple views for different users. A user who is in the Sales department will have a different view of database than a person working in the Production department. This feature enables the users to have a concentrate view of the database according to their requirements.
Multiple views − DBMS offers multiple views for different users. A user who is in the Sales department will have a different view of database than a person working in the Production department. This feature enables the users to have a concentrate view of the database according to their requirements.
Security − Features like multiple views offer security to some extent where users are unable to access data of other users and departments. DBMS offers methods to impose constraints while entering data into the database and retrieving the same at a later stage. DBMS offers many different levels of security features, which enables multiple users to have different views with different features. For example, a user in the Sales department cannot see the data that belongs to the Purchase department. Additionally, it can also be managed how much data of the Sales department should be displayed to the user. Since a DBMS is not saved on the disk as traditional file systems, it is very hard for miscreants to break the code.
Security − Features like multiple views offer security to some extent where users are unable to access data of other users and departments. DBMS offers methods to impose constraints while entering data into the database and retrieving the same at a later stage. DBMS offers many different levels of security features, which enables multiple users to have different views with different features. For example, a user in the Sales department cannot see the data that belongs to the Purchase department. Additionally, it can also be managed how much data of the Sales department should be displayed to the user. Since a DBMS is not saved on the disk as traditional file systems, it is very hard for miscreants to break the code.
A typical DBMS has users with different rights and permissions who use it for different purposes. Some users retrieve data and some back it up. The users of a DBMS can be broadly categorized as follows −
Administrators − Administrators maintain the DBMS and are responsible for administrating the database. They are responsible to look after its usage and by whom it should be used. They create access profiles for users and apply limitations to maintain isolation and force security. Administrators also look after DBMS resources like system license, required tools, and other software and hardware related maintenance.
Administrators − Administrators maintain the DBMS and are responsible for administrating the database. They are responsible to look after its usage and by whom it should be used. They create access profiles for users and apply limitations to maintain isolation and force security. Administrators also look after DBMS resources like system license, required tools, and other software and hardware related maintenance.
Designers − Designers are the group of people who actually work on the designing part of the database. They keep a close watch on what data should be kept and in what format. They identify and design the whole set of entities, relations, constraints, and views.
Designers − Designers are the group of people who actually work on the designing part of the database. They keep a close watch on what data should be kept and in what format. They identify and design the whole set of entities, relations, constraints, and views.
End Users − End users are those who actually reap the benefits of having a DBMS. End users can range from simple viewers who pay attention to the logs or market rates to sophisticated users such as business analysts.
End Users − End users are those who actually reap the benefits of having a DBMS. End users can range from simple viewers who pay attention to the logs or market rates to sophisticated users such as business analysts.
The design of a DBMS depends on its architecture. It can be centralized or decentralized or hierarchical. The architecture of a DBMS can be seen as either single tier or multi-tier. An n-tier architecture divides the whole system into related but independent n modules, which can be independently modified, altered, changed, or replaced.
In 1-tier architecture, the DBMS is the only entity where the user directly sits on the DBMS and uses it. Any changes done here will directly be done on the DBMS itself. It does not provide handy tools for end-users. Database designers and programmers normally prefer to use single-tier architecture.
If the architecture of DBMS is 2-tier, then it must have an application through which the DBMS can be accessed. Programmers use 2-tier architecture where they access the DBMS by means of an application. Here the application tier is entirely independent of the database in terms of operation, design, and programming.
A 3-tier architecture separates its tiers from each other based on the complexity of the users and how they use the data present in the database. It is the most widely used architecture to design a DBMS.
Database (Data) Tier − At this tier, the database resides along with its query processing languages. We also have the relations that define the data and their constraints at this level.
Database (Data) Tier − At this tier, the database resides along with its query processing languages. We also have the relations that define the data and their constraints at this level.
Application (Middle) Tier − At this tier reside the application server and the programs that access the database. For a user, this application tier presents an abstracted view of the database. End-users are unaware of any existence of the database beyond the application. At the other end, the database tier is not aware of any other user beyond the application tier. Hence, the application layer sits in the middle and acts as a mediator between the end-user and the database.
Application (Middle) Tier − At this tier reside the application server and the programs that access the database. For a user, this application tier presents an abstracted view of the database. End-users are unaware of any existence of the database beyond the application. At the other end, the database tier is not aware of any other user beyond the application tier. Hence, the application layer sits in the middle and acts as a mediator between the end-user and the database.
User (Presentation) Tier − End-users operate on this tier and they know nothing about any existence of the database beyond this layer. At this layer, multiple views of the database can be provided by the application. All views are generated by applications that reside in the application tier.
User (Presentation) Tier − End-users operate on this tier and they know nothing about any existence of the database beyond this layer. At this layer, multiple views of the database can be provided by the application. All views are generated by applications that reside in the application tier.
Multiple-tier database architecture is highly modifiable, as almost all its components are independent and can be changed independently.
Data models define how the logical structure of a database is modeled. Data Models are fundamental entities to introduce abstraction in a DBMS. Data models define how data is connected to each other and how they are processed and stored inside the system.
The very first data model could be flat data-models, where all the data used are to be kept in the same plane. Earlier data models were not so scientific, hence they were prone to introduce lots of duplication and update anomalies.
Entity-Relationship (ER) Model is based on the notion of real-world entities and relationships among them. While formulating real-world scenario into the database model, the ER Model creates entity set, relationship set, general attributes and constraints.
ER Model is best used for the conceptual design of a database.
ER Model is based on −
Entities and their attributes.
Entities and their attributes.
Relationships among entities.
Relationships among entities.
These concepts are explained below.
Entity − An entity in an ER Model is a real-world entity having properties called attributes. Every attribute is defined by its set of values called domain. For example, in a school database, a student is considered as an entity. Student has various attributes like name, age, class, etc.
Entity − An entity in an ER Model is a real-world entity having properties called attributes. Every attribute is defined by its set of values called domain. For example, in a school database, a student is considered as an entity. Student has various attributes like name, age, class, etc.
Relationship − The logical association among entities is called relationship. Relationships are mapped with entities in various ways. Mapping cardinalities define the number of association between two entities.
Mapping cardinalities −
one to one
one to many
many to one
many to many
Relationship − The logical association among entities is called relationship. Relationships are mapped with entities in various ways. Mapping cardinalities define the number of association between two entities.
Mapping cardinalities −
one to one
one to many
many to one
many to many
The most popular data model in DBMS is the Relational Model. It is more scientific a model than others. This model is based on first-order predicate logic and defines a table as an n-ary relation.
The main highlights of this model are −
Data is stored in tables called relations.
Relations can be normalized.
In normalized relations, values saved are atomic values.
Each row in a relation contains a unique value.
Each column in a relation contains values from a same domain.
A database schema is the skeleton structure that represents the logical view of the entire database. It defines how the data is organized and how the relations among them are associated. It formulates all the constraints that are to be applied on the data.
A database schema defines its entities and the relationship among them. It contains a descriptive detail of the database, which can be depicted by means of schema diagrams. It’s the database designers who design the schema to help programmers understand the database and make it useful.
A database schema can be divided broadly into two categories −
Physical Database Schema − This schema pertains to the actual storage of data and its form of storage like files, indices, etc. It defines how the data will be stored in a secondary storage.
Physical Database Schema − This schema pertains to the actual storage of data and its form of storage like files, indices, etc. It defines how the data will be stored in a secondary storage.
Logical Database Schema − This schema defines all the logical constraints that need to be applied on the data stored. It defines tables, views, and integrity constraints.
Logical Database Schema − This schema defines all the logical constraints that need to be applied on the data stored. It defines tables, views, and integrity constraints.
It is important that we distinguish these two terms individually. Database schema is the skeleton of database. It is designed when the database doesn't exist at all. Once the database is operational, it is very difficult to make any changes to it. A database schema does not contain any data or information.
A database instance is a state of operational database with data at any given time. It contains a snapshot of the database. Database instances tend to change with time. A DBMS ensures that its every instance (state) is in a valid state, by diligently following all the validations, constraints, and conditions that the database designers have imposed.
If a database system is not multi-layered, then it becomes difficult to make any changes in the database system. Database systems are designed in multi-layers as we learnt earlier.
A database system normally contains a lot of data in addition to users’ data. For example, it stores data about data, known as metadata, to locate and retrieve data easily. It is rather difficult to modify or update a set of metadata once it is stored in the database. But as a DBMS expands, it needs to change over time to satisfy the requirements of the users. If the entire data is dependent, it would become a tedious and highly complex job.
Metadata itself follows a layered architecture, so that when we change data at one layer, it does not affect the data at another level. This data is independent but mapped to each other.
Logical data is data about database, that is, it stores information about how data is managed inside. For example, a table (relation) stored in the database and all its constraints, applied on that relation.
Logical data independence is a kind of mechanism, which liberalizes itself from actual data stored on the disk. If we do some changes on table format, it should not change the data residing on the disk.
All the schemas are logical, and the actual data is stored in bit format on the disk. Physical data independence is the power to change the physical data without impacting the schema or logical data.
For example, in case we want to change or upgrade the storage system itself − suppose we want to replace hard-disks with SSD − it should not have any impact on the logical data or schemas.
The ER model defines the conceptual view of a database. It works around real-world entities and the associations among them. At view level, the ER model is considered a good option for designing databases.
An entity can be a real-world object, either animate or inanimate, that can be easily identifiable. For example, in a school database, students, teachers, classes, and courses offered can be considered as entities. All these entities have some attributes or properties that give them their identity.
An entity set is a collection of similar types of entities. An entity set may contain entities with attribute sharing similar values. For example, a Students set may contain all the students of a school; likewise a Teachers set may contain all the teachers of a school from all faculties. Entity sets need not be disjoint.
Entities are represented by means of their properties, called attributes. All attributes have values. For example, a student entity may have name, class, and age as attributes.
There exists a domain or range of values that can be assigned to attributes. For example, a student's name cannot be a numeric value. It has to be alphabetic. A student's age cannot be negative, etc.
Simple attribute − Simple attributes are atomic values, which cannot be divided further. For example, a student's phone number is an atomic value of 10 digits.
Simple attribute − Simple attributes are atomic values, which cannot be divided further. For example, a student's phone number is an atomic value of 10 digits.
Composite attribute − Composite attributes are made of more than one simple attribute. For example, a student's complete name may have first_name and last_name.
Composite attribute − Composite attributes are made of more than one simple attribute. For example, a student's complete name may have first_name and last_name.
Derived attribute − Derived attributes are the attributes that do not exist in the physical database, but their values are derived from other attributes present in the database. For example, average_salary in a department should not be saved directly in the database, instead it can be derived. For another example, age can be derived from data_of_birth.
Derived attribute − Derived attributes are the attributes that do not exist in the physical database, but their values are derived from other attributes present in the database. For example, average_salary in a department should not be saved directly in the database, instead it can be derived. For another example, age can be derived from data_of_birth.
Single-value attribute − Single-value attributes contain single value. For example − Social_Security_Number.
Single-value attribute − Single-value attributes contain single value. For example − Social_Security_Number.
Multi-value attribute − Multi-value attributes may contain more than one values. For example, a person can have more than one phone number, email_address, etc.
Multi-value attribute − Multi-value attributes may contain more than one values. For example, a person can have more than one phone number, email_address, etc.
These attribute types can come together in a way like −
simple single-valued attributes
simple multi-valued attributes
composite single-valued attributes
composite multi-valued attributes
Key is an attribute or collection of attributes that uniquely identifies an entity among entity set.
For example, the roll_number of a student makes him/her identifiable among students.
Super Key − A set of attributes (one or more) that collectively identifies an entity in an entity set.
Super Key − A set of attributes (one or more) that collectively identifies an entity in an entity set.
Candidate Key − A minimal super key is called a candidate key. An entity set may have more than one candidate key.
Candidate Key − A minimal super key is called a candidate key. An entity set may have more than one candidate key.
Primary Key − A primary key is one of the candidate keys chosen by the database designer to uniquely identify the entity set.
Primary Key − A primary key is one of the candidate keys chosen by the database designer to uniquely identify the entity set.
The association among entities is called a relationship. For example, an employee works_at a department, a student enrolls in a course. Here, Works_at and Enrolls are called relationships.
A set of relationships of similar type is called a relationship set. Like entities, a relationship too can have attributes. These attributes are called descriptive attributes.
The number of participating entities in a relationship defines the degree of the relationship.
Binary = degree 2
Ternary = degree 3
n-ary = degree
Cardinality defines the number of entities in one entity set, which can be associated with the number of entities of other set via relationship set.
One-to-one − One entity from entity set A can be associated with at most one entity of entity set B and vice versa.
One-to-one − One entity from entity set A can be associated with at most one entity of entity set B and vice versa.
One-to-many − One entity from entity set A can be associated with more than one entities of entity set B however an entity from entity set B, can be associated with at most one entity.
One-to-many − One entity from entity set A can be associated with more than one entities of entity set B however an entity from entity set B, can be associated with at most one entity.
Many-to-one − More than one entities from entity set A can be associated with at most one entity of entity set B, however an entity from entity set B can be associated with more than one entity from entity set A.
Many-to-one − More than one entities from entity set A can be associated with at most one entity of entity set B, however an entity from entity set B can be associated with more than one entity from entity set A.
Many-to-many − One entity from A can be associated with more than one entity from B and vice versa.
Many-to-many − One entity from A can be associated with more than one entity from B and vice versa.
Let us now learn how the ER Model is represented by means of an ER diagram. Any object, for example, entities, attributes of an entity, relationship sets, and attributes of relationship sets, can be represented with the help of an ER diagram.
Entities are represented by means of rectangles. Rectangles are named with the entity set they represent.
Attributes are the properties of entities. Attributes are represented by means of ellipses. Every ellipse represents one attribute and is directly connected to its entity (rectangle).
If the attributes are composite, they are further divided in a tree like structure. Every node is then connected to its attribute. That is, composite attributes are represented by ellipses that are connected with an ellipse.
Multivalued attributes are depicted by double ellipse.
Derived attributes are depicted by dashed ellipse.
Relationships are represented by diamond-shaped box. Name of the relationship is written inside the diamond-box. All the entities (rectangles) participating in a relationship, are connected to it by a line.
A relationship where two entities are participating is called a binary relationship. Cardinality is the number of instance of an entity from a relation that can be associated with the relation.
One-to-one − When only one instance of an entity is associated with the relationship, it is marked as '1:1'. The following image reflects that only one instance of each entity should be associated with the relationship. It depicts one-to-one relationship.
One-to-one − When only one instance of an entity is associated with the relationship, it is marked as '1:1'. The following image reflects that only one instance of each entity should be associated with the relationship. It depicts one-to-one relationship.
One-to-many − When more than one instance of an entity is associated with a relationship, it is marked as '1:N'. The following image reflects that only one instance of entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts one-to-many relationship.
One-to-many − When more than one instance of an entity is associated with a relationship, it is marked as '1:N'. The following image reflects that only one instance of entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts one-to-many relationship.
Many-to-one − When more than one instance of entity is associated with the relationship, it is marked as 'N:1'. The following image reflects that more than one instance of an entity on the left and only one instance of an entity on the right can be associated with the relationship. It depicts many-to-one relationship.
Many-to-one − When more than one instance of entity is associated with the relationship, it is marked as 'N:1'. The following image reflects that more than one instance of an entity on the left and only one instance of an entity on the right can be associated with the relationship. It depicts many-to-one relationship.
Many-to-many − The following image reflects that more than one instance of an entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts many-to-many relationship.
Many-to-many − The following image reflects that more than one instance of an entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts many-to-many relationship.
Total Participation − Each entity is involved in the relationship. Total participation is represented by double lines.
Total Participation − Each entity is involved in the relationship. Total participation is represented by double lines.
Partial participation − Not all entities are involved in the relationship. Partial participation is represented by single lines.
Partial participation − Not all entities are involved in the relationship. Partial participation is represented by single lines.
Let us now learn how the ER Model is represented by means of an ER diagram. Any object, for example, entities, attributes of an entity, relationship sets, and attributes of relationship sets, can be represented with the help of an ER diagram.
Entities are represented by means of rectangles. Rectangles are named with the entity set they represent.
Attributes are the properties of entities. Attributes are represented by means of ellipses. Every ellipse represents one attribute and is directly connected to its entity (rectangle).
If the attributes are composite, they are further divided in a tree like structure. Every node is then connected to its attribute. That is, composite attributes are represented by ellipses that are connected with an ellipse.
Multivalued attributes are depicted by double ellipse.
Derived attributes are depicted by dashed ellipse.
Relationships are represented by diamond-shaped box. Name of the relationship is written inside the diamond-box. All the entities (rectangles) participating in a relationship, are connected to it by a line.
A relationship where two entities are participating is called a binary relationship. Cardinality is the number of instance of an entity from a relation that can be associated with the relation.
One-to-one − When only one instance of an entity is associated with the relationship, it is marked as '1:1'. The following image reflects that only one instance of each entity should be associated with the relationship. It depicts one-to-one relationship.
One-to-one − When only one instance of an entity is associated with the relationship, it is marked as '1:1'. The following image reflects that only one instance of each entity should be associated with the relationship. It depicts one-to-one relationship.
One-to-many − When more than one instance of an entity is associated with a relationship, it is marked as '1:N'. The following image reflects that only one instance of entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts one-to-many relationship.
One-to-many − When more than one instance of an entity is associated with a relationship, it is marked as '1:N'. The following image reflects that only one instance of entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts one-to-many relationship.
Many-to-one − When more than one instance of entity is associated with the relationship, it is marked as 'N:1'. The following image reflects that more than one instance of an entity on the left and only one instance of an entity on the right can be associated with the relationship. It depicts many-to-one relationship.
Many-to-one − When more than one instance of entity is associated with the relationship, it is marked as 'N:1'. The following image reflects that more than one instance of an entity on the left and only one instance of an entity on the right can be associated with the relationship. It depicts many-to-one relationship.
Many-to-many − The following image reflects that more than one instance of an entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts many-to-many relationship.
Many-to-many − The following image reflects that more than one instance of an entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts many-to-many relationship.
Total Participation − Each entity is involved in the relationship. Total participation is represented by double lines.
Total Participation − Each entity is involved in the relationship. Total participation is represented by double lines.
Partial participation − Not all entities are involved in the relationship. Partial participation is represented by single lines.
Partial participation − Not all entities are involved in the relationship. Partial participation is represented by single lines.
The ER Model has the power of expressing database entities in a conceptual hierarchical manner. As the hierarchy goes up, it generalizes the view of entities, and as we go deep in the hierarchy, it gives us the detail of every entity included.
Going up in this structure is called generalization, where entities are clubbed together to represent a more generalized view. For example, a particular student named Mira can be generalized along with all the students. The entity shall be a student, and further, the student is a person. The reverse is called specialization where a person is a student, and that student is Mira.
As mentioned above, the process of generalizing entities, where the generalized entities contain the properties of all the generalized entities, is called generalization. In generalization, a number of entities are brought together into one generalized entity based on their similar characteristics. For example, pigeon, house sparrow, crow and dove can all be generalized as Birds.
Specialization is the opposite of generalization. In specialization, a group of entities is divided into sub-groups based on their characteristics. Take a group ‘Person’ for example. A person has name, date of birth, gender, etc. These properties are common in all persons, human beings. But in a company, persons can be identified as employee, employer, customer, or vendor, based on what role they play in the company.
Similarly, in a school database, persons can be specialized as teacher, student, or a staff, based on what role they play in school as entities.
We use all the above features of ER-Model in order to create classes of objects in object-oriented programming. The details of entities are generally hidden from the user; this process known as abstraction.
Inheritance is an important feature of Generalization and Specialization. It allows lower-level entities to inherit the attributes of higher-level entities.
For example, the attributes of a Person class such as name, age, and gender can be inherited by lower-level entities such as Student or Teacher.
Dr Edgar F. Codd, after his extensive research on the Relational Model of database systems, came up with twelve rules of his own, which according to him, a database must obey in order to be regarded as a true relational database.
These rules can be applied on any database system that manages stored data using only its relational capabilities. This is a foundation rule, which acts as a base for all the other rules.
The data stored in a database, may it be user data or metadata, must be a value of some table cell. Everything in a database must be stored in a table format.
Every single data element (value) is guaranteed to be accessible logically with a combination of table-name, primary-key (row value), and attribute-name (column value). No other means, such as pointers, can be used to access data.
The NULL values in a database must be given a systematic and uniform treatment. This is a very important rule because a NULL can be interpreted as one the following − data is missing, data is not known, or data is not applicable.
The structure description of the entire database must be stored in an online catalog, known as data dictionary, which can be accessed by authorized users. Users can use the same query language to access the catalog which they use to access the database itself.
A database can only be accessed using a language having linear syntax that supports data definition, data manipulation, and transaction management operations. This language can be used directly or by means of some application. If the database allows access to data without any help of this language, then it is considered as a violation.
All the views of a database, which can theoretically be updated, must also be updatable by the system.
A database must support high-level insertion, updation, and deletion. This must not be limited to a single row, that is, it must also support union, intersection and minus operations to yield sets of data records.
The data stored in a database must be independent of the applications that access the database. Any change in the physical structure of a database must not have any impact on how the data is being accessed by external applications.
The logical data in a database must be independent of its user’s view (application). Any change in logical data must not affect the applications using it. For example, if two tables are merged or one is split into two different tables, there should be no impact or change on the user application. This is one of the most difficult rule to apply.
A database must be independent of the application that uses it. All its integrity constraints can be independently modified without the need of any change in the application. This rule makes a database independent of the front-end application and its interface.
The end-user must not be able to see that the data is distributed over various locations. Users should always get the impression that the data is located at one site only. This rule has been regarded as the foundation of distributed database systems.
If a system has an interface that provides access to low-level records, then the interface must not be able to subvert the system and bypass security and integrity constraints.
Relational data model is the primary data model, which is used widely around the world for data storage and processing. This model is simple and it has all the properties and capabilities required to process data with storage efficiency.
Tables − In relational data model, relations are saved in the format of Tables. This format stores the relation among entities. A table has rows and columns, where rows represents records and columns represent the attributes.
Tuple − A single row of a table, which contains a single record for that relation is called a tuple.
Relation instance − A finite set of tuples in the relational database system represents relation instance. Relation instances do not have duplicate tuples.
Relation schema − A relation schema describes the relation name (table name), attributes, and their names.
Relation key − Each row has one or more attributes, known as relation key, which can identify the row in the relation (table) uniquely.
Attribute domain − Every attribute has some pre-defined value scope, known as attribute domain.
Every relation has some conditions that must hold for it to be a valid relation. These conditions are called Relational Integrity Constraints. There are three main integrity constraints −
Key constraints
Domain constraints
Referential integrity constraints
There must be at least one minimal subset of attributes in the relation, which can identify a tuple uniquely. This minimal subset of attributes is called key for that relation. If there are more than one such minimal subsets, these are called candidate keys.
Key constraints force that −
in a relation with a key attribute, no two tuples can have identical values for key attributes.
in a relation with a key attribute, no two tuples can have identical values for key attributes.
a key attribute can not have NULL values.
a key attribute can not have NULL values.
Key constraints are also referred to as Entity Constraints.
Attributes have specific values in real-world scenario. For example, age can only be a positive integer. The same constraints have been tried to employ on the attributes of a relation. Every attribute is bound to have a specific range of values. For example, age cannot be less than zero and telephone numbers cannot contain a digit outside 0-9.
Referential integrity constraints work on the concept of Foreign Keys. A foreign key is a key attribute of a relation that can be referred in other relation.
Referential integrity constraint states that if a relation refers to a key attribute of a different or same relation, then that key element must exist.
Relational database systems are expected to be equipped with a query language that can assist its users to query the database instances. There are two kinds of query languages − relational algebra and relational calculus.
Relational algebra is a procedural query language, which takes instances of relations as input and yields instances of relations as output. It uses operators to perform queries. An operator can be either unary or binary. They accept relations as their input and yield relations as their output. Relational algebra is performed recursively on a relation and intermediate results are also considered relations.
The fundamental operations of relational algebra are as follows −
Select
Project
Union
Set different
Cartesian product
Rename
We will discuss all these operations in the following sections.
It selects tuples that satisfy the given predicate from a relation.
Notation − σp(r)
Where σ stands for selection predicate and r stands for relation. p is prepositional logic formula which may use connectors like and, or, and not. These terms may use relational operators like − =, ≠, ≥, < , >, ≤.
For example −
σsubject="database"(Books)
σsubject="database"(Books)
Output − Selects tuples from books where subject is 'database'.
σsubject="database" and price="450"(Books)
σsubject="database" and price="450"(Books)
Output − Selects tuples from books where subject is 'database' and 'price' is 450.
σsubject="database" and price < "450" or year > "2010"(Books)
σsubject="database" and price < "450" or year > "2010"(Books)
Output − Selects tuples from books where subject is 'database' and 'price' is 450 or those books published after 2010.
It projects column(s) that satisfy a given predicate.
Notation − ∏A1, A2, An (r)
Where A1, A2 , An are attribute names of relation r.
Duplicate rows are automatically eliminated, as relation is a set.
For example −
∏subject, author (Books)
∏subject, author (Books)
Selects and projects columns named as subject and author from the relation Books.
It performs binary union between two given relations and is defined as −
r ∪ s = { t | t ∈ r or t ∈ s}
r ∪ s = { t | t ∈ r or t ∈ s}
Notation − r U s
Where r and s are either database relations or relation result set (temporary relation).
For a union operation to be valid, the following conditions must hold −
r, and s must have the same number of attributes.
Attribute domains must be compatible.
Duplicate tuples are automatically eliminated.
∏ author (Books) ∪ ∏ author (Articles)
∏ author (Books) ∪ ∏ author (Articles)
Output − Projects the names of the authors who have either written a book or an article or both.
The result of set difference operation is tuples, which are present in one relation but are not in the second relation.
Notation − r − s
Finds all the tuples that are present in r but not in s.
∏ author (Books) − ∏ author (Articles)
∏ author (Books) − ∏ author (Articles)
Output − Provides the name of authors who have written books but not articles.
Combines information of two different relations into one.
Notation − r Χ s
Where r and s are relations and their output will be defined as −
r Χ s = { q t | q ∈ r and t ∈ s}
∏ author = 'tutorialspoint'(Books Χ Articles)
∏ author = 'tutorialspoint'(Books Χ Articles)
Output − Yields a relation, which shows all the books and articles written by tutorialspoint.
The results of relational algebra are also relations but without any name. The rename operation allows us to rename the output relation. 'rename' operation is denoted with small Greek letter rho ρ.
Notation − ρ x (E)
Where the result of expression E is saved with name of x.
Additional operations are −
Set intersection
Assignment
Natural join
In contrast to Relational Algebra, Relational Calculus is a non-procedural query language, that is, it tells what to do but never explains how to do it.
Relational calculus exists in two forms −
Filtering variable ranges over tuples
Notation − {T | Condition}
Returns all tuples T that satisfies a condition.
For example −
{ T.name | Author(T) AND T.article = 'database' }
Output − Returns tuples with 'name' from Author who has written article on 'database'.
TRC can be quantified. We can use Existential (∃) and Universal Quantifiers (∀).
For example −
{ R| ∃T ∈ Authors(T.article='database' AND R.name=T.name)}
Output − The above query will yield the same result as the previous one.
In DRC, the filtering variable uses the domain of attributes instead of entire tuple values (as done in TRC, mentioned above).
Notation −
{ a1, a2, a3, ..., an | P (a1, a2, a3, ... ,an)}
Where a1, a2 are attributes and P stands for formulae built by inner attributes.
For example −
{< article, page, subject > | ∈ TutorialsPoint ∧ subject = 'database'}
{< article, page, subject > | ∈ TutorialsPoint ∧ subject = 'database'}
Output − Yields Article, Page, and Subject from the relation TutorialsPoint, where subject is database.
Just like TRC, DRC can also be written using existential and universal quantifiers. DRC also involves relational operators.
The expression power of Tuple Relation Calculus and Domain Relation Calculus is equivalent to Relational Algebra.
ER Model, when conceptualized into diagrams, gives a good overview of entity-relationship, which is easier to understand. ER diagrams can be mapped to relational schema, that is, it is possible to create relational schema using ER diagram. We cannot import all the ER constraints into relational model, but an approximate schema can be generated.
There are several processes and algorithms available to convert ER Diagrams into Relational Schema. Some of them are automated and some of them are manual. We may focus here on the mapping diagram contents to relational basics.
ER diagrams mainly comprise of −
Entity and its attributes
Relationship, which is association among entities.
An entity is a real-world object with some attributes.
Create table for each entity.
Entity's attributes should become fields of tables with their respective data types.
Declare primary key.
A relationship is an association among entities.
Create table for a relationship.
Add the primary keys of all participating Entities as fields of table with their respective data types.
If relationship has any attribute, add each attribute as field of table.
Declare a primary key composing all the primary keys of participating entities.
Declare all foreign key constraints.
A weak entity set is one which does not have any primary key associated with it.
Create table for weak entity set.
Add all its attributes to table as field.
Add the primary key of identifying entity set.
Declare all foreign key constraints.
ER specialization or generalization comes in the form of hierarchical entity sets.
Create tables for all higher-level entities.
Create tables for all higher-level entities.
Create tables for lower-level entities.
Create tables for lower-level entities.
Add primary keys of higher-level entities in the table of lower-level entities.
Add primary keys of higher-level entities in the table of lower-level entities.
In lower-level tables, add all other attributes of lower-level entities.
In lower-level tables, add all other attributes of lower-level entities.
Declare primary key of higher-level table and the primary key for lower-level table.
Declare primary key of higher-level table and the primary key for lower-level table.
Declare foreign key constraints.
Declare foreign key constraints.
SQL is a programming language for Relational Databases. It is designed over relational algebra and tuple relational calculus. SQL comes as a package with all major distributions of RDBMS.
SQL comprises both data definition and data manipulation languages. Using the data definition properties of SQL, one can design and modify database schema, whereas data manipulation properties allows SQL to store and retrieve data from database.
SQL uses the following set of commands to define database schema −
Creates new databases, tables and views from RDBMS.
For example −
Create database tutorialspoint;
Create table article;
Create view for_students;
Drops commands, views, tables, and databases from RDBMS.
For example−
Drop object_type object_name;
Drop database tutorialspoint;
Drop table article;
Drop view for_students;
Modifies database schema.
Alter object_type object_name parameters;
For example−
Alter table article add subject varchar;
This command adds an attribute in the relation article with the name subject of string type.
SQL is equipped with data manipulation language (DML). DML modifies the database instance by inserting, updating and deleting its data. DML is responsible for all forms data modification in a database. SQL contains the following set of commands in its DML section −
SELECT/FROM/WHERE
INSERT INTO/VALUES
UPDATE/SET/WHERE
DELETE FROM/WHERE
These basic constructs allow database programmers and users to enter data and information into the database and retrieve efficiently using a number of filter options.
SELECT − This is one of the fundamental query command of SQL. It is similar to the projection operation of relational algebra. It selects the attributes based on the condition described by WHERE clause.
SELECT − This is one of the fundamental query command of SQL. It is similar to the projection operation of relational algebra. It selects the attributes based on the condition described by WHERE clause.
FROM − This clause takes a relation name as an argument from which attributes are to be selected/projected. In case more than one relation names are given, this clause corresponds to Cartesian product.
FROM − This clause takes a relation name as an argument from which attributes are to be selected/projected. In case more than one relation names are given, this clause corresponds to Cartesian product.
WHERE − This clause defines predicate or conditions, which must match in order to qualify the attributes to be projected.
WHERE − This clause defines predicate or conditions, which must match in order to qualify the attributes to be projected.
For example −
Select author_name
From book_author
Where age > 50;
This command will yield the names of authors from the relation book_author whose age is greater than 50.
This command is used for inserting values into the rows of a table (relation).
Syntax−
INSERT INTO table (column1 [, column2, column3 ... ]) VALUES (value1 [, value2, value3 ... ])
Or
INSERT INTO table VALUES (value1, [value2, ... ])
For example −
INSERT INTO tutorialspoint (Author, Subject) VALUES ("anonymous", "computers");
This command is used for updating or modifying the values of columns in a table (relation).
Syntax −
UPDATE table_name SET column_name = value [, column_name = value ...] [WHERE condition]
For example −
UPDATE tutorialspoint SET Author="webmaster" WHERE Author="anonymous";
This command is used for removing one or more rows from a table (relation).
Syntax −
DELETE FROM table_name [WHERE condition];
For example −
DELETE FROM tutorialspoints
WHERE Author="unknown";
Functional dependency (FD) is a set of constraints between two attributes in a relation. Functional dependency says that if two tuples have same values for attributes A1, A2,..., An, then those two tuples must have to have same values for attributes B1, B2, ..., Bn.
Functional dependency is represented by an arrow sign (→) that is, X→Y, where X functionally determines Y. The left-hand side attributes determine the values of attributes on the right-hand side.
If F is a set of functional dependencies then the closure of F, denoted as F+, is the set of all functional dependencies logically implied by F. Armstrong's Axioms are a set of rules, that when applied repeatedly, generates a closure of functional dependencies.
Reflexive rule − If alpha is a set of attributes and beta is_subset_of alpha, then alpha holds beta.
Reflexive rule − If alpha is a set of attributes and beta is_subset_of alpha, then alpha holds beta.
Augmentation rule − If a → b holds and y is attribute set, then ay → by also holds. That is adding attributes in dependencies, does not change the basic dependencies.
Augmentation rule − If a → b holds and y is attribute set, then ay → by also holds. That is adding attributes in dependencies, does not change the basic dependencies.
Transitivity rule − Same as transitive rule in algebra, if a → b holds and b → c holds, then a → c also holds. a → b is called as a functionally that determines b.
Transitivity rule − Same as transitive rule in algebra, if a → b holds and b → c holds, then a → c also holds. a → b is called as a functionally that determines b.
Trivial − If a functional dependency (FD) X → Y holds, where Y is a subset of X, then it is called a trivial FD. Trivial FDs always hold.
Trivial − If a functional dependency (FD) X → Y holds, where Y is a subset of X, then it is called a trivial FD. Trivial FDs always hold.
Non-trivial − If an FD X → Y holds, where Y is not a subset of X, then it is called a non-trivial FD.
Non-trivial − If an FD X → Y holds, where Y is not a subset of X, then it is called a non-trivial FD.
Completely non-trivial − If an FD X → Y holds, where x intersect Y = Φ, it is said to be a completely non-trivial FD.
Completely non-trivial − If an FD X → Y holds, where x intersect Y = Φ, it is said to be a completely non-trivial FD.
If a database design is not perfect, it may contain anomalies, which are like a bad dream for any database administrator. Managing a database with anomalies is next to impossible.
Update anomalies − If data items are scattered and are not linked to each other properly, then it could lead to strange situations. For example, when we try to update one data item having its copies scattered over several places, a few instances get updated properly while a few others are left with old values. Such instances leave the database in an inconsistent state.
Update anomalies − If data items are scattered and are not linked to each other properly, then it could lead to strange situations. For example, when we try to update one data item having its copies scattered over several places, a few instances get updated properly while a few others are left with old values. Such instances leave the database in an inconsistent state.
Deletion anomalies − We tried to delete a record, but parts of it was left undeleted because of unawareness, the data is also saved somewhere else.
Deletion anomalies − We tried to delete a record, but parts of it was left undeleted because of unawareness, the data is also saved somewhere else.
Insert anomalies − We tried to insert data in a record that does not exist at all.
Insert anomalies − We tried to insert data in a record that does not exist at all.
Normalization is a method to remove all these anomalies and bring the database to a consistent state.
First Normal Form is defined in the definition of relations (tables) itself. This rule defines that all the attributes in a relation must have atomic domains. The values in an atomic domain are indivisible units.
We re-arrange the relation (table) as below, to convert it to First Normal Form.
Each attribute must contain only a single value from its pre-defined domain.
Before we learn about the second normal form, we need to understand the following −
Prime attribute − An attribute, which is a part of the candidate-key, is known as a prime attribute.
Prime attribute − An attribute, which is a part of the candidate-key, is known as a prime attribute.
Non-prime attribute − An attribute, which is not a part of the prime-key, is said to be a non-prime attribute.
Non-prime attribute − An attribute, which is not a part of the prime-key, is said to be a non-prime attribute.
If we follow second normal form, then every non-prime attribute should be fully functionally dependent on prime key attribute. That is, if X → A holds, then there should not be any proper subset Y of X, for which Y → A also holds true.
We see here in Student_Project relation that the prime key attributes are Stu_ID and Proj_ID. According to the rule, non-key attributes, i.e. Stu_Name and Proj_Name must be dependent upon both and not on any of the prime key attribute individually. But we find that Stu_Name can be identified by Stu_ID and Proj_Name can be identified by Proj_ID independently. This is called partial dependency, which is not allowed in Second Normal Form.
We broke the relation in two as depicted in the above picture. So there exists no partial dependency.
For a relation to be in Third Normal Form, it must be in Second Normal form and the following must satisfy −
No non-prime attribute is transitively dependent on prime key attribute.
For any non-trivial functional dependency, X → A, then either −
X is a superkey or,
A is prime attribute.
A is prime attribute.
We find that in the above Student_detail relation, Stu_ID is the key and only prime key attribute. We find that City can be identified by Stu_ID as well as Zip itself. Neither Zip is a superkey nor is City a prime attribute. Additionally, Stu_ID → Zip → City, so there exists transitive dependency.
To bring this relation into third normal form, we break the relation into two relations as follows −
Boyce-Codd Normal Form (BCNF) is an extension of Third Normal Form on strict terms. BCNF states that −
For any non-trivial functional dependency, X → A, X must be a super-key.
In the above image, Stu_ID is the super-key in the relation Student_Detail and Zip is the super-key in the relation ZipCodes. So,
Stu_ID → Stu_Name, Zip
and
Zip → City
Which confirms that both the relations are in BCNF.
We understand the benefits of taking a Cartesian product of two relations, which gives us all the possible tuples that are paired together. But it might not be feasible for us in certain cases to take a Cartesian product where we encounter huge relations with thousands of tuples having a considerable large number of attributes.
Join is a combination of a Cartesian product followed by a selection process. A Join operation pairs two tuples from different relations, if and only if a given join condition is satisfied.
We will briefly describe various join types in the following sections.
Theta join combines tuples from different relations provided they satisfy the theta condition. The join condition is denoted by the symbol θ.
R1 ⋈θ R2
R1 and R2 are relations having attributes (A1, A2, .., An) and (B1, B2,.. ,Bn) such that the attributes don’t have anything in common, that is R1 ∩ R2 = Φ.
Theta join can use all kinds of comparison operators.
Student_Detail =
STUDENT ⋈Student.Std = Subject.Class SUBJECT
When Theta join uses only equality comparison operator, it is said to be equijoin. The above example corresponds to equijoin.
Natural join does not use any comparison operator. It does not concatenate the way a Cartesian product does. We can perform a Natural Join only if there is at least one common attribute that exists between two relations. In addition, the attributes must have the same name and domain.
Natural join acts on those matching attributes where the values of attributes in both the relations are same.
Theta Join, Equijoin, and Natural Join are called inner joins. An inner join includes only those tuples with matching attributes and the rest are discarded in the resulting relation. Therefore, we need to use outer joins to include all the tuples from the participating relations in the resulting relation. There are three kinds of outer joins − left outer join, right outer join, and full outer join.
All the tuples from the Left relation, R, are included in the resulting relation. If there are tuples in R without any matching tuple in the Right relation S, then the S-attributes of the resulting relation are made NULL.
All the tuples from the Right relation, S, are included in the resulting relation. If there are tuples in S without any matching tuple in R, then the R-attributes of resulting relation are made NULL.
All the tuples from both participating relations are included in the resulting relation. If there are no matching tuples for both relations, their respective unmatched attributes are made NULL.
Databases are stored in file formats, which contain records. At physical level, the actual data is stored in electromagnetic format on some device. These storage devices can be broadly categorized into three types −
Primary Storage − The memory storage that is directly accessible to the CPU comes under this category. CPU's internal memory (registers), fast memory (cache), and main memory (RAM) are directly accessible to the CPU, as they are all placed on the motherboard or CPU chipset. This storage is typically very small, ultra-fast, and volatile. Primary storage requires continuous power supply in order to maintain its state. In case of a power failure, all its data is lost.
Primary Storage − The memory storage that is directly accessible to the CPU comes under this category. CPU's internal memory (registers), fast memory (cache), and main memory (RAM) are directly accessible to the CPU, as they are all placed on the motherboard or CPU chipset. This storage is typically very small, ultra-fast, and volatile. Primary storage requires continuous power supply in order to maintain its state. In case of a power failure, all its data is lost.
Secondary Storage − Secondary storage devices are used to store data for future use or as backup. Secondary storage includes memory devices that are not a part of the CPU chipset or motherboard, for example, magnetic disks, optical disks (DVD, CD, etc.), hard disks, flash drives, and magnetic tapes.
Secondary Storage − Secondary storage devices are used to store data for future use or as backup. Secondary storage includes memory devices that are not a part of the CPU chipset or motherboard, for example, magnetic disks, optical disks (DVD, CD, etc.), hard disks, flash drives, and magnetic tapes.
Tertiary Storage − Tertiary storage is used to store huge volumes of data. Since such storage devices are external to the computer system, they are the slowest in speed. These storage devices are mostly used to take the back up of an entire system. Optical disks and magnetic tapes are widely used as tertiary storage.
Tertiary Storage − Tertiary storage is used to store huge volumes of data. Since such storage devices are external to the computer system, they are the slowest in speed. These storage devices are mostly used to take the back up of an entire system. Optical disks and magnetic tapes are widely used as tertiary storage.
A computer system has a well-defined hierarchy of memory. A CPU has direct access to it main memory as well as its inbuilt registers. The access time of the main memory is obviously less than the CPU speed. To minimize this speed mismatch, cache memory is introduced. Cache memory provides the fastest access time and it contains data that is most frequently accessed by the CPU.
The memory with the fastest access is the costliest one. Larger storage devices offer slow speed and they are less expensive, however they can store huge volumes of data as compared to CPU registers or cache memory.
Hard disk drives are the most common secondary storage devices in present computer systems. These are called magnetic disks because they use the concept of magnetization to store information. Hard disks consist of metal disks coated with magnetizable material. These disks are placed vertically on a spindle. A read/write head moves in between the disks and is used to magnetize or de-magnetize the spot under it. A magnetized spot can be recognized as 0 (zero) or 1 (one).
Hard disks are formatted in a well-defined order to store data efficiently. A hard disk plate has many concentric circles on it, called tracks. Every track is further divided into sectors. A sector on a hard disk typically stores 512 bytes of data.
RAID stands for Redundant Array of Independent Disks, which is a technology to connect multiple secondary storage devices and use them as a single storage media.
RAID consists of an array of disks in which multiple disks are connected together to achieve different goals. RAID levels define the use of disk arrays.
RAID 0 − In this level, a striped array of disks is implemented. The data is broken down into blocks and the blocks are distributed among disks. Each disk receives a block of data to write/read in parallel. It enhances the speed and performance of the storage device. There is no parity and backup in Level 0.
RAID 0 − In this level, a striped array of disks is implemented. The data is broken down into blocks and the blocks are distributed among disks. Each disk receives a block of data to write/read in parallel. It enhances the speed and performance of the storage device. There is no parity and backup in Level 0.
RAID 1 − RAID 1 uses mirroring techniques. When data is sent to a RAID controller, it sends a copy of data to all the disks in the array. RAID level 1 is also called mirroring and provides 100% redundancy in case of a failure.
RAID 1 − RAID 1 uses mirroring techniques. When data is sent to a RAID controller, it sends a copy of data to all the disks in the array. RAID level 1 is also called mirroring and provides 100% redundancy in case of a failure.
RAID 2 − RAID 2 records Error Correction Code using Hamming distance for its data, striped on different disks. Like level 0, each data bit in a word is recorded on a separate disk and ECC codes of the data words are stored on a different set disks. Due to its complex structure and high cost, RAID 2 is not commercially available.
RAID 2 − RAID 2 records Error Correction Code using Hamming distance for its data, striped on different disks. Like level 0, each data bit in a word is recorded on a separate disk and ECC codes of the data words are stored on a different set disks. Due to its complex structure and high cost, RAID 2 is not commercially available.
RAID 3 − RAID 3 stripes the data onto multiple disks. The parity bit generated for data word is stored on a different disk. This technique makes it to overcome single disk failures.
RAID 3 − RAID 3 stripes the data onto multiple disks. The parity bit generated for data word is stored on a different disk. This technique makes it to overcome single disk failures.
RAID 4 − In this level, an entire block of data is written onto data disks and then the parity is generated and stored on a different disk. Note that level 3 uses byte-level striping, whereas level 4 uses block-level striping. Both level 3 and level 4 require at least three disks to implement RAID.
RAID 4 − In this level, an entire block of data is written onto data disks and then the parity is generated and stored on a different disk. Note that level 3 uses byte-level striping, whereas level 4 uses block-level striping. Both level 3 and level 4 require at least three disks to implement RAID.
RAID 5 − RAID 5 writes whole data blocks onto different disks, but the parity bits generated for data block stripe are distributed among all the data disks rather than storing them on a different dedicated disk.
RAID 5 − RAID 5 writes whole data blocks onto different disks, but the parity bits generated for data block stripe are distributed among all the data disks rather than storing them on a different dedicated disk.
RAID 6 − RAID 6 is an extension of level 5. In this level, two independent parities are generated and stored in distributed fashion among multiple disks. Two parities provide additional fault tolerance. This level requires at least four disk drives to implement RAID.
RAID 6 − RAID 6 is an extension of level 5. In this level, two independent parities are generated and stored in distributed fashion among multiple disks. Two parities provide additional fault tolerance. This level requires at least four disk drives to implement RAID.
Relative data and information is stored collectively in file formats. A file is a sequence of records stored in binary format. A disk drive is formatted into several blocks that can store records. File records are mapped onto those disk blocks.
File Organization defines how file records are mapped onto disk blocks. We have four types of File Organization to organize file records −
When a file is created using Heap File Organization, the Operating System allocates memory area to that file without any further accounting details. File records can be placed anywhere in that memory area. It is the responsibility of the software to manage the records. Heap File does not support any ordering, sequencing, or indexing on its own.
Every file record contains a data field (attribute) to uniquely identify that record. In sequential file organization, records are placed in the file in some sequential order based on the unique key field or search key. Practically, it is not possible to store all the records sequentially in physical form.
Hash File Organization uses Hash function computation on some fields of the records. The output of the hash function determines the location of disk block where the records are to be placed.
Clustered file organization is not considered good for large databases. In this mechanism, related records from one or more relations are kept in the same disk block, that is, the ordering of records is not based on primary key or search key.
Operations on database files can be broadly classified into two categories −
Update Operations
Update Operations
Retrieval Operations
Retrieval Operations
Update operations change the data values by insertion, deletion, or update. Retrieval operations, on the other hand, do not alter the data but retrieve them after optional conditional filtering. In both types of operations, selection plays a significant role. Other than creation and deletion of a file, there could be several operations, which can be done on files.
Open − A file can be opened in one of the two modes, read mode or write mode. In read mode, the operating system does not allow anyone to alter data. In other words, data is read only. Files opened in read mode can be shared among several entities. Write mode allows data modification. Files opened in write mode can be read but cannot be shared.
Open − A file can be opened in one of the two modes, read mode or write mode. In read mode, the operating system does not allow anyone to alter data. In other words, data is read only. Files opened in read mode can be shared among several entities. Write mode allows data modification. Files opened in write mode can be read but cannot be shared.
Locate − Every file has a file pointer, which tells the current position where the data is to be read or written. This pointer can be adjusted accordingly. Using find (seek) operation, it can be moved forward or backward.
Locate − Every file has a file pointer, which tells the current position where the data is to be read or written. This pointer can be adjusted accordingly. Using find (seek) operation, it can be moved forward or backward.
Read − By default, when files are opened in read mode, the file pointer points to the beginning of the file. There are options where the user can tell the operating system where to locate the file pointer at the time of opening a file. The very next data to the file pointer is read.
Read − By default, when files are opened in read mode, the file pointer points to the beginning of the file. There are options where the user can tell the operating system where to locate the file pointer at the time of opening a file. The very next data to the file pointer is read.
Write − User can select to open a file in write mode, which enables them to edit its contents. It can be deletion, insertion, or modification. The file pointer can be located at the time of opening or can be dynamically changed if the operating system allows to do so.
Write − User can select to open a file in write mode, which enables them to edit its contents. It can be deletion, insertion, or modification. The file pointer can be located at the time of opening or can be dynamically changed if the operating system allows to do so.
Close − This is the most important operation from the operating system’s point of view. When a request to close a file is generated, the operating system
removes all the locks (if in shared mode),
saves the data (if altered) to the secondary storage media, and
releases all the buffers and file handlers associated with the file.
Close − This is the most important operation from the operating system’s point of view. When a request to close a file is generated, the operating system
removes all the locks (if in shared mode),
saves the data (if altered) to the secondary storage media, and
releases all the buffers and file handlers associated with the file.
The organization of data inside a file plays a major role here. The process to locate the file pointer to a desired record inside a file various based on whether the records are arranged sequentially or clustered.
We know that data is stored in the form of records. Every record has a key field, which helps it to be recognized uniquely.
Indexing is a data structure technique to efficiently retrieve records from the database files based on some attributes on which the indexing has been done. Indexing in database systems is similar to what we see in books.
Indexing is defined based on its indexing attributes. Indexing can be of the following types −
Primary Index − Primary index is defined on an ordered data file. The data file is ordered on a key field. The key field is generally the primary key of the relation.
Primary Index − Primary index is defined on an ordered data file. The data file is ordered on a key field. The key field is generally the primary key of the relation.
Secondary Index − Secondary index may be generated from a field which is a candidate key and has a unique value in every record, or a non-key with duplicate values.
Secondary Index − Secondary index may be generated from a field which is a candidate key and has a unique value in every record, or a non-key with duplicate values.
Clustering Index − Clustering index is defined on an ordered data file. The data file is ordered on a non-key field.
Clustering Index − Clustering index is defined on an ordered data file. The data file is ordered on a non-key field.
Ordered Indexing is of two types −
Dense Index
Sparse Index
In dense index, there is an index record for every search key value in the database. This makes searching faster but requires more space to store index records itself. Index records contain search key value and a pointer to the actual record on the disk.
In sparse index, index records are not created for every search key. An index record here contains a search key and an actual pointer to the data on the disk. To search a record, we first proceed by index record and reach at the actual location of the data. If the data we are looking for is not where we directly reach by following the index, then the system starts sequential search until the desired data is found.
Index records comprise search-key values and data pointers. Multilevel index is stored on the disk along with the actual database files. As the size of the database grows, so does the size of the indices. There is an immense need to keep the index records in the main memory so as to speed up the search operations. If single-level index is used, then a large size index cannot be kept in memory which leads to multiple disk accesses.
Multi-level Index helps in breaking down the index into several smaller indices in order to make the outermost level so small that it can be saved in a single disk block, which can easily be accommodated anywhere in the main memory.
A B+ tree is a balanced binary search tree that follows a multi-level index format. The leaf nodes of a B+ tree denote actual data pointers. B+ tree ensures that all leaf nodes remain at the same height, thus balanced. Additionally, the leaf nodes are linked using a link list; therefore, a B+ tree can support random access as well as sequential access.
Every leaf node is at equal distance from the root node. A B+ tree is of the order n where n is fixed for every B+ tree.
Internal nodes −
Internal (non-leaf) nodes contain at least ⌈n/2⌉ pointers, except the root node.
At most, an internal node can contain n pointers.
Leaf nodes −
Leaf nodes contain at least ⌈n/2⌉ record pointers and ⌈n/2⌉ key values.
At most, a leaf node can contain n record pointers and n key values.
Every leaf node contains one block pointer P to point to next leaf node and forms a linked list.
B+ trees are filled from bottom and each entry is done at the leaf node.
B+ trees are filled from bottom and each entry is done at the leaf node.
If a leaf node overflows −
Split node into two parts.
Partition at i = ⌊(m+1)/2⌋.
First i entries are stored in one node.
Rest of the entries (i+1 onwards) are moved to a new node.
ith key is duplicated at the parent of the leaf.
Split node into two parts.
Split node into two parts.
Partition at i = ⌊(m+1)/2⌋.
Partition at i = ⌊(m+1)/2⌋.
First i entries are stored in one node.
First i entries are stored in one node.
Rest of the entries (i+1 onwards) are moved to a new node.
Rest of the entries (i+1 onwards) are moved to a new node.
ith key is duplicated at the parent of the leaf.
ith key is duplicated at the parent of the leaf.
If a non-leaf node overflows −
Split node into two parts.
Partition the node at i = ⌈(m+1)/2⌉.
Entries up to i are kept in one node.
Rest of the entries are moved to a new node.
If a non-leaf node overflows −
Split node into two parts.
Split node into two parts.
Partition the node at i = ⌈(m+1)/2⌉.
Partition the node at i = ⌈(m+1)/2⌉.
Entries up to i are kept in one node.
Entries up to i are kept in one node.
Rest of the entries are moved to a new node.
Rest of the entries are moved to a new node.
B+ tree entries are deleted at the leaf nodes.
B+ tree entries are deleted at the leaf nodes.
The target entry is searched and deleted.
If it is an internal node, delete and replace with the entry from the left position.
The target entry is searched and deleted.
If it is an internal node, delete and replace with the entry from the left position.
If it is an internal node, delete and replace with the entry from the left position.
After deletion, underflow is tested,
If underflow occurs, distribute the entries from the nodes left to it.
After deletion, underflow is tested,
If underflow occurs, distribute the entries from the nodes left to it.
If underflow occurs, distribute the entries from the nodes left to it.
If distribution is not possible from left, then
Distribute from the nodes right to it.
If distribution is not possible from left, then
Distribute from the nodes right to it.
Distribute from the nodes right to it.
If distribution is not possible from left or from right, then
Merge the node with left and right to it.
If distribution is not possible from left or from right, then
Merge the node with left and right to it.
Merge the node with left and right to it.
For a huge database structure, it can be almost next to impossible to search all the index values through all its level and then reach the destination data block to retrieve the desired data. Hashing is an effective technique to calculate the direct location of a data record on the disk without using index structure.
Hashing uses hash functions with search keys as parameters to generate the address of a data record.
Bucket − A hash file stores data in bucket format. Bucket is considered a unit of storage. A bucket typically stores one complete disk block, which in turn can store one or more records.
Bucket − A hash file stores data in bucket format. Bucket is considered a unit of storage. A bucket typically stores one complete disk block, which in turn can store one or more records.
Hash Function − A hash function, h, is a mapping function that maps all the set of search-keys K to the address where actual records are placed. It is a function from search keys to bucket addresses.
Hash Function − A hash function, h, is a mapping function that maps all the set of search-keys K to the address where actual records are placed. It is a function from search keys to bucket addresses.
In static hashing, when a search-key value is provided, the hash function always computes the same address. For example, if mod-4 hash function is used, then it shall generate only 5 values. The output address shall always be same for that function. The number of buckets provided remains unchanged at all times.
Insertion − When a record is required to be entered using static hash, the hash function h computes the bucket address for search key K, where the record will be stored.
Bucket address = h(K)
Insertion − When a record is required to be entered using static hash, the hash function h computes the bucket address for search key K, where the record will be stored.
Bucket address = h(K)
Search − When a record needs to be retrieved, the same hash function can be used to retrieve the address of the bucket where the data is stored.
Search − When a record needs to be retrieved, the same hash function can be used to retrieve the address of the bucket where the data is stored.
Delete − This is simply a search followed by a deletion operation.
Delete − This is simply a search followed by a deletion operation.
The condition of bucket-overflow is known as collision. This is a fatal state for any static hash function. In this case, overflow chaining can be used.
Overflow Chaining − When buckets are full, a new bucket is allocated for the same hash result and is linked after the previous one. This mechanism is called Closed Hashing.
Overflow Chaining − When buckets are full, a new bucket is allocated for the same hash result and is linked after the previous one. This mechanism is called Closed Hashing.
Linear Probing − When a hash function generates an address at which data is already stored, the next free bucket is allocated to it. This mechanism is called Open Hashing.
Linear Probing − When a hash function generates an address at which data is already stored, the next free bucket is allocated to it. This mechanism is called Open Hashing.
The problem with static hashing is that it does not expand or shrink dynamically as the size of the database grows or shrinks. Dynamic hashing provides a mechanism in which data buckets are added and removed dynamically and on-demand. Dynamic hashing is also known as extended hashing.
Hash function, in dynamic hashing, is made to produce a large number of values and only a few are used initially.
The prefix of an entire hash value is taken as a hash index. Only a portion of the hash value is used for computing bucket addresses. Every hash index has a depth value to signify how many bits are used for computing a hash function. These bits can address 2n buckets. When all these bits are consumed − that is, when all the buckets are full − then the depth value is increased linearly and twice the buckets are allocated.
Querying − Look at the depth value of the hash index and use those bits to compute the bucket address.
Querying − Look at the depth value of the hash index and use those bits to compute the bucket address.
Update − Perform a query as above and update the data.
Update − Perform a query as above and update the data.
Deletion − Perform a query to locate the desired data and delete the same.
Deletion − Perform a query to locate the desired data and delete the same.
Insertion − Compute the address of the bucket
If the bucket is already full.
Add more buckets.
Add additional bits to the hash value.
Re-compute the hash function.
Else
Add data to the bucket,
If all the buckets are full, perform the remedies of static hashing.
Insertion − Compute the address of the bucket
If the bucket is already full.
Add more buckets.
Add additional bits to the hash value.
Re-compute the hash function.
Add more buckets.
Add additional bits to the hash value.
Re-compute the hash function.
Else
Add data to the bucket,
Add data to the bucket,
If all the buckets are full, perform the remedies of static hashing.
Hashing is not favorable when the data is organized in some ordering and the queries require a range of data. When data is discrete and random, hash performs the best.
Hashing algorithms have high complexity than indexing. All hash operations are done in constant time.
A transaction can be defined as a group of tasks. A single task is the minimum processing unit which cannot be divided further.
Let’s take an example of a simple transaction. Suppose a bank employee transfers Rs 500 from A's account to B's account. This very simple and small transaction involves several low-level tasks.
A’s Account
Open_Account(A)
Old_Balance = A.balance
New_Balance = Old_Balance - 500
A.balance = New_Balance
Close_Account(A)
B’s Account
Open_Account(B)
Old_Balance = B.balance
New_Balance = Old_Balance + 500
B.balance = New_Balance
Close_Account(B)
A transaction is a very small unit of a program and it may contain several lowlevel tasks. A transaction in a database system must maintain Atomicity, Consistency, Isolation, and Durability − commonly known as ACID properties − in order to ensure accuracy, completeness, and data integrity.
Atomicity − This property states that a transaction must be treated as an atomic unit, that is, either all of its operations are executed or none. There must be no state in a database where a transaction is left partially completed. States should be defined either before the execution of the transaction or after the execution/abortion/failure of the transaction.
Atomicity − This property states that a transaction must be treated as an atomic unit, that is, either all of its operations are executed or none. There must be no state in a database where a transaction is left partially completed. States should be defined either before the execution of the transaction or after the execution/abortion/failure of the transaction.
Consistency − The database must remain in a consistent state after any transaction. No transaction should have any adverse effect on the data residing in the database. If the database was in a consistent state before the execution of a transaction, it must remain consistent after the execution of the transaction as well.
Consistency − The database must remain in a consistent state after any transaction. No transaction should have any adverse effect on the data residing in the database. If the database was in a consistent state before the execution of a transaction, it must remain consistent after the execution of the transaction as well.
Durability − The database should be durable enough to hold all its latest updates even if the system fails or restarts. If a transaction updates a chunk of data in a database and commits, then the database will hold the modified data. If a transaction commits but the system fails before the data could be written on to the disk, then that data will be updated once the system springs back into action.
Durability − The database should be durable enough to hold all its latest updates even if the system fails or restarts. If a transaction updates a chunk of data in a database and commits, then the database will hold the modified data. If a transaction commits but the system fails before the data could be written on to the disk, then that data will be updated once the system springs back into action.
Isolation − In a database system where more than one transaction are being executed simultaneously and in parallel, the property of isolation states that all the transactions will be carried out and executed as if it is the only transaction in the system. No transaction will affect the existence of any other transaction.
Isolation − In a database system where more than one transaction are being executed simultaneously and in parallel, the property of isolation states that all the transactions will be carried out and executed as if it is the only transaction in the system. No transaction will affect the existence of any other transaction.
When multiple transactions are being executed by the operating system in a multiprogramming environment, there are possibilities that instructions of one transactions are interleaved with some other transaction.
Schedule − A chronological execution sequence of a transaction is called a schedule. A schedule can have many transactions in it, each comprising of a number of instructions/tasks.
Schedule − A chronological execution sequence of a transaction is called a schedule. A schedule can have many transactions in it, each comprising of a number of instructions/tasks.
Serial Schedule − It is a schedule in which transactions are aligned in such a way that one transaction is executed first. When the first transaction completes its cycle, then the next transaction is executed. Transactions are ordered one after the other. This type of schedule is called a serial schedule, as transactions are executed in a serial manner.
Serial Schedule − It is a schedule in which transactions are aligned in such a way that one transaction is executed first. When the first transaction completes its cycle, then the next transaction is executed. Transactions are ordered one after the other. This type of schedule is called a serial schedule, as transactions are executed in a serial manner.
In a multi-transaction environment, serial schedules are considered as a benchmark. The execution sequence of an instruction in a transaction cannot be changed, but two transactions can have their instructions executed in a random fashion. This execution does no harm if two transactions are mutually independent and working on different segments of data; but in case these two transactions are working on the same data, then the results may vary. This ever-varying result may bring the database to an inconsistent state.
To resolve this problem, we allow parallel execution of a transaction schedule, if its transactions are either serializable or have some equivalence relation among them.
An equivalence schedule can be of the following types −
If two schedules produce the same result after execution, they are said to be result equivalent. They may yield the same result for some value and different results for another set of values. That's why this equivalence is not generally considered significant.
Two schedules would be view equivalence if the transactions in both the schedules perform similar actions in a similar manner.
For example −
If T reads the initial data in S1, then it also reads the initial data in S2.
If T reads the initial data in S1, then it also reads the initial data in S2.
If T reads the value written by J in S1, then it also reads the value written by J in S2.
If T reads the value written by J in S1, then it also reads the value written by J in S2.
If T performs the final write on the data value in S1, then it also performs the final write on the data value in S2.
If T performs the final write on the data value in S1, then it also performs the final write on the data value in S2.
Two schedules would be conflicting if they have the following properties −
Both belong to separate transactions.
Both accesses the same data item.
At least one of them is "write" operation.
Two schedules having multiple transactions with conflicting operations are said to be conflict equivalent if and only if −
Both the schedules contain the same set of Transactions.
The order of conflicting pairs of operation is maintained in both the schedules.
Note − View equivalent schedules are view serializable and conflict equivalent schedules are conflict serializable. All conflict serializable schedules are view serializable too.
A transaction in a database can be in one of the following states −
Active − In this state, the transaction is being executed. This is the initial state of every transaction.
Active − In this state, the transaction is being executed. This is the initial state of every transaction.
Partially Committed − When a transaction executes its final operation, it is said to be in a partially committed state.
Partially Committed − When a transaction executes its final operation, it is said to be in a partially committed state.
Failed − A transaction is said to be in a failed state if any of the checks made by the database recovery system fails. A failed transaction can no longer proceed further.
Failed − A transaction is said to be in a failed state if any of the checks made by the database recovery system fails. A failed transaction can no longer proceed further.
Aborted − If any of the checks fails and the transaction has reached a failed state, then the recovery manager rolls back all its write operations on the database to bring the database back to its original state where it was prior to the execution of the transaction. Transactions in this state are called aborted. The database recovery module can select one of the two operations after a transaction aborts −
Re-start the transaction
Kill the transaction
Aborted − If any of the checks fails and the transaction has reached a failed state, then the recovery manager rolls back all its write operations on the database to bring the database back to its original state where it was prior to the execution of the transaction. Transactions in this state are called aborted. The database recovery module can select one of the two operations after a transaction aborts −
Re-start the transaction
Kill the transaction
Committed − If a transaction executes all its operations successfully, it is said to be committed. All its effects are now permanently established on the database system.
Committed − If a transaction executes all its operations successfully, it is said to be committed. All its effects are now permanently established on the database system.
In a multiprogramming environment where multiple transactions can be executed simultaneously, it is highly important to control the concurrency of transactions. We have concurrency control protocols to ensure atomicity, isolation, and serializability of concurrent transactions. Concurrency control protocols can be broadly divided into two categories −
Lock based protocols
Time stamp based protocols
Database systems equipped with lock-based protocols use a mechanism by which any transaction cannot read or write data until it acquires an appropriate lock on it. Locks are of two kinds −
Binary Locks − A lock on a data item can be in two states; it is either locked or unlocked.
Binary Locks − A lock on a data item can be in two states; it is either locked or unlocked.
Shared/exclusive − This type of locking mechanism differentiates the locks based on their uses. If a lock is acquired on a data item to perform a write operation, it is an exclusive lock. Allowing more than one transaction to write on the same data item would lead the database into an inconsistent state. Read locks are shared because no data value is being changed.
Shared/exclusive − This type of locking mechanism differentiates the locks based on their uses. If a lock is acquired on a data item to perform a write operation, it is an exclusive lock. Allowing more than one transaction to write on the same data item would lead the database into an inconsistent state. Read locks are shared because no data value is being changed.
There are four types of lock protocols available −
Simplistic lock-based protocols allow transactions to obtain a lock on every object before a 'write' operation is performed. Transactions may unlock the data item after completing the ‘write’ operation.
Pre-claiming protocols evaluate their operations and create a list of data items on which they need locks. Before initiating an execution, the transaction requests the system for all the locks it needs beforehand. If all the locks are granted, the transaction executes and releases all the locks when all its operations are over. If all the locks are not granted, the transaction rolls back and waits until all the locks are granted.
This locking protocol divides the execution phase of a transaction into three parts. In the first part, when the transaction starts executing, it seeks permission for the locks it requires. The second part is where the transaction acquires all the locks. As soon as the transaction releases its first lock, the third phase starts. In this phase, the transaction cannot demand any new locks; it only releases the acquired locks.
Two-phase locking has two phases, one is growing, where all the locks are being acquired by the transaction; and the second phase is shrinking, where the locks held by the transaction are being released.
To claim an exclusive (write) lock, a transaction must first acquire a shared (read) lock and then upgrade it to an exclusive lock.
The first phase of Strict-2PL is same as 2PL. After acquiring all the locks in the first phase, the transaction continues to execute normally. But in contrast to 2PL, Strict-2PL does not release a lock after using it. Strict-2PL holds all the locks until the commit point and releases all the locks at a time.
Strict-2PL does not have cascading abort as 2PL does.
The most commonly used concurrency protocol is the timestamp based protocol. This protocol uses either system time or logical counter as a timestamp.
Lock-based protocols manage the order between the conflicting pairs among transactions at the time of execution, whereas timestamp-based protocols start working as soon as a transaction is created.
Every transaction has a timestamp associated with it, and the ordering is determined by the age of the transaction. A transaction created at 0002 clock time would be older than all other transactions that come after it. For example, any transaction 'y' entering the system at 0004 is two seconds younger and the priority would be given to the older one.
In addition, every data item is given the latest read and write-timestamp. This lets the system know when the last ‘read and write’ operation was performed on the data item.
The timestamp-ordering protocol ensures serializability among transactions in their conflicting read and write operations. This is the responsibility of the protocol system that the conflicting pair of tasks should be executed according to the timestamp values of the transactions.
The timestamp of transaction Ti is denoted as TS(Ti).
Read time-stamp of data-item X is denoted by R-timestamp(X).
Write time-stamp of data-item X is denoted by W-timestamp(X).
Timestamp ordering protocol works as follows −
If a transaction Ti issues a read(X) operation −
If a transaction Ti issues a read(X) operation −
If TS(Ti) < W-timestamp(X)
Operation rejected.
Operation rejected.
If TS(Ti) >= W-timestamp(X)
Operation executed.
Operation executed.
All data-item timestamps updated.
If a transaction Ti issues a write(X) operation −
If a transaction Ti issues a write(X) operation −
If TS(Ti) < R-timestamp(X)
Operation rejected.
If TS(Ti) < W-timestamp(X)
Operation rejected and Ti rolled back.
Otherwise, operation executed.
This rule states if TS(Ti) < W-timestamp(X), then the operation is rejected and Ti is rolled back.
Time-stamp ordering rules can be modified to make the schedule view serializable.
Instead of making Ti rolled back, the 'write' operation itself is ignored.
In a multi-process system, deadlock is an unwanted situation that arises in a shared resource environment, where a process indefinitely waits for a resource that is held by another process.
For example, assume a set of transactions {T0, T1, T2, ...,Tn}. T0 needs a resource X to complete its task. Resource X is held by T1, and T1 is waiting for a resource Y, which is held by T2. T2 is waiting for resource Z, which is held by T0. Thus, all the processes wait for each other to release resources. In this situation, none of the processes can finish their task. This situation is known as a deadlock.
Deadlocks are not healthy for a system. In case a system is stuck in a deadlock, the transactions involved in the deadlock are either rolled back or restarted.
To prevent any deadlock situation in the system, the DBMS aggressively inspects all the operations, where transactions are about to execute. The DBMS inspects the operations and analyzes if they can create a deadlock situation. If it finds that a deadlock situation might occur, then that transaction is never allowed to be executed.
There are deadlock prevention schemes that use timestamp ordering mechanism of transactions in order to predetermine a deadlock situation.
In this scheme, if a transaction requests to lock a resource (data item), which is already held with a conflicting lock by another transaction, then one of the two possibilities may occur −
If TS(Ti) < TS(Tj) − that is Ti, which is requesting a conflicting lock, is older than Tj − then Ti is allowed to wait until the data-item is available.
If TS(Ti) < TS(Tj) − that is Ti, which is requesting a conflicting lock, is older than Tj − then Ti is allowed to wait until the data-item is available.
If TS(Ti) > TS(tj) − that is Ti is younger than Tj − then Ti dies. Ti is restarted later with a random delay but with the same timestamp.
If TS(Ti) > TS(tj) − that is Ti is younger than Tj − then Ti dies. Ti is restarted later with a random delay but with the same timestamp.
This scheme allows the older transaction to wait but kills the younger one.
In this scheme, if a transaction requests to lock a resource (data item), which is already held with conflicting lock by some another transaction, one of the two possibilities may occur −
If TS(Ti) < TS(Tj), then Ti forces Tj to be rolled back − that is Ti wounds Tj. Tj is restarted later with a random delay but with the same timestamp.
If TS(Ti) < TS(Tj), then Ti forces Tj to be rolled back − that is Ti wounds Tj. Tj is restarted later with a random delay but with the same timestamp.
If TS(Ti) > TS(Tj), then Ti is forced to wait until the resource is available.
If TS(Ti) > TS(Tj), then Ti is forced to wait until the resource is available.
This scheme, allows the younger transaction to wait; but when an older transaction requests an item held by a younger one, the older transaction forces the younger one to abort and release the item.
In both the cases, the transaction that enters the system at a later stage is aborted.
Aborting a transaction is not always a practical approach. Instead, deadlock avoidance mechanisms can be used to detect any deadlock situation in advance. Methods like "wait-for graph" are available but they are suitable for only those systems where transactions are lightweight having fewer instances of resource. In a bulky system, deadlock prevention techniques may work well.
This is a simple method available to track if any deadlock situation may arise. For each transaction entering into the system, a node is created. When a transaction Ti requests for a lock on an item, say X, which is held by some other transaction Tj, a directed edge is created from Ti to Tj. If Tj releases item X, the edge between them is dropped and Ti locks the data item.
The system maintains this wait-for graph for every transaction waiting for some data items held by others. The system keeps checking if there's any cycle in the graph.
Here, we can use any of the two following approaches −
First, do not allow any request for an item, which is already locked by another transaction. This is not always feasible and may cause starvation, where a transaction indefinitely waits for a data item and can never acquire it.
First, do not allow any request for an item, which is already locked by another transaction. This is not always feasible and may cause starvation, where a transaction indefinitely waits for a data item and can never acquire it.
The second option is to roll back one of the transactions. It is not always feasible to roll back the younger transaction, as it may be important than the older one. With the help of some relative algorithm, a transaction is chosen, which is to be aborted. This transaction is known as the victim and the process is known as victim selection.
The second option is to roll back one of the transactions. It is not always feasible to roll back the younger transaction, as it may be important than the older one. With the help of some relative algorithm, a transaction is chosen, which is to be aborted. This transaction is known as the victim and the process is known as victim selection.
A volatile storage like RAM stores all the active logs, disk buffers, and related data. In addition, it stores all the transactions that are being currently executed. What happens if such a volatile storage crashes abruptly? It would obviously take away all the logs and active copies of the database. It makes recovery almost impossible, as everything that is required to recover the data is lost.
Following techniques may be adopted in case of loss of volatile storage −
We can have checkpoints at multiple stages so as to save the contents of the database periodically.
We can have checkpoints at multiple stages so as to save the contents of the database periodically.
A state of active database in the volatile memory can be periodically dumped onto a stable storage, which may also contain logs and active transactions and buffer blocks.
A state of active database in the volatile memory can be periodically dumped onto a stable storage, which may also contain logs and active transactions and buffer blocks.
<dump> can be marked on a log file, whenever the database contents are dumped from a non-volatile memory to a stable one.
<dump> can be marked on a log file, whenever the database contents are dumped from a non-volatile memory to a stable one.
When the system recovers from a failure, it can restore the latest dump.
When the system recovers from a failure, it can restore the latest dump.
It can maintain a redo-list and an undo-list as checkpoints.
It can maintain a redo-list and an undo-list as checkpoints.
It can recover the system by consulting undo-redo lists to restore the state of all transactions up to the last checkpoint.
It can recover the system by consulting undo-redo lists to restore the state of all transactions up to the last checkpoint.
A catastrophic failure is one where a stable, secondary storage device gets corrupt. With the storage device, all the valuable data that is stored inside is lost. We have two different strategies to recover data from such a catastrophic failure −
Remote backup &minu; Here a backup copy of the database is stored at a remote location from where it can be restored in case of a catastrophe.
Remote backup &minu; Here a backup copy of the database is stored at a remote location from where it can be restored in case of a catastrophe.
Alternatively, database backups can be taken on magnetic tapes and stored at a safer place. This backup can later be transferred onto a freshly installed database to bring it to the point of backup.
Alternatively, database backups can be taken on magnetic tapes and stored at a safer place. This backup can later be transferred onto a freshly installed database to bring it to the point of backup.
Grown-up databases are too bulky to be frequently backed up. In such cases, we have techniques where we can restore a database just by looking at its logs. So, all that we need to do here is to take a backup of all the logs at frequent intervals of time. The database can be backed up once a week, and the logs being very small can be backed up every day or as frequently as possible.
Remote backup provides a sense of security in case the primary location where the database is located gets destroyed. Remote backup can be offline or real-time or online. In case it is offline, it is maintained manually.
Online backup systems are more real-time and lifesavers for database administrators and investors. An online backup system is a mechanism where every bit of the real-time data is backed up simultaneously at two distant places. One of them is directly connected to the system and the other one is kept at a remote place as backup.
As soon as the primary database storage fails, the backup system senses the failure and switches the user system to the remote storage. Sometimes this is so instant that the users can’t even realize a failure.
DBMS is a highly complex system with hundreds of transactions being executed every second. The durability and robustness of a DBMS depends on its complex architecture and its underlying hardware and system software. If it fails or crashes amid transactions, it is expected that the system would follow some sort of algorithm or techniques to recover lost data.
To see where the problem has occurred, we generalize a failure into various categories, as follows −
A transaction has to abort when it fails to execute or when it reaches a point from where it can’t go any further. This is called transaction failure where only a few transactions or processes are hurt.
Reasons for a transaction failure could be −
Logical errors − Where a transaction cannot complete because it has some code error or any internal error condition.
Logical errors − Where a transaction cannot complete because it has some code error or any internal error condition.
System errors − Where the database system itself terminates an active transaction because the DBMS is not able to execute it, or it has to stop because of some system condition. For example, in case of deadlock or resource unavailability, the system aborts an active transaction.
System errors − Where the database system itself terminates an active transaction because the DBMS is not able to execute it, or it has to stop because of some system condition. For example, in case of deadlock or resource unavailability, the system aborts an active transaction.
There are problems − external to the system − that may cause the system to stop abruptly and cause the system to crash. For example, interruptions in power supply may cause the failure of underlying hardware or software failure.
Examples may include operating system errors.
In early days of technology evolution, it was a common problem where hard-disk drives or storage drives used to fail frequently.
Disk failures include formation of bad sectors, unreachability to the disk, disk head crash or any other failure, which destroys all or a part of disk storage.
We have already described the storage system. In brief, the storage structure can be divided into two categories −
Volatile storage − As the name suggests, a volatile storage cannot survive system crashes. Volatile storage devices are placed very close to the CPU; normally they are embedded onto the chipset itself. For example, main memory and cache memory are examples of volatile storage. They are fast but can store only a small amount of information.
Volatile storage − As the name suggests, a volatile storage cannot survive system crashes. Volatile storage devices are placed very close to the CPU; normally they are embedded onto the chipset itself. For example, main memory and cache memory are examples of volatile storage. They are fast but can store only a small amount of information.
Non-volatile storage − These memories are made to survive system crashes. They are huge in data storage capacity, but slower in accessibility. Examples may include hard-disks, magnetic tapes, flash memory, and non-volatile (battery backed up) RAM.
Non-volatile storage − These memories are made to survive system crashes. They are huge in data storage capacity, but slower in accessibility. Examples may include hard-disks, magnetic tapes, flash memory, and non-volatile (battery backed up) RAM.
When a system crashes, it may have several transactions being executed and various files opened for them to modify the data items. Transactions are made of various operations, which are atomic in nature. But according to ACID properties of DBMS, atomicity of transactions as a whole must be maintained, that is, either all the operations are executed or none.
When a DBMS recovers from a crash, it should maintain the following −
It should check the states of all the transactions, which were being executed.
It should check the states of all the transactions, which were being executed.
A transaction may be in the middle of some operation; the DBMS must ensure the atomicity of the transaction in this case.
A transaction may be in the middle of some operation; the DBMS must ensure the atomicity of the transaction in this case.
It should check whether the transaction can be completed now or it needs to be rolled back.
It should check whether the transaction can be completed now or it needs to be rolled back.
No transactions would be allowed to leave the DBMS in an inconsistent state.
No transactions would be allowed to leave the DBMS in an inconsistent state.
There are two types of techniques, which can help a DBMS in recovering as well as maintaining the atomicity of a transaction −
Maintaining the logs of each transaction, and writing them onto some stable storage before actually modifying the database.
Maintaining the logs of each transaction, and writing them onto some stable storage before actually modifying the database.
Maintaining shadow paging, where the changes are done on a volatile memory, and later, the actual database is updated.
Maintaining shadow paging, where the changes are done on a volatile memory, and later, the actual database is updated.
Log is a sequence of records, which maintains the records of actions performed by a transaction. It is important that the logs are written prior to the actual modification and stored on a stable storage media, which is failsafe.
Log-based recovery works as follows −
The log file is kept on a stable storage media.
The log file is kept on a stable storage media.
When a transaction enters the system and starts execution, it writes a log about it.
When a transaction enters the system and starts execution, it writes a log about it.
<Tn, Start>
When the transaction modifies an item X, it write logs as follows −
When the transaction modifies an item X, it write logs as follows −
<Tn, X, V1, V2>
It reads Tn has changed the value of X, from V1 to V2.
When the transaction finishes, it logs −
<Tn, commit>
The database can be modified using two approaches −
Deferred database modification − All logs are written on to the stable storage and the database is updated when a transaction commits.
Deferred database modification − All logs are written on to the stable storage and the database is updated when a transaction commits.
Immediate database modification − Each log follows an actual database modification. That is, the database is modified immediately after every operation.
Immediate database modification − Each log follows an actual database modification. That is, the database is modified immediately after every operation.
When more than one transaction are being executed in parallel, the logs are interleaved. At the time of recovery, it would become hard for the recovery system to backtrack all logs, and then start recovering. To ease this situation, most modern DBMS use the concept of 'checkpoints'.
Keeping and maintaining logs in real time and in real environment may fill out all the memory space available in the system. As time passes, the log file may grow too big to be handled at all. Checkpoint is a mechanism where all the previous logs are removed from the system and stored permanently in a storage disk. Checkpoint declares a point before which the DBMS was in consistent state, and all the transactions were committed.
When a system with concurrent transactions crashes and recovers, it behaves in the following manner −
The recovery system reads the logs backwards from the end to the last checkpoint.
The recovery system reads the logs backwards from the end to the last checkpoint.
It maintains two lists, an undo-list and a redo-list.
It maintains two lists, an undo-list and a redo-list.
If the recovery system sees a log with <Tn, Start> and <Tn, Commit> or just <Tn, Commit>, it puts the transaction in the redo-list.
If the recovery system sees a log with <Tn, Start> and <Tn, Commit> or just <Tn, Commit>, it puts the transaction in the redo-list.
If the recovery system sees a log with <Tn, Start> but no commit or abort log found, it puts the transaction in undo-list.
If the recovery system sees a log with <Tn, Start> but no commit or abort log found, it puts the transaction in undo-list.
All the transactions in the undo-list are then undone and their logs are removed. All the transactions in the redo-list and their previous logs are removed and then redone before saving their logs.
178 Lectures
14.5 hours
Arnab Chakraborty
194 Lectures
16 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2415,
"s": 2282,
"text": "Database is a collection of related data and data is a collection of facts and figures that can be processed to produce information."
},
{
"code": null,
"e": 2638,
"s": 2415,
"text": "Mostly data represents recordable facts. Data aids in producing information, which is based on facts. For example, if we have data about marks obtained by all students, we can then conclude about toppers and average marks."
},
{
"code": null,
"e": 2766,
"s": 2638,
"text": "A database management system stores data in such a way that it becomes easier to retrieve, manipulate, and produce information."
},
{
"code": null,
"e": 3004,
"s": 2766,
"text": "Traditionally, data was organized in file formats. DBMS was a new concept then, and all the research was done to make it overcome the deficiencies in traditional style of data management. A modern DBMS has the following characteristics −"
},
{
"code": null,
"e": 3246,
"s": 3004,
"text": "Real-world entity − A modern DBMS is more realistic and uses real-world entities to design its architecture. It uses the behavior and attributes too. For example, a school database may use students as an entity and their age as an attribute."
},
{
"code": null,
"e": 3488,
"s": 3246,
"text": "Real-world entity − A modern DBMS is more realistic and uses real-world entities to design its architecture. It uses the behavior and attributes too. For example, a school database may use students as an entity and their age as an attribute."
},
{
"code": null,
"e": 3663,
"s": 3488,
"text": "Relation-based tables − DBMS allows entities and relations among them to form tables. A user can understand the architecture of a database just by looking at the table names."
},
{
"code": null,
"e": 3838,
"s": 3663,
"text": "Relation-based tables − DBMS allows entities and relations among them to form tables. A user can understand the architecture of a database just by looking at the table names."
},
{
"code": null,
"e": 4118,
"s": 3838,
"text": "Isolation of data and application − A database system is entirely different than its data. A database is an active entity, whereas data is said to be passive, on which the database works and organizes. DBMS also stores metadata, which is data about data, to ease its own process."
},
{
"code": null,
"e": 4398,
"s": 4118,
"text": "Isolation of data and application − A database system is entirely different than its data. A database is an active entity, whereas data is said to be passive, on which the database works and organizes. DBMS also stores metadata, which is data about data, to ease its own process."
},
{
"code": null,
"e": 4632,
"s": 4398,
"text": "Less redundancy − DBMS follows the rules of normalization, which splits a relation when any of its attributes is having redundancy in values. Normalization is a mathematically rich and scientific process that reduces data redundancy."
},
{
"code": null,
"e": 4866,
"s": 4632,
"text": "Less redundancy − DBMS follows the rules of normalization, which splits a relation when any of its attributes is having redundancy in values. Normalization is a mathematically rich and scientific process that reduces data redundancy."
},
{
"code": null,
"e": 5189,
"s": 4866,
"text": "Consistency − Consistency is a state where every relation in a database remains consistent. There exist methods and techniques, which can detect attempt of leaving database in inconsistent state. A DBMS can provide greater consistency as compared to earlier forms of data storing applications like file-processing systems."
},
{
"code": null,
"e": 5512,
"s": 5189,
"text": "Consistency − Consistency is a state where every relation in a database remains consistent. There exist methods and techniques, which can detect attempt of leaving database in inconsistent state. A DBMS can provide greater consistency as compared to earlier forms of data storing applications like file-processing systems."
},
{
"code": null,
"e": 5802,
"s": 5512,
"text": "Query Language − DBMS is equipped with query language, which makes it more efficient to retrieve and manipulate data. A user can apply as many and as different filtering options as required to retrieve a set of data. Traditionally it was not possible where file-processing system was used."
},
{
"code": null,
"e": 6092,
"s": 5802,
"text": "Query Language − DBMS is equipped with query language, which makes it more efficient to retrieve and manipulate data. A user can apply as many and as different filtering options as required to retrieve a set of data. Traditionally it was not possible where file-processing system was used."
},
{
"code": null,
"e": 6407,
"s": 6092,
"text": "ACID Properties − DBMS follows the concepts of Atomicity, Consistency, Isolation, and Durability (normally shortened as ACID). These concepts are applied on transactions, which manipulate data in a database. ACID properties help the database stay healthy in multi-transactional environments and in case of failure."
},
{
"code": null,
"e": 6722,
"s": 6407,
"text": "ACID Properties − DBMS follows the concepts of Atomicity, Consistency, Isolation, and Durability (normally shortened as ACID). These concepts are applied on transactions, which manipulate data in a database. ACID properties help the database stay healthy in multi-transactional environments and in case of failure."
},
{
"code": null,
"e": 6985,
"s": 6722,
"text": "Multiuser and Concurrent Access − DBMS supports multi-user environment and allows them to access and manipulate data in parallel. Though there are restrictions on transactions when users attempt to handle the same data item, but users are always unaware of them."
},
{
"code": null,
"e": 7248,
"s": 6985,
"text": "Multiuser and Concurrent Access − DBMS supports multi-user environment and allows them to access and manipulate data in parallel. Though there are restrictions on transactions when users attempt to handle the same data item, but users are always unaware of them."
},
{
"code": null,
"e": 7549,
"s": 7248,
"text": "Multiple views − DBMS offers multiple views for different users. A user who is in the Sales department will have a different view of database than a person working in the Production department. This feature enables the users to have a concentrate view of the database according to their requirements."
},
{
"code": null,
"e": 7850,
"s": 7549,
"text": "Multiple views − DBMS offers multiple views for different users. A user who is in the Sales department will have a different view of database than a person working in the Production department. This feature enables the users to have a concentrate view of the database according to their requirements."
},
{
"code": null,
"e": 8576,
"s": 7850,
"text": "Security − Features like multiple views offer security to some extent where users are unable to access data of other users and departments. DBMS offers methods to impose constraints while entering data into the database and retrieving the same at a later stage. DBMS offers many different levels of security features, which enables multiple users to have different views with different features. For example, a user in the Sales department cannot see the data that belongs to the Purchase department. Additionally, it can also be managed how much data of the Sales department should be displayed to the user. Since a DBMS is not saved on the disk as traditional file systems, it is very hard for miscreants to break the code."
},
{
"code": null,
"e": 9302,
"s": 8576,
"text": "Security − Features like multiple views offer security to some extent where users are unable to access data of other users and departments. DBMS offers methods to impose constraints while entering data into the database and retrieving the same at a later stage. DBMS offers many different levels of security features, which enables multiple users to have different views with different features. For example, a user in the Sales department cannot see the data that belongs to the Purchase department. Additionally, it can also be managed how much data of the Sales department should be displayed to the user. Since a DBMS is not saved on the disk as traditional file systems, it is very hard for miscreants to break the code."
},
{
"code": null,
"e": 9506,
"s": 9302,
"text": "A typical DBMS has users with different rights and permissions who use it for different purposes. Some users retrieve data and some back it up. The users of a DBMS can be broadly categorized as follows −"
},
{
"code": null,
"e": 9923,
"s": 9506,
"text": "Administrators − Administrators maintain the DBMS and are responsible for administrating the database. They are responsible to look after its usage and by whom it should be used. They create access profiles for users and apply limitations to maintain isolation and force security. Administrators also look after DBMS resources like system license, required tools, and other software and hardware related maintenance."
},
{
"code": null,
"e": 10340,
"s": 9923,
"text": "Administrators − Administrators maintain the DBMS and are responsible for administrating the database. They are responsible to look after its usage and by whom it should be used. They create access profiles for users and apply limitations to maintain isolation and force security. Administrators also look after DBMS resources like system license, required tools, and other software and hardware related maintenance."
},
{
"code": null,
"e": 10602,
"s": 10340,
"text": "Designers − Designers are the group of people who actually work on the designing part of the database. They keep a close watch on what data should be kept and in what format. They identify and design the whole set of entities, relations, constraints, and views."
},
{
"code": null,
"e": 10864,
"s": 10602,
"text": "Designers − Designers are the group of people who actually work on the designing part of the database. They keep a close watch on what data should be kept and in what format. They identify and design the whole set of entities, relations, constraints, and views."
},
{
"code": null,
"e": 11081,
"s": 10864,
"text": "End Users − End users are those who actually reap the benefits of having a DBMS. End users can range from simple viewers who pay attention to the logs or market rates to sophisticated users such as business analysts."
},
{
"code": null,
"e": 11298,
"s": 11081,
"text": "End Users − End users are those who actually reap the benefits of having a DBMS. End users can range from simple viewers who pay attention to the logs or market rates to sophisticated users such as business analysts."
},
{
"code": null,
"e": 11636,
"s": 11298,
"text": "The design of a DBMS depends on its architecture. It can be centralized or decentralized or hierarchical. The architecture of a DBMS can be seen as either single tier or multi-tier. An n-tier architecture divides the whole system into related but independent n modules, which can be independently modified, altered, changed, or replaced."
},
{
"code": null,
"e": 11937,
"s": 11636,
"text": "In 1-tier architecture, the DBMS is the only entity where the user directly sits on the DBMS and uses it. Any changes done here will directly be done on the DBMS itself. It does not provide handy tools for end-users. Database designers and programmers normally prefer to use single-tier architecture."
},
{
"code": null,
"e": 12254,
"s": 11937,
"text": "If the architecture of DBMS is 2-tier, then it must have an application through which the DBMS can be accessed. Programmers use 2-tier architecture where they access the DBMS by means of an application. Here the application tier is entirely independent of the database in terms of operation, design, and programming."
},
{
"code": null,
"e": 12458,
"s": 12254,
"text": "A 3-tier architecture separates its tiers from each other based on the complexity of the users and how they use the data present in the database. It is the most widely used architecture to design a DBMS."
},
{
"code": null,
"e": 12644,
"s": 12458,
"text": "Database (Data) Tier − At this tier, the database resides along with its query processing languages. We also have the relations that define the data and their constraints at this level."
},
{
"code": null,
"e": 12830,
"s": 12644,
"text": "Database (Data) Tier − At this tier, the database resides along with its query processing languages. We also have the relations that define the data and their constraints at this level."
},
{
"code": null,
"e": 13308,
"s": 12830,
"text": "Application (Middle) Tier − At this tier reside the application server and the programs that access the database. For a user, this application tier presents an abstracted view of the database. End-users are unaware of any existence of the database beyond the application. At the other end, the database tier is not aware of any other user beyond the application tier. Hence, the application layer sits in the middle and acts as a mediator between the end-user and the database."
},
{
"code": null,
"e": 13786,
"s": 13308,
"text": "Application (Middle) Tier − At this tier reside the application server and the programs that access the database. For a user, this application tier presents an abstracted view of the database. End-users are unaware of any existence of the database beyond the application. At the other end, the database tier is not aware of any other user beyond the application tier. Hence, the application layer sits in the middle and acts as a mediator between the end-user and the database."
},
{
"code": null,
"e": 14080,
"s": 13786,
"text": "User (Presentation) Tier − End-users operate on this tier and they know nothing about any existence of the database beyond this layer. At this layer, multiple views of the database can be provided by the application. All views are generated by applications that reside in the application tier."
},
{
"code": null,
"e": 14374,
"s": 14080,
"text": "User (Presentation) Tier − End-users operate on this tier and they know nothing about any existence of the database beyond this layer. At this layer, multiple views of the database can be provided by the application. All views are generated by applications that reside in the application tier."
},
{
"code": null,
"e": 14511,
"s": 14374,
"text": "Multiple-tier database architecture is highly modifiable, as almost all its components are independent and can be changed independently."
},
{
"code": null,
"e": 14767,
"s": 14511,
"text": "Data models define how the logical structure of a database is modeled. Data Models are fundamental entities to introduce abstraction in a DBMS. Data models define how data is connected to each other and how they are processed and stored inside the system."
},
{
"code": null,
"e": 14999,
"s": 14767,
"text": "The very first data model could be flat data-models, where all the data used are to be kept in the same plane. Earlier data models were not so scientific, hence they were prone to introduce lots of duplication and update anomalies."
},
{
"code": null,
"e": 15256,
"s": 14999,
"text": "Entity-Relationship (ER) Model is based on the notion of real-world entities and relationships among them. While formulating real-world scenario into the database model, the ER Model creates entity set, relationship set, general attributes and constraints."
},
{
"code": null,
"e": 15319,
"s": 15256,
"text": "ER Model is best used for the conceptual design of a database."
},
{
"code": null,
"e": 15342,
"s": 15319,
"text": "ER Model is based on −"
},
{
"code": null,
"e": 15373,
"s": 15342,
"text": "Entities and their attributes."
},
{
"code": null,
"e": 15404,
"s": 15373,
"text": "Entities and their attributes."
},
{
"code": null,
"e": 15434,
"s": 15404,
"text": "Relationships among entities."
},
{
"code": null,
"e": 15464,
"s": 15434,
"text": "Relationships among entities."
},
{
"code": null,
"e": 15500,
"s": 15464,
"text": "These concepts are explained below."
},
{
"code": null,
"e": 15789,
"s": 15500,
"text": "Entity − An entity in an ER Model is a real-world entity having properties called attributes. Every attribute is defined by its set of values called domain. For example, in a school database, a student is considered as an entity. Student has various attributes like name, age, class, etc."
},
{
"code": null,
"e": 16078,
"s": 15789,
"text": "Entity − An entity in an ER Model is a real-world entity having properties called attributes. Every attribute is defined by its set of values called domain. For example, in a school database, a student is considered as an entity. Student has various attributes like name, age, class, etc."
},
{
"code": null,
"e": 16364,
"s": 16078,
"text": "Relationship − The logical association among entities is called relationship. Relationships are mapped with entities in various ways. Mapping cardinalities define the number of association between two entities.\nMapping cardinalities −\n\none to one\none to many\nmany to one\nmany to many\n\n"
},
{
"code": null,
"e": 16575,
"s": 16364,
"text": "Relationship − The logical association among entities is called relationship. Relationships are mapped with entities in various ways. Mapping cardinalities define the number of association between two entities."
},
{
"code": null,
"e": 16599,
"s": 16575,
"text": "Mapping cardinalities −"
},
{
"code": null,
"e": 16610,
"s": 16599,
"text": "one to one"
},
{
"code": null,
"e": 16622,
"s": 16610,
"text": "one to many"
},
{
"code": null,
"e": 16634,
"s": 16622,
"text": "many to one"
},
{
"code": null,
"e": 16647,
"s": 16634,
"text": "many to many"
},
{
"code": null,
"e": 16844,
"s": 16647,
"text": "The most popular data model in DBMS is the Relational Model. It is more scientific a model than others. This model is based on first-order predicate logic and defines a table as an n-ary relation."
},
{
"code": null,
"e": 16884,
"s": 16844,
"text": "The main highlights of this model are −"
},
{
"code": null,
"e": 16927,
"s": 16884,
"text": "Data is stored in tables called relations."
},
{
"code": null,
"e": 16956,
"s": 16927,
"text": "Relations can be normalized."
},
{
"code": null,
"e": 17013,
"s": 16956,
"text": "In normalized relations, values saved are atomic values."
},
{
"code": null,
"e": 17061,
"s": 17013,
"text": "Each row in a relation contains a unique value."
},
{
"code": null,
"e": 17123,
"s": 17061,
"text": "Each column in a relation contains values from a same domain."
},
{
"code": null,
"e": 17380,
"s": 17123,
"text": "A database schema is the skeleton structure that represents the logical view of the entire database. It defines how the data is organized and how the relations among them are associated. It formulates all the constraints that are to be applied on the data."
},
{
"code": null,
"e": 17667,
"s": 17380,
"text": "A database schema defines its entities and the relationship among them. It contains a descriptive detail of the database, which can be depicted by means of schema diagrams. It’s the database designers who design the schema to help programmers understand the database and make it useful."
},
{
"code": null,
"e": 17730,
"s": 17667,
"text": "A database schema can be divided broadly into two categories −"
},
{
"code": null,
"e": 17921,
"s": 17730,
"text": "Physical Database Schema − This schema pertains to the actual storage of data and its form of storage like files, indices, etc. It defines how the data will be stored in a secondary storage."
},
{
"code": null,
"e": 18112,
"s": 17921,
"text": "Physical Database Schema − This schema pertains to the actual storage of data and its form of storage like files, indices, etc. It defines how the data will be stored in a secondary storage."
},
{
"code": null,
"e": 18283,
"s": 18112,
"text": "Logical Database Schema − This schema defines all the logical constraints that need to be applied on the data stored. It defines tables, views, and integrity constraints."
},
{
"code": null,
"e": 18454,
"s": 18283,
"text": "Logical Database Schema − This schema defines all the logical constraints that need to be applied on the data stored. It defines tables, views, and integrity constraints."
},
{
"code": null,
"e": 18762,
"s": 18454,
"text": "It is important that we distinguish these two terms individually. Database schema is the skeleton of database. It is designed when the database doesn't exist at all. Once the database is operational, it is very difficult to make any changes to it. A database schema does not contain any data or information."
},
{
"code": null,
"e": 19114,
"s": 18762,
"text": "A database instance is a state of operational database with data at any given time. It contains a snapshot of the database. Database instances tend to change with time. A DBMS ensures that its every instance (state) is in a valid state, by diligently following all the validations, constraints, and conditions that the database designers have imposed."
},
{
"code": null,
"e": 19295,
"s": 19114,
"text": "If a database system is not multi-layered, then it becomes difficult to make any changes in the database system. Database systems are designed in multi-layers as we learnt earlier."
},
{
"code": null,
"e": 19741,
"s": 19295,
"text": "A database system normally contains a lot of data in addition to users’ data. For example, it stores data about data, known as metadata, to locate and retrieve data easily. It is rather difficult to modify or update a set of metadata once it is stored in the database. But as a DBMS expands, it needs to change over time to satisfy the requirements of the users. If the entire data is dependent, it would become a tedious and highly complex job."
},
{
"code": null,
"e": 19928,
"s": 19741,
"text": "Metadata itself follows a layered architecture, so that when we change data at one layer, it does not affect the data at another level. This data is independent but mapped to each other."
},
{
"code": null,
"e": 20136,
"s": 19928,
"text": "Logical data is data about database, that is, it stores information about how data is managed inside. For example, a table (relation) stored in the database and all its constraints, applied on that relation."
},
{
"code": null,
"e": 20339,
"s": 20136,
"text": "Logical data independence is a kind of mechanism, which liberalizes itself from actual data stored on the disk. If we do some changes on table format, it should not change the data residing on the disk."
},
{
"code": null,
"e": 20539,
"s": 20339,
"text": "All the schemas are logical, and the actual data is stored in bit format on the disk. Physical data independence is the power to change the physical data without impacting the schema or logical data."
},
{
"code": null,
"e": 20728,
"s": 20539,
"text": "For example, in case we want to change or upgrade the storage system itself − suppose we want to replace hard-disks with SSD − it should not have any impact on the logical data or schemas."
},
{
"code": null,
"e": 20934,
"s": 20728,
"text": "The ER model defines the conceptual view of a database. It works around real-world entities and the associations among them. At view level, the ER model is considered a good option for designing databases."
},
{
"code": null,
"e": 21234,
"s": 20934,
"text": "An entity can be a real-world object, either animate or inanimate, that can be easily identifiable. For example, in a school database, students, teachers, classes, and courses offered can be considered as entities. All these entities have some attributes or properties that give them their identity."
},
{
"code": null,
"e": 21557,
"s": 21234,
"text": "An entity set is a collection of similar types of entities. An entity set may contain entities with attribute sharing similar values. For example, a Students set may contain all the students of a school; likewise a Teachers set may contain all the teachers of a school from all faculties. Entity sets need not be disjoint."
},
{
"code": null,
"e": 21734,
"s": 21557,
"text": "Entities are represented by means of their properties, called attributes. All attributes have values. For example, a student entity may have name, class, and age as attributes."
},
{
"code": null,
"e": 21934,
"s": 21734,
"text": "There exists a domain or range of values that can be assigned to attributes. For example, a student's name cannot be a numeric value. It has to be alphabetic. A student's age cannot be negative, etc."
},
{
"code": null,
"e": 22094,
"s": 21934,
"text": "Simple attribute − Simple attributes are atomic values, which cannot be divided further. For example, a student's phone number is an atomic value of 10 digits."
},
{
"code": null,
"e": 22254,
"s": 22094,
"text": "Simple attribute − Simple attributes are atomic values, which cannot be divided further. For example, a student's phone number is an atomic value of 10 digits."
},
{
"code": null,
"e": 22415,
"s": 22254,
"text": "Composite attribute − Composite attributes are made of more than one simple attribute. For example, a student's complete name may have first_name and last_name."
},
{
"code": null,
"e": 22576,
"s": 22415,
"text": "Composite attribute − Composite attributes are made of more than one simple attribute. For example, a student's complete name may have first_name and last_name."
},
{
"code": null,
"e": 22931,
"s": 22576,
"text": "Derived attribute − Derived attributes are the attributes that do not exist in the physical database, but their values are derived from other attributes present in the database. For example, average_salary in a department should not be saved directly in the database, instead it can be derived. For another example, age can be derived from data_of_birth."
},
{
"code": null,
"e": 23286,
"s": 22931,
"text": "Derived attribute − Derived attributes are the attributes that do not exist in the physical database, but their values are derived from other attributes present in the database. For example, average_salary in a department should not be saved directly in the database, instead it can be derived. For another example, age can be derived from data_of_birth."
},
{
"code": null,
"e": 23395,
"s": 23286,
"text": "Single-value attribute − Single-value attributes contain single value. For example − Social_Security_Number."
},
{
"code": null,
"e": 23504,
"s": 23395,
"text": "Single-value attribute − Single-value attributes contain single value. For example − Social_Security_Number."
},
{
"code": null,
"e": 23664,
"s": 23504,
"text": "Multi-value attribute − Multi-value attributes may contain more than one values. For example, a person can have more than one phone number, email_address, etc."
},
{
"code": null,
"e": 23824,
"s": 23664,
"text": "Multi-value attribute − Multi-value attributes may contain more than one values. For example, a person can have more than one phone number, email_address, etc."
},
{
"code": null,
"e": 23880,
"s": 23824,
"text": "These attribute types can come together in a way like −"
},
{
"code": null,
"e": 23912,
"s": 23880,
"text": "simple single-valued attributes"
},
{
"code": null,
"e": 23943,
"s": 23912,
"text": "simple multi-valued attributes"
},
{
"code": null,
"e": 23978,
"s": 23943,
"text": "composite single-valued attributes"
},
{
"code": null,
"e": 24012,
"s": 23978,
"text": "composite multi-valued attributes"
},
{
"code": null,
"e": 24113,
"s": 24012,
"text": "Key is an attribute or collection of attributes that uniquely identifies an entity among entity set."
},
{
"code": null,
"e": 24198,
"s": 24113,
"text": "For example, the roll_number of a student makes him/her identifiable among students."
},
{
"code": null,
"e": 24301,
"s": 24198,
"text": "Super Key − A set of attributes (one or more) that collectively identifies an entity in an entity set."
},
{
"code": null,
"e": 24404,
"s": 24301,
"text": "Super Key − A set of attributes (one or more) that collectively identifies an entity in an entity set."
},
{
"code": null,
"e": 24519,
"s": 24404,
"text": "Candidate Key − A minimal super key is called a candidate key. An entity set may have more than one candidate key."
},
{
"code": null,
"e": 24634,
"s": 24519,
"text": "Candidate Key − A minimal super key is called a candidate key. An entity set may have more than one candidate key."
},
{
"code": null,
"e": 24760,
"s": 24634,
"text": "Primary Key − A primary key is one of the candidate keys chosen by the database designer to uniquely identify the entity set."
},
{
"code": null,
"e": 24886,
"s": 24760,
"text": "Primary Key − A primary key is one of the candidate keys chosen by the database designer to uniquely identify the entity set."
},
{
"code": null,
"e": 25075,
"s": 24886,
"text": "The association among entities is called a relationship. For example, an employee works_at a department, a student enrolls in a course. Here, Works_at and Enrolls are called relationships."
},
{
"code": null,
"e": 25251,
"s": 25075,
"text": "A set of relationships of similar type is called a relationship set. Like entities, a relationship too can have attributes. These attributes are called descriptive attributes."
},
{
"code": null,
"e": 25346,
"s": 25251,
"text": "The number of participating entities in a relationship defines the degree of the relationship."
},
{
"code": null,
"e": 25364,
"s": 25346,
"text": "Binary = degree 2"
},
{
"code": null,
"e": 25383,
"s": 25364,
"text": "Ternary = degree 3"
},
{
"code": null,
"e": 25398,
"s": 25383,
"text": "n-ary = degree"
},
{
"code": null,
"e": 25547,
"s": 25398,
"text": "Cardinality defines the number of entities in one entity set, which can be associated with the number of entities of other set via relationship set."
},
{
"code": null,
"e": 25663,
"s": 25547,
"text": "One-to-one − One entity from entity set A can be associated with at most one entity of entity set B and vice versa."
},
{
"code": null,
"e": 25779,
"s": 25663,
"text": "One-to-one − One entity from entity set A can be associated with at most one entity of entity set B and vice versa."
},
{
"code": null,
"e": 25964,
"s": 25779,
"text": "One-to-many − One entity from entity set A can be associated with more than one entities of entity set B however an entity from entity set B, can be associated with at most one entity."
},
{
"code": null,
"e": 26149,
"s": 25964,
"text": "One-to-many − One entity from entity set A can be associated with more than one entities of entity set B however an entity from entity set B, can be associated with at most one entity."
},
{
"code": null,
"e": 26362,
"s": 26149,
"text": "Many-to-one − More than one entities from entity set A can be associated with at most one entity of entity set B, however an entity from entity set B can be associated with more than one entity from entity set A."
},
{
"code": null,
"e": 26575,
"s": 26362,
"text": "Many-to-one − More than one entities from entity set A can be associated with at most one entity of entity set B, however an entity from entity set B can be associated with more than one entity from entity set A."
},
{
"code": null,
"e": 26675,
"s": 26575,
"text": "Many-to-many − One entity from A can be associated with more than one entity from B and vice versa."
},
{
"code": null,
"e": 26775,
"s": 26675,
"text": "Many-to-many − One entity from A can be associated with more than one entity from B and vice versa."
},
{
"code": null,
"e": 27018,
"s": 26775,
"text": "Let us now learn how the ER Model is represented by means of an ER diagram. Any object, for example, entities, attributes of an entity, relationship sets, and attributes of relationship sets, can be represented with the help of an ER diagram."
},
{
"code": null,
"e": 27124,
"s": 27018,
"text": "Entities are represented by means of rectangles. Rectangles are named with the entity set they represent."
},
{
"code": null,
"e": 27308,
"s": 27124,
"text": "Attributes are the properties of entities. Attributes are represented by means of ellipses. Every ellipse represents one attribute and is directly connected to its entity (rectangle)."
},
{
"code": null,
"e": 27533,
"s": 27308,
"text": "If the attributes are composite, they are further divided in a tree like structure. Every node is then connected to its attribute. That is, composite attributes are represented by ellipses that are connected with an ellipse."
},
{
"code": null,
"e": 27588,
"s": 27533,
"text": "Multivalued attributes are depicted by double ellipse."
},
{
"code": null,
"e": 27639,
"s": 27588,
"text": "Derived attributes are depicted by dashed ellipse."
},
{
"code": null,
"e": 27846,
"s": 27639,
"text": "Relationships are represented by diamond-shaped box. Name of the relationship is written inside the diamond-box. All the entities (rectangles) participating in a relationship, are connected to it by a line."
},
{
"code": null,
"e": 28040,
"s": 27846,
"text": "A relationship where two entities are participating is called a binary relationship. Cardinality is the number of instance of an entity from a relation that can be associated with the relation."
},
{
"code": null,
"e": 28296,
"s": 28040,
"text": "One-to-one − When only one instance of an entity is associated with the relationship, it is marked as '1:1'. The following image reflects that only one instance of each entity should be associated with the relationship. It depicts one-to-one relationship."
},
{
"code": null,
"e": 28552,
"s": 28296,
"text": "One-to-one − When only one instance of an entity is associated with the relationship, it is marked as '1:1'. The following image reflects that only one instance of each entity should be associated with the relationship. It depicts one-to-one relationship."
},
{
"code": null,
"e": 28870,
"s": 28552,
"text": "One-to-many − When more than one instance of an entity is associated with a relationship, it is marked as '1:N'. The following image reflects that only one instance of entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts one-to-many relationship."
},
{
"code": null,
"e": 29188,
"s": 28870,
"text": "One-to-many − When more than one instance of an entity is associated with a relationship, it is marked as '1:N'. The following image reflects that only one instance of entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts one-to-many relationship."
},
{
"code": null,
"e": 29508,
"s": 29188,
"text": "Many-to-one − When more than one instance of entity is associated with the relationship, it is marked as 'N:1'. The following image reflects that more than one instance of an entity on the left and only one instance of an entity on the right can be associated with the relationship. It depicts many-to-one relationship."
},
{
"code": null,
"e": 29828,
"s": 29508,
"text": "Many-to-one − When more than one instance of entity is associated with the relationship, it is marked as 'N:1'. The following image reflects that more than one instance of an entity on the left and only one instance of an entity on the right can be associated with the relationship. It depicts many-to-one relationship."
},
{
"code": null,
"e": 30057,
"s": 29828,
"text": "Many-to-many − The following image reflects that more than one instance of an entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts many-to-many relationship."
},
{
"code": null,
"e": 30286,
"s": 30057,
"text": "Many-to-many − The following image reflects that more than one instance of an entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts many-to-many relationship."
},
{
"code": null,
"e": 30405,
"s": 30286,
"text": "Total Participation − Each entity is involved in the relationship. Total participation is represented by double lines."
},
{
"code": null,
"e": 30524,
"s": 30405,
"text": "Total Participation − Each entity is involved in the relationship. Total participation is represented by double lines."
},
{
"code": null,
"e": 30653,
"s": 30524,
"text": "Partial participation − Not all entities are involved in the relationship. Partial participation is represented by single lines."
},
{
"code": null,
"e": 30782,
"s": 30653,
"text": "Partial participation − Not all entities are involved in the relationship. Partial participation is represented by single lines."
},
{
"code": null,
"e": 31025,
"s": 30782,
"text": "Let us now learn how the ER Model is represented by means of an ER diagram. Any object, for example, entities, attributes of an entity, relationship sets, and attributes of relationship sets, can be represented with the help of an ER diagram."
},
{
"code": null,
"e": 31131,
"s": 31025,
"text": "Entities are represented by means of rectangles. Rectangles are named with the entity set they represent."
},
{
"code": null,
"e": 31315,
"s": 31131,
"text": "Attributes are the properties of entities. Attributes are represented by means of ellipses. Every ellipse represents one attribute and is directly connected to its entity (rectangle)."
},
{
"code": null,
"e": 31540,
"s": 31315,
"text": "If the attributes are composite, they are further divided in a tree like structure. Every node is then connected to its attribute. That is, composite attributes are represented by ellipses that are connected with an ellipse."
},
{
"code": null,
"e": 31595,
"s": 31540,
"text": "Multivalued attributes are depicted by double ellipse."
},
{
"code": null,
"e": 31646,
"s": 31595,
"text": "Derived attributes are depicted by dashed ellipse."
},
{
"code": null,
"e": 31853,
"s": 31646,
"text": "Relationships are represented by diamond-shaped box. Name of the relationship is written inside the diamond-box. All the entities (rectangles) participating in a relationship, are connected to it by a line."
},
{
"code": null,
"e": 32047,
"s": 31853,
"text": "A relationship where two entities are participating is called a binary relationship. Cardinality is the number of instance of an entity from a relation that can be associated with the relation."
},
{
"code": null,
"e": 32303,
"s": 32047,
"text": "One-to-one − When only one instance of an entity is associated with the relationship, it is marked as '1:1'. The following image reflects that only one instance of each entity should be associated with the relationship. It depicts one-to-one relationship."
},
{
"code": null,
"e": 32559,
"s": 32303,
"text": "One-to-one − When only one instance of an entity is associated with the relationship, it is marked as '1:1'. The following image reflects that only one instance of each entity should be associated with the relationship. It depicts one-to-one relationship."
},
{
"code": null,
"e": 32877,
"s": 32559,
"text": "One-to-many − When more than one instance of an entity is associated with a relationship, it is marked as '1:N'. The following image reflects that only one instance of entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts one-to-many relationship."
},
{
"code": null,
"e": 33195,
"s": 32877,
"text": "One-to-many − When more than one instance of an entity is associated with a relationship, it is marked as '1:N'. The following image reflects that only one instance of entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts one-to-many relationship."
},
{
"code": null,
"e": 33515,
"s": 33195,
"text": "Many-to-one − When more than one instance of entity is associated with the relationship, it is marked as 'N:1'. The following image reflects that more than one instance of an entity on the left and only one instance of an entity on the right can be associated with the relationship. It depicts many-to-one relationship."
},
{
"code": null,
"e": 33835,
"s": 33515,
"text": "Many-to-one − When more than one instance of entity is associated with the relationship, it is marked as 'N:1'. The following image reflects that more than one instance of an entity on the left and only one instance of an entity on the right can be associated with the relationship. It depicts many-to-one relationship."
},
{
"code": null,
"e": 34064,
"s": 33835,
"text": "Many-to-many − The following image reflects that more than one instance of an entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts many-to-many relationship."
},
{
"code": null,
"e": 34293,
"s": 34064,
"text": "Many-to-many − The following image reflects that more than one instance of an entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts many-to-many relationship."
},
{
"code": null,
"e": 34412,
"s": 34293,
"text": "Total Participation − Each entity is involved in the relationship. Total participation is represented by double lines."
},
{
"code": null,
"e": 34531,
"s": 34412,
"text": "Total Participation − Each entity is involved in the relationship. Total participation is represented by double lines."
},
{
"code": null,
"e": 34660,
"s": 34531,
"text": "Partial participation − Not all entities are involved in the relationship. Partial participation is represented by single lines."
},
{
"code": null,
"e": 34789,
"s": 34660,
"text": "Partial participation − Not all entities are involved in the relationship. Partial participation is represented by single lines."
},
{
"code": null,
"e": 35033,
"s": 34789,
"text": "The ER Model has the power of expressing database entities in a conceptual hierarchical manner. As the hierarchy goes up, it generalizes the view of entities, and as we go deep in the hierarchy, it gives us the detail of every entity included."
},
{
"code": null,
"e": 35414,
"s": 35033,
"text": "Going up in this structure is called generalization, where entities are clubbed together to represent a more generalized view. For example, a particular student named Mira can be generalized along with all the students. The entity shall be a student, and further, the student is a person. The reverse is called specialization where a person is a student, and that student is Mira."
},
{
"code": null,
"e": 35797,
"s": 35414,
"text": "As mentioned above, the process of generalizing entities, where the generalized entities contain the properties of all the generalized entities, is called generalization. In generalization, a number of entities are brought together into one generalized entity based on their similar characteristics. For example, pigeon, house sparrow, crow and dove can all be generalized as Birds."
},
{
"code": null,
"e": 36218,
"s": 35797,
"text": "Specialization is the opposite of generalization. In specialization, a group of entities is divided into sub-groups based on their characteristics. Take a group ‘Person’ for example. A person has name, date of birth, gender, etc. These properties are common in all persons, human beings. But in a company, persons can be identified as employee, employer, customer, or vendor, based on what role they play in the company."
},
{
"code": null,
"e": 36363,
"s": 36218,
"text": "Similarly, in a school database, persons can be specialized as teacher, student, or a staff, based on what role they play in school as entities."
},
{
"code": null,
"e": 36570,
"s": 36363,
"text": "We use all the above features of ER-Model in order to create classes of objects in object-oriented programming. The details of entities are generally hidden from the user; this process known as abstraction."
},
{
"code": null,
"e": 36727,
"s": 36570,
"text": "Inheritance is an important feature of Generalization and Specialization. It allows lower-level entities to inherit the attributes of higher-level entities."
},
{
"code": null,
"e": 36872,
"s": 36727,
"text": "For example, the attributes of a Person class such as name, age, and gender can be inherited by lower-level entities such as Student or Teacher."
},
{
"code": null,
"e": 37102,
"s": 36872,
"text": "Dr Edgar F. Codd, after his extensive research on the Relational Model of database systems, came up with twelve rules of his own, which according to him, a database must obey in order to be regarded as a true relational database."
},
{
"code": null,
"e": 37290,
"s": 37102,
"text": "These rules can be applied on any database system that manages stored data using only its relational capabilities. This is a foundation rule, which acts as a base for all the other rules."
},
{
"code": null,
"e": 37449,
"s": 37290,
"text": "The data stored in a database, may it be user data or metadata, must be a value of some table cell. Everything in a database must be stored in a table format."
},
{
"code": null,
"e": 37680,
"s": 37449,
"text": "Every single data element (value) is guaranteed to be accessible logically with a combination of table-name, primary-key (row value), and attribute-name (column value). No other means, such as pointers, can be used to access data."
},
{
"code": null,
"e": 37910,
"s": 37680,
"text": "The NULL values in a database must be given a systematic and uniform treatment. This is a very important rule because a NULL can be interpreted as one the following − data is missing, data is not known, or data is not applicable."
},
{
"code": null,
"e": 38171,
"s": 37910,
"text": "The structure description of the entire database must be stored in an online catalog, known as data dictionary, which can be accessed by authorized users. Users can use the same query language to access the catalog which they use to access the database itself."
},
{
"code": null,
"e": 38509,
"s": 38171,
"text": "A database can only be accessed using a language having linear syntax that supports data definition, data manipulation, and transaction management operations. This language can be used directly or by means of some application. If the database allows access to data without any help of this language, then it is considered as a violation."
},
{
"code": null,
"e": 38612,
"s": 38509,
"text": "All the views of a database, which can theoretically be updated, must also be updatable by the system."
},
{
"code": null,
"e": 38826,
"s": 38612,
"text": "A database must support high-level insertion, updation, and deletion. This must not be limited to a single row, that is, it must also support union, intersection and minus operations to yield sets of data records."
},
{
"code": null,
"e": 39058,
"s": 38826,
"text": "The data stored in a database must be independent of the applications that access the database. Any change in the physical structure of a database must not have any impact on how the data is being accessed by external applications."
},
{
"code": null,
"e": 39404,
"s": 39058,
"text": "The logical data in a database must be independent of its user’s view (application). Any change in logical data must not affect the applications using it. For example, if two tables are merged or one is split into two different tables, there should be no impact or change on the user application. This is one of the most difficult rule to apply."
},
{
"code": null,
"e": 39666,
"s": 39404,
"text": "A database must be independent of the application that uses it. All its integrity constraints can be independently modified without the need of any change in the application. This rule makes a database independent of the front-end application and its interface."
},
{
"code": null,
"e": 39917,
"s": 39666,
"text": "The end-user must not be able to see that the data is distributed over various locations. Users should always get the impression that the data is located at one site only. This rule has been regarded as the foundation of distributed database systems."
},
{
"code": null,
"e": 40094,
"s": 39917,
"text": "If a system has an interface that provides access to low-level records, then the interface must not be able to subvert the system and bypass security and integrity constraints."
},
{
"code": null,
"e": 40332,
"s": 40094,
"text": "Relational data model is the primary data model, which is used widely around the world for data storage and processing. This model is simple and it has all the properties and capabilities required to process data with storage efficiency."
},
{
"code": null,
"e": 40558,
"s": 40332,
"text": "Tables − In relational data model, relations are saved in the format of Tables. This format stores the relation among entities. A table has rows and columns, where rows represents records and columns represent the attributes."
},
{
"code": null,
"e": 40659,
"s": 40558,
"text": "Tuple − A single row of a table, which contains a single record for that relation is called a tuple."
},
{
"code": null,
"e": 40815,
"s": 40659,
"text": "Relation instance − A finite set of tuples in the relational database system represents relation instance. Relation instances do not have duplicate tuples."
},
{
"code": null,
"e": 40922,
"s": 40815,
"text": "Relation schema − A relation schema describes the relation name (table name), attributes, and their names."
},
{
"code": null,
"e": 41058,
"s": 40922,
"text": "Relation key − Each row has one or more attributes, known as relation key, which can identify the row in the relation (table) uniquely."
},
{
"code": null,
"e": 41154,
"s": 41058,
"text": "Attribute domain − Every attribute has some pre-defined value scope, known as attribute domain."
},
{
"code": null,
"e": 41343,
"s": 41154,
"text": "Every relation has some conditions that must hold for it to be a valid relation. These conditions are called Relational Integrity Constraints. There are three main integrity constraints −"
},
{
"code": null,
"e": 41359,
"s": 41343,
"text": "Key constraints"
},
{
"code": null,
"e": 41378,
"s": 41359,
"text": "Domain constraints"
},
{
"code": null,
"e": 41412,
"s": 41378,
"text": "Referential integrity constraints"
},
{
"code": null,
"e": 41671,
"s": 41412,
"text": "There must be at least one minimal subset of attributes in the relation, which can identify a tuple uniquely. This minimal subset of attributes is called key for that relation. If there are more than one such minimal subsets, these are called candidate keys."
},
{
"code": null,
"e": 41700,
"s": 41671,
"text": "Key constraints force that −"
},
{
"code": null,
"e": 41796,
"s": 41700,
"text": "in a relation with a key attribute, no two tuples can have identical values for key attributes."
},
{
"code": null,
"e": 41892,
"s": 41796,
"text": "in a relation with a key attribute, no two tuples can have identical values for key attributes."
},
{
"code": null,
"e": 41934,
"s": 41892,
"text": "a key attribute can not have NULL values."
},
{
"code": null,
"e": 41976,
"s": 41934,
"text": "a key attribute can not have NULL values."
},
{
"code": null,
"e": 42036,
"s": 41976,
"text": "Key constraints are also referred to as Entity Constraints."
},
{
"code": null,
"e": 42382,
"s": 42036,
"text": "Attributes have specific values in real-world scenario. For example, age can only be a positive integer. The same constraints have been tried to employ on the attributes of a relation. Every attribute is bound to have a specific range of values. For example, age cannot be less than zero and telephone numbers cannot contain a digit outside 0-9."
},
{
"code": null,
"e": 42540,
"s": 42382,
"text": "Referential integrity constraints work on the concept of Foreign Keys. A foreign key is a key attribute of a relation that can be referred in other relation."
},
{
"code": null,
"e": 42692,
"s": 42540,
"text": "Referential integrity constraint states that if a relation refers to a key attribute of a different or same relation, then that key element must exist."
},
{
"code": null,
"e": 42914,
"s": 42692,
"text": "Relational database systems are expected to be equipped with a query language that can assist its users to query the database instances. There are two kinds of query languages − relational algebra and relational calculus."
},
{
"code": null,
"e": 43324,
"s": 42914,
"text": "Relational algebra is a procedural query language, which takes instances of relations as input and yields instances of relations as output. It uses operators to perform queries. An operator can be either unary or binary. They accept relations as their input and yield relations as their output. Relational algebra is performed recursively on a relation and intermediate results are also considered relations."
},
{
"code": null,
"e": 43390,
"s": 43324,
"text": "The fundamental operations of relational algebra are as follows −"
},
{
"code": null,
"e": 43397,
"s": 43390,
"text": "Select"
},
{
"code": null,
"e": 43405,
"s": 43397,
"text": "Project"
},
{
"code": null,
"e": 43411,
"s": 43405,
"text": "Union"
},
{
"code": null,
"e": 43425,
"s": 43411,
"text": "Set different"
},
{
"code": null,
"e": 43443,
"s": 43425,
"text": "Cartesian product"
},
{
"code": null,
"e": 43450,
"s": 43443,
"text": "Rename"
},
{
"code": null,
"e": 43514,
"s": 43450,
"text": "We will discuss all these operations in the following sections."
},
{
"code": null,
"e": 43582,
"s": 43514,
"text": "It selects tuples that satisfy the given predicate from a relation."
},
{
"code": null,
"e": 43599,
"s": 43582,
"text": "Notation − σp(r)"
},
{
"code": null,
"e": 43816,
"s": 43599,
"text": "Where σ stands for selection predicate and r stands for relation. p is prepositional logic formula which may use connectors like and, or, and not. These terms may use relational operators like − =, ≠, ≥, < , >, ≤."
},
{
"code": null,
"e": 43830,
"s": 43816,
"text": "For example −"
},
{
"code": null,
"e": 43858,
"s": 43830,
"text": "σsubject=\"database\"(Books)\n"
},
{
"code": null,
"e": 43885,
"s": 43858,
"text": "σsubject=\"database\"(Books)"
},
{
"code": null,
"e": 43949,
"s": 43885,
"text": "Output − Selects tuples from books where subject is 'database'."
},
{
"code": null,
"e": 43993,
"s": 43949,
"text": "σsubject=\"database\" and price=\"450\"(Books)\n"
},
{
"code": null,
"e": 44036,
"s": 43993,
"text": "σsubject=\"database\" and price=\"450\"(Books)"
},
{
"code": null,
"e": 44119,
"s": 44036,
"text": "Output − Selects tuples from books where subject is 'database' and 'price' is 450."
},
{
"code": null,
"e": 44182,
"s": 44119,
"text": "σsubject=\"database\" and price < \"450\" or year > \"2010\"(Books)\n"
},
{
"code": null,
"e": 44244,
"s": 44182,
"text": "σsubject=\"database\" and price < \"450\" or year > \"2010\"(Books)"
},
{
"code": null,
"e": 44363,
"s": 44244,
"text": "Output − Selects tuples from books where subject is 'database' and 'price' is 450 or those books published after 2010."
},
{
"code": null,
"e": 44417,
"s": 44363,
"text": "It projects column(s) that satisfy a given predicate."
},
{
"code": null,
"e": 44444,
"s": 44417,
"text": "Notation − ∏A1, A2, An (r)"
},
{
"code": null,
"e": 44497,
"s": 44444,
"text": "Where A1, A2 , An are attribute names of relation r."
},
{
"code": null,
"e": 44564,
"s": 44497,
"text": "Duplicate rows are automatically eliminated, as relation is a set."
},
{
"code": null,
"e": 44578,
"s": 44564,
"text": "For example −"
},
{
"code": null,
"e": 44605,
"s": 44578,
"text": " ∏subject, author (Books)\n"
},
{
"code": null,
"e": 44631,
"s": 44605,
"text": " ∏subject, author (Books)"
},
{
"code": null,
"e": 44713,
"s": 44631,
"text": "Selects and projects columns named as subject and author from the relation Books."
},
{
"code": null,
"e": 44786,
"s": 44713,
"text": "It performs binary union between two given relations and is defined as −"
},
{
"code": null,
"e": 44819,
"s": 44786,
"text": " r ∪ s = { t | t ∈ r or t ∈ s} \n"
},
{
"code": null,
"e": 44851,
"s": 44819,
"text": " r ∪ s = { t | t ∈ r or t ∈ s} "
},
{
"code": null,
"e": 44869,
"s": 44851,
"text": "Notation − r U s "
},
{
"code": null,
"e": 44958,
"s": 44869,
"text": "Where r and s are either database relations or relation result set (temporary relation)."
},
{
"code": null,
"e": 45030,
"s": 44958,
"text": "For a union operation to be valid, the following conditions must hold −"
},
{
"code": null,
"e": 45080,
"s": 45030,
"text": "r, and s must have the same number of attributes."
},
{
"code": null,
"e": 45118,
"s": 45080,
"text": "Attribute domains must be compatible."
},
{
"code": null,
"e": 45165,
"s": 45118,
"text": "Duplicate tuples are automatically eliminated."
},
{
"code": null,
"e": 45206,
"s": 45165,
"text": " ∏ author (Books) ∪ ∏ author (Articles)\n"
},
{
"code": null,
"e": 45246,
"s": 45206,
"text": " ∏ author (Books) ∪ ∏ author (Articles)"
},
{
"code": null,
"e": 45343,
"s": 45246,
"text": "Output − Projects the names of the authors who have either written a book or an article or both."
},
{
"code": null,
"e": 45463,
"s": 45343,
"text": "The result of set difference operation is tuples, which are present in one relation but are not in the second relation."
},
{
"code": null,
"e": 45480,
"s": 45463,
"text": "Notation − r − s"
},
{
"code": null,
"e": 45537,
"s": 45480,
"text": "Finds all the tuples that are present in r but not in s."
},
{
"code": null,
"e": 45578,
"s": 45537,
"text": " ∏ author (Books) − ∏ author (Articles)\n"
},
{
"code": null,
"e": 45618,
"s": 45578,
"text": " ∏ author (Books) − ∏ author (Articles)"
},
{
"code": null,
"e": 45697,
"s": 45618,
"text": "Output − Provides the name of authors who have written books but not articles."
},
{
"code": null,
"e": 45756,
"s": 45697,
"text": "Combines information of two different relations into one. "
},
{
"code": null,
"e": 45773,
"s": 45756,
"text": "Notation − r Χ s"
},
{
"code": null,
"e": 45839,
"s": 45773,
"text": "Where r and s are relations and their output will be defined as −"
},
{
"code": null,
"e": 45874,
"s": 45839,
"text": "r Χ s = { q t | q ∈ r and t ∈ s}"
},
{
"code": null,
"e": 45923,
"s": 45874,
"text": " ∏ author = 'tutorialspoint'(Books Χ Articles) \n"
},
{
"code": null,
"e": 45971,
"s": 45923,
"text": " ∏ author = 'tutorialspoint'(Books Χ Articles) "
},
{
"code": null,
"e": 46065,
"s": 45971,
"text": "Output − Yields a relation, which shows all the books and articles written by tutorialspoint."
},
{
"code": null,
"e": 46263,
"s": 46065,
"text": "The results of relational algebra are also relations but without any name. The rename operation allows us to rename the output relation. 'rename' operation is denoted with small Greek letter rho ρ."
},
{
"code": null,
"e": 46282,
"s": 46263,
"text": "Notation − ρ x (E)"
},
{
"code": null,
"e": 46340,
"s": 46282,
"text": "Where the result of expression E is saved with name of x."
},
{
"code": null,
"e": 46368,
"s": 46340,
"text": "Additional operations are −"
},
{
"code": null,
"e": 46385,
"s": 46368,
"text": "Set intersection"
},
{
"code": null,
"e": 46396,
"s": 46385,
"text": "Assignment"
},
{
"code": null,
"e": 46409,
"s": 46396,
"text": "Natural join"
},
{
"code": null,
"e": 46562,
"s": 46409,
"text": "In contrast to Relational Algebra, Relational Calculus is a non-procedural query language, that is, it tells what to do but never explains how to do it."
},
{
"code": null,
"e": 46604,
"s": 46562,
"text": "Relational calculus exists in two forms −"
},
{
"code": null,
"e": 46642,
"s": 46604,
"text": "Filtering variable ranges over tuples"
},
{
"code": null,
"e": 46670,
"s": 46642,
"text": "Notation − {T | Condition} "
},
{
"code": null,
"e": 46719,
"s": 46670,
"text": "Returns all tuples T that satisfies a condition."
},
{
"code": null,
"e": 46733,
"s": 46719,
"text": "For example −"
},
{
"code": null,
"e": 46785,
"s": 46733,
"text": "{ T.name | Author(T) AND T.article = 'database' }\n"
},
{
"code": null,
"e": 46872,
"s": 46785,
"text": "Output − Returns tuples with 'name' from Author who has written article on 'database'."
},
{
"code": null,
"e": 46953,
"s": 46872,
"text": "TRC can be quantified. We can use Existential (∃) and Universal Quantifiers (∀)."
},
{
"code": null,
"e": 46967,
"s": 46953,
"text": "For example −"
},
{
"code": null,
"e": 47029,
"s": 46967,
"text": "{ R| ∃T ∈ Authors(T.article='database' AND R.name=T.name)}\n"
},
{
"code": null,
"e": 47102,
"s": 47029,
"text": "Output − The above query will yield the same result as the previous one."
},
{
"code": null,
"e": 47229,
"s": 47102,
"text": "In DRC, the filtering variable uses the domain of attributes instead of entire tuple values (as done in TRC, mentioned above)."
},
{
"code": null,
"e": 47240,
"s": 47229,
"text": "Notation −"
},
{
"code": null,
"e": 47289,
"s": 47240,
"text": "{ a1, a2, a3, ..., an | P (a1, a2, a3, ... ,an)}"
},
{
"code": null,
"e": 47370,
"s": 47289,
"text": "Where a1, a2 are attributes and P stands for formulae built by inner attributes."
},
{
"code": null,
"e": 47384,
"s": 47370,
"text": "For example −"
},
{
"code": null,
"e": 47457,
"s": 47384,
"text": "{< article, page, subject > | ∈ TutorialsPoint ∧ subject = 'database'}\n"
},
{
"code": null,
"e": 47529,
"s": 47457,
"text": "{< article, page, subject > | ∈ TutorialsPoint ∧ subject = 'database'}"
},
{
"code": null,
"e": 47633,
"s": 47529,
"text": "Output − Yields Article, Page, and Subject from the relation TutorialsPoint, where subject is database."
},
{
"code": null,
"e": 47758,
"s": 47633,
"text": "Just like TRC, DRC can also be written using existential and universal quantifiers. DRC also involves relational operators."
},
{
"code": null,
"e": 47872,
"s": 47758,
"text": "The expression power of Tuple Relation Calculus and Domain Relation Calculus is equivalent to Relational Algebra."
},
{
"code": null,
"e": 48219,
"s": 47872,
"text": "ER Model, when conceptualized into diagrams, gives a good overview of entity-relationship, which is easier to understand. ER diagrams can be mapped to relational schema, that is, it is possible to create relational schema using ER diagram. We cannot import all the ER constraints into relational model, but an approximate schema can be generated."
},
{
"code": null,
"e": 48447,
"s": 48219,
"text": "There are several processes and algorithms available to convert ER Diagrams into Relational Schema. Some of them are automated and some of them are manual. We may focus here on the mapping diagram contents to relational basics."
},
{
"code": null,
"e": 48480,
"s": 48447,
"text": "ER diagrams mainly comprise of −"
},
{
"code": null,
"e": 48506,
"s": 48480,
"text": "Entity and its attributes"
},
{
"code": null,
"e": 48557,
"s": 48506,
"text": "Relationship, which is association among entities."
},
{
"code": null,
"e": 48612,
"s": 48557,
"text": "An entity is a real-world object with some attributes."
},
{
"code": null,
"e": 48642,
"s": 48612,
"text": "Create table for each entity."
},
{
"code": null,
"e": 48727,
"s": 48642,
"text": "Entity's attributes should become fields of tables with their respective data types."
},
{
"code": null,
"e": 48748,
"s": 48727,
"text": "Declare primary key."
},
{
"code": null,
"e": 48797,
"s": 48748,
"text": "A relationship is an association among entities."
},
{
"code": null,
"e": 48830,
"s": 48797,
"text": "Create table for a relationship."
},
{
"code": null,
"e": 48934,
"s": 48830,
"text": "Add the primary keys of all participating Entities as fields of table with their respective data types."
},
{
"code": null,
"e": 49007,
"s": 48934,
"text": "If relationship has any attribute, add each attribute as field of table."
},
{
"code": null,
"e": 49087,
"s": 49007,
"text": "Declare a primary key composing all the primary keys of participating entities."
},
{
"code": null,
"e": 49124,
"s": 49087,
"text": "Declare all foreign key constraints."
},
{
"code": null,
"e": 49205,
"s": 49124,
"text": "A weak entity set is one which does not have any primary key associated with it."
},
{
"code": null,
"e": 49239,
"s": 49205,
"text": "Create table for weak entity set."
},
{
"code": null,
"e": 49281,
"s": 49239,
"text": "Add all its attributes to table as field."
},
{
"code": null,
"e": 49328,
"s": 49281,
"text": "Add the primary key of identifying entity set."
},
{
"code": null,
"e": 49365,
"s": 49328,
"text": "Declare all foreign key constraints."
},
{
"code": null,
"e": 49448,
"s": 49365,
"text": "ER specialization or generalization comes in the form of hierarchical entity sets."
},
{
"code": null,
"e": 49493,
"s": 49448,
"text": "Create tables for all higher-level entities."
},
{
"code": null,
"e": 49538,
"s": 49493,
"text": "Create tables for all higher-level entities."
},
{
"code": null,
"e": 49578,
"s": 49538,
"text": "Create tables for lower-level entities."
},
{
"code": null,
"e": 49618,
"s": 49578,
"text": "Create tables for lower-level entities."
},
{
"code": null,
"e": 49698,
"s": 49618,
"text": "Add primary keys of higher-level entities in the table of lower-level entities."
},
{
"code": null,
"e": 49778,
"s": 49698,
"text": "Add primary keys of higher-level entities in the table of lower-level entities."
},
{
"code": null,
"e": 49851,
"s": 49778,
"text": "In lower-level tables, add all other attributes of lower-level entities."
},
{
"code": null,
"e": 49924,
"s": 49851,
"text": "In lower-level tables, add all other attributes of lower-level entities."
},
{
"code": null,
"e": 50009,
"s": 49924,
"text": "Declare primary key of higher-level table and the primary key for lower-level table."
},
{
"code": null,
"e": 50094,
"s": 50009,
"text": "Declare primary key of higher-level table and the primary key for lower-level table."
},
{
"code": null,
"e": 50127,
"s": 50094,
"text": "Declare foreign key constraints."
},
{
"code": null,
"e": 50160,
"s": 50127,
"text": "Declare foreign key constraints."
},
{
"code": null,
"e": 50348,
"s": 50160,
"text": "SQL is a programming language for Relational Databases. It is designed over relational algebra and tuple relational calculus. SQL comes as a package with all major distributions of RDBMS."
},
{
"code": null,
"e": 50594,
"s": 50348,
"text": "SQL comprises both data definition and data manipulation languages. Using the data definition properties of SQL, one can design and modify database schema, whereas data manipulation properties allows SQL to store and retrieve data from database."
},
{
"code": null,
"e": 50661,
"s": 50594,
"text": "SQL uses the following set of commands to define database schema −"
},
{
"code": null,
"e": 50713,
"s": 50661,
"text": "Creates new databases, tables and views from RDBMS."
},
{
"code": null,
"e": 50727,
"s": 50713,
"text": "For example −"
},
{
"code": null,
"e": 50808,
"s": 50727,
"text": "Create database tutorialspoint;\nCreate table article;\nCreate view for_students;\n"
},
{
"code": null,
"e": 50865,
"s": 50808,
"text": "Drops commands, views, tables, and databases from RDBMS."
},
{
"code": null,
"e": 50878,
"s": 50865,
"text": "For example−"
},
{
"code": null,
"e": 50983,
"s": 50878,
"text": "Drop object_type object_name;\nDrop database tutorialspoint;\nDrop table article;\nDrop view for_students;\n"
},
{
"code": null,
"e": 51009,
"s": 50983,
"text": "Modifies database schema."
},
{
"code": null,
"e": 51052,
"s": 51009,
"text": "Alter object_type object_name parameters;\n"
},
{
"code": null,
"e": 51065,
"s": 51052,
"text": "For example−"
},
{
"code": null,
"e": 51107,
"s": 51065,
"text": "Alter table article add subject varchar;\n"
},
{
"code": null,
"e": 51200,
"s": 51107,
"text": "This command adds an attribute in the relation article with the name subject of string type."
},
{
"code": null,
"e": 51466,
"s": 51200,
"text": "SQL is equipped with data manipulation language (DML). DML modifies the database instance by inserting, updating and deleting its data. DML is responsible for all forms data modification in a database. SQL contains the following set of commands in its DML section −"
},
{
"code": null,
"e": 51484,
"s": 51466,
"text": "SELECT/FROM/WHERE"
},
{
"code": null,
"e": 51503,
"s": 51484,
"text": "INSERT INTO/VALUES"
},
{
"code": null,
"e": 51520,
"s": 51503,
"text": "UPDATE/SET/WHERE"
},
{
"code": null,
"e": 51538,
"s": 51520,
"text": "DELETE FROM/WHERE"
},
{
"code": null,
"e": 51705,
"s": 51538,
"text": "These basic constructs allow database programmers and users to enter data and information into the database and retrieve efficiently using a number of filter options."
},
{
"code": null,
"e": 51908,
"s": 51705,
"text": "SELECT − This is one of the fundamental query command of SQL. It is similar to the projection operation of relational algebra. It selects the attributes based on the condition described by WHERE clause."
},
{
"code": null,
"e": 52111,
"s": 51908,
"text": "SELECT − This is one of the fundamental query command of SQL. It is similar to the projection operation of relational algebra. It selects the attributes based on the condition described by WHERE clause."
},
{
"code": null,
"e": 52313,
"s": 52111,
"text": "FROM − This clause takes a relation name as an argument from which attributes are to be selected/projected. In case more than one relation names are given, this clause corresponds to Cartesian product."
},
{
"code": null,
"e": 52515,
"s": 52313,
"text": "FROM − This clause takes a relation name as an argument from which attributes are to be selected/projected. In case more than one relation names are given, this clause corresponds to Cartesian product."
},
{
"code": null,
"e": 52637,
"s": 52515,
"text": "WHERE − This clause defines predicate or conditions, which must match in order to qualify the attributes to be projected."
},
{
"code": null,
"e": 52759,
"s": 52637,
"text": "WHERE − This clause defines predicate or conditions, which must match in order to qualify the attributes to be projected."
},
{
"code": null,
"e": 52773,
"s": 52759,
"text": "For example −"
},
{
"code": null,
"e": 52826,
"s": 52773,
"text": "Select author_name\nFrom book_author\nWhere age > 50;\n"
},
{
"code": null,
"e": 52931,
"s": 52826,
"text": "This command will yield the names of authors from the relation book_author whose age is greater than 50."
},
{
"code": null,
"e": 53010,
"s": 52931,
"text": "This command is used for inserting values into the rows of a table (relation)."
},
{
"code": null,
"e": 53018,
"s": 53010,
"text": "Syntax−"
},
{
"code": null,
"e": 53113,
"s": 53018,
"text": "INSERT INTO table (column1 [, column2, column3 ... ]) VALUES (value1 [, value2, value3 ... ])\n"
},
{
"code": null,
"e": 53116,
"s": 53113,
"text": "Or"
},
{
"code": null,
"e": 53167,
"s": 53116,
"text": "INSERT INTO table VALUES (value1, [value2, ... ])\n"
},
{
"code": null,
"e": 53181,
"s": 53167,
"text": "For example −"
},
{
"code": null,
"e": 53262,
"s": 53181,
"text": "INSERT INTO tutorialspoint (Author, Subject) VALUES (\"anonymous\", \"computers\");\n"
},
{
"code": null,
"e": 53354,
"s": 53262,
"text": "This command is used for updating or modifying the values of columns in a table (relation)."
},
{
"code": null,
"e": 53363,
"s": 53354,
"text": "Syntax −"
},
{
"code": null,
"e": 53452,
"s": 53363,
"text": "UPDATE table_name SET column_name = value [, column_name = value ...] [WHERE condition]\n"
},
{
"code": null,
"e": 53466,
"s": 53452,
"text": "For example −"
},
{
"code": null,
"e": 53538,
"s": 53466,
"text": "UPDATE tutorialspoint SET Author=\"webmaster\" WHERE Author=\"anonymous\";\n"
},
{
"code": null,
"e": 53614,
"s": 53538,
"text": "This command is used for removing one or more rows from a table (relation)."
},
{
"code": null,
"e": 53623,
"s": 53614,
"text": "Syntax −"
},
{
"code": null,
"e": 53666,
"s": 53623,
"text": "DELETE FROM table_name [WHERE condition];\n"
},
{
"code": null,
"e": 53680,
"s": 53666,
"text": "For example −"
},
{
"code": null,
"e": 53736,
"s": 53680,
"text": "DELETE FROM tutorialspoints\n WHERE Author=\"unknown\";\n"
},
{
"code": null,
"e": 54003,
"s": 53736,
"text": "Functional dependency (FD) is a set of constraints between two attributes in a relation. Functional dependency says that if two tuples have same values for attributes A1, A2,..., An, then those two tuples must have to have same values for attributes B1, B2, ..., Bn."
},
{
"code": null,
"e": 54199,
"s": 54003,
"text": "Functional dependency is represented by an arrow sign (→) that is, X→Y, where X functionally determines Y. The left-hand side attributes determine the values of attributes on the right-hand side."
},
{
"code": null,
"e": 54461,
"s": 54199,
"text": "If F is a set of functional dependencies then the closure of F, denoted as F+, is the set of all functional dependencies logically implied by F. Armstrong's Axioms are a set of rules, that when applied repeatedly, generates a closure of functional dependencies."
},
{
"code": null,
"e": 54562,
"s": 54461,
"text": "Reflexive rule − If alpha is a set of attributes and beta is_subset_of alpha, then alpha holds beta."
},
{
"code": null,
"e": 54663,
"s": 54562,
"text": "Reflexive rule − If alpha is a set of attributes and beta is_subset_of alpha, then alpha holds beta."
},
{
"code": null,
"e": 54830,
"s": 54663,
"text": "Augmentation rule − If a → b holds and y is attribute set, then ay → by also holds. That is adding attributes in dependencies, does not change the basic dependencies."
},
{
"code": null,
"e": 54997,
"s": 54830,
"text": "Augmentation rule − If a → b holds and y is attribute set, then ay → by also holds. That is adding attributes in dependencies, does not change the basic dependencies."
},
{
"code": null,
"e": 55161,
"s": 54997,
"text": "Transitivity rule − Same as transitive rule in algebra, if a → b holds and b → c holds, then a → c also holds. a → b is called as a functionally that determines b."
},
{
"code": null,
"e": 55325,
"s": 55161,
"text": "Transitivity rule − Same as transitive rule in algebra, if a → b holds and b → c holds, then a → c also holds. a → b is called as a functionally that determines b."
},
{
"code": null,
"e": 55463,
"s": 55325,
"text": "Trivial − If a functional dependency (FD) X → Y holds, where Y is a subset of X, then it is called a trivial FD. Trivial FDs always hold."
},
{
"code": null,
"e": 55601,
"s": 55463,
"text": "Trivial − If a functional dependency (FD) X → Y holds, where Y is a subset of X, then it is called a trivial FD. Trivial FDs always hold."
},
{
"code": null,
"e": 55703,
"s": 55601,
"text": "Non-trivial − If an FD X → Y holds, where Y is not a subset of X, then it is called a non-trivial FD."
},
{
"code": null,
"e": 55805,
"s": 55703,
"text": "Non-trivial − If an FD X → Y holds, where Y is not a subset of X, then it is called a non-trivial FD."
},
{
"code": null,
"e": 55923,
"s": 55805,
"text": "Completely non-trivial − If an FD X → Y holds, where x intersect Y = Φ, it is said to be a completely non-trivial FD."
},
{
"code": null,
"e": 56041,
"s": 55923,
"text": "Completely non-trivial − If an FD X → Y holds, where x intersect Y = Φ, it is said to be a completely non-trivial FD."
},
{
"code": null,
"e": 56221,
"s": 56041,
"text": "If a database design is not perfect, it may contain anomalies, which are like a bad dream for any database administrator. Managing a database with anomalies is next to impossible."
},
{
"code": null,
"e": 56593,
"s": 56221,
"text": "Update anomalies − If data items are scattered and are not linked to each other properly, then it could lead to strange situations. For example, when we try to update one data item having its copies scattered over several places, a few instances get updated properly while a few others are left with old values. Such instances leave the database in an inconsistent state."
},
{
"code": null,
"e": 56965,
"s": 56593,
"text": "Update anomalies − If data items are scattered and are not linked to each other properly, then it could lead to strange situations. For example, when we try to update one data item having its copies scattered over several places, a few instances get updated properly while a few others are left with old values. Such instances leave the database in an inconsistent state."
},
{
"code": null,
"e": 57113,
"s": 56965,
"text": "Deletion anomalies − We tried to delete a record, but parts of it was left undeleted because of unawareness, the data is also saved somewhere else."
},
{
"code": null,
"e": 57261,
"s": 57113,
"text": "Deletion anomalies − We tried to delete a record, but parts of it was left undeleted because of unawareness, the data is also saved somewhere else."
},
{
"code": null,
"e": 57344,
"s": 57261,
"text": "Insert anomalies − We tried to insert data in a record that does not exist at all."
},
{
"code": null,
"e": 57427,
"s": 57344,
"text": "Insert anomalies − We tried to insert data in a record that does not exist at all."
},
{
"code": null,
"e": 57529,
"s": 57427,
"text": "Normalization is a method to remove all these anomalies and bring the database to a consistent state."
},
{
"code": null,
"e": 57742,
"s": 57529,
"text": "First Normal Form is defined in the definition of relations (tables) itself. This rule defines that all the attributes in a relation must have atomic domains. The values in an atomic domain are indivisible units."
},
{
"code": null,
"e": 57823,
"s": 57742,
"text": "We re-arrange the relation (table) as below, to convert it to First Normal Form."
},
{
"code": null,
"e": 57900,
"s": 57823,
"text": "Each attribute must contain only a single value from its pre-defined domain."
},
{
"code": null,
"e": 57984,
"s": 57900,
"text": "Before we learn about the second normal form, we need to understand the following −"
},
{
"code": null,
"e": 58085,
"s": 57984,
"text": "Prime attribute − An attribute, which is a part of the candidate-key, is known as a prime attribute."
},
{
"code": null,
"e": 58186,
"s": 58085,
"text": "Prime attribute − An attribute, which is a part of the candidate-key, is known as a prime attribute."
},
{
"code": null,
"e": 58297,
"s": 58186,
"text": "Non-prime attribute − An attribute, which is not a part of the prime-key, is said to be a non-prime attribute."
},
{
"code": null,
"e": 58408,
"s": 58297,
"text": "Non-prime attribute − An attribute, which is not a part of the prime-key, is said to be a non-prime attribute."
},
{
"code": null,
"e": 58644,
"s": 58408,
"text": "If we follow second normal form, then every non-prime attribute should be fully functionally dependent on prime key attribute. That is, if X → A holds, then there should not be any proper subset Y of X, for which Y → A also holds true."
},
{
"code": null,
"e": 59084,
"s": 58644,
"text": "We see here in Student_Project relation that the prime key attributes are Stu_ID and Proj_ID. According to the rule, non-key attributes, i.e. Stu_Name and Proj_Name must be dependent upon both and not on any of the prime key attribute individually. But we find that Stu_Name can be identified by Stu_ID and Proj_Name can be identified by Proj_ID independently. This is called partial dependency, which is not allowed in Second Normal Form."
},
{
"code": null,
"e": 59186,
"s": 59084,
"text": "We broke the relation in two as depicted in the above picture. So there exists no partial dependency."
},
{
"code": null,
"e": 59295,
"s": 59186,
"text": "For a relation to be in Third Normal Form, it must be in Second Normal form and the following must satisfy −"
},
{
"code": null,
"e": 59368,
"s": 59295,
"text": "No non-prime attribute is transitively dependent on prime key attribute."
},
{
"code": null,
"e": 59476,
"s": 59368,
"text": "For any non-trivial functional dependency, X → A, then either −\nX is a superkey or,\nA is prime attribute.\n\n"
},
{
"code": null,
"e": 59498,
"s": 59476,
"text": "A is prime attribute."
},
{
"code": null,
"e": 59798,
"s": 59498,
"text": "We find that in the above Student_detail relation, Stu_ID is the key and only prime key attribute. We find that City can be identified by Stu_ID as well as Zip itself. Neither Zip is a superkey nor is City a prime attribute. Additionally, Stu_ID → Zip → City, so there exists transitive dependency."
},
{
"code": null,
"e": 59899,
"s": 59798,
"text": "To bring this relation into third normal form, we break the relation into two relations as follows −"
},
{
"code": null,
"e": 60002,
"s": 59899,
"text": "Boyce-Codd Normal Form (BCNF) is an extension of Third Normal Form on strict terms. BCNF states that −"
},
{
"code": null,
"e": 60075,
"s": 60002,
"text": "For any non-trivial functional dependency, X → A, X must be a super-key."
},
{
"code": null,
"e": 60205,
"s": 60075,
"text": "In the above image, Stu_ID is the super-key in the relation Student_Detail and Zip is the super-key in the relation ZipCodes. So,"
},
{
"code": null,
"e": 60228,
"s": 60205,
"text": "Stu_ID → Stu_Name, Zip"
},
{
"code": null,
"e": 60232,
"s": 60228,
"text": "and"
},
{
"code": null,
"e": 60243,
"s": 60232,
"text": "Zip → City"
},
{
"code": null,
"e": 60295,
"s": 60243,
"text": "Which confirms that both the relations are in BCNF."
},
{
"code": null,
"e": 60625,
"s": 60295,
"text": "We understand the benefits of taking a Cartesian product of two relations, which gives us all the possible tuples that are paired together. But it might not be feasible for us in certain cases to take a Cartesian product where we encounter huge relations with thousands of tuples having a considerable large number of attributes."
},
{
"code": null,
"e": 60815,
"s": 60625,
"text": "Join is a combination of a Cartesian product followed by a selection process. A Join operation pairs two tuples from different relations, if and only if a given join condition is satisfied."
},
{
"code": null,
"e": 60886,
"s": 60815,
"text": "We will briefly describe various join types in the following sections."
},
{
"code": null,
"e": 61028,
"s": 60886,
"text": "Theta join combines tuples from different relations provided they satisfy the theta condition. The join condition is denoted by the symbol θ."
},
{
"code": null,
"e": 61038,
"s": 61028,
"text": "R1 ⋈θ R2\n"
},
{
"code": null,
"e": 61194,
"s": 61038,
"text": "R1 and R2 are relations having attributes (A1, A2, .., An) and (B1, B2,.. ,Bn) such that the attributes don’t have anything in common, that is R1 ∩ R2 = Φ."
},
{
"code": null,
"e": 61248,
"s": 61194,
"text": "Theta join can use all kinds of comparison operators."
},
{
"code": null,
"e": 61265,
"s": 61248,
"text": "Student_Detail ="
},
{
"code": null,
"e": 61311,
"s": 61265,
"text": "STUDENT ⋈Student.Std = Subject.Class SUBJECT\n"
},
{
"code": null,
"e": 61437,
"s": 61311,
"text": "When Theta join uses only equality comparison operator, it is said to be equijoin. The above example corresponds to equijoin."
},
{
"code": null,
"e": 61722,
"s": 61437,
"text": "Natural join does not use any comparison operator. It does not concatenate the way a Cartesian product does. We can perform a Natural Join only if there is at least one common attribute that exists between two relations. In addition, the attributes must have the same name and domain."
},
{
"code": null,
"e": 61832,
"s": 61722,
"text": "Natural join acts on those matching attributes where the values of attributes in both the relations are same."
},
{
"code": null,
"e": 62234,
"s": 61832,
"text": "Theta Join, Equijoin, and Natural Join are called inner joins. An inner join includes only those tuples with matching attributes and the rest are discarded in the resulting relation. Therefore, we need to use outer joins to include all the tuples from the participating relations in the resulting relation. There are three kinds of outer joins − left outer join, right outer join, and full outer join."
},
{
"code": null,
"e": 62456,
"s": 62234,
"text": "All the tuples from the Left relation, R, are included in the resulting relation. If there are tuples in R without any matching tuple in the Right relation S, then the S-attributes of the resulting relation are made NULL."
},
{
"code": null,
"e": 62656,
"s": 62456,
"text": "All the tuples from the Right relation, S, are included in the resulting relation. If there are tuples in S without any matching tuple in R, then the R-attributes of resulting relation are made NULL."
},
{
"code": null,
"e": 62850,
"s": 62656,
"text": "All the tuples from both participating relations are included in the resulting relation. If there are no matching tuples for both relations, their respective unmatched attributes are made NULL."
},
{
"code": null,
"e": 63066,
"s": 62850,
"text": "Databases are stored in file formats, which contain records. At physical level, the actual data is stored in electromagnetic format on some device. These storage devices can be broadly categorized into three types −"
},
{
"code": null,
"e": 63536,
"s": 63066,
"text": "Primary Storage − The memory storage that is directly accessible to the CPU comes under this category. CPU's internal memory (registers), fast memory (cache), and main memory (RAM) are directly accessible to the CPU, as they are all placed on the motherboard or CPU chipset. This storage is typically very small, ultra-fast, and volatile. Primary storage requires continuous power supply in order to maintain its state. In case of a power failure, all its data is lost."
},
{
"code": null,
"e": 64006,
"s": 63536,
"text": "Primary Storage − The memory storage that is directly accessible to the CPU comes under this category. CPU's internal memory (registers), fast memory (cache), and main memory (RAM) are directly accessible to the CPU, as they are all placed on the motherboard or CPU chipset. This storage is typically very small, ultra-fast, and volatile. Primary storage requires continuous power supply in order to maintain its state. In case of a power failure, all its data is lost."
},
{
"code": null,
"e": 64307,
"s": 64006,
"text": "Secondary Storage − Secondary storage devices are used to store data for future use or as backup. Secondary storage includes memory devices that are not a part of the CPU chipset or motherboard, for example, magnetic disks, optical disks (DVD, CD, etc.), hard disks, flash drives, and magnetic tapes."
},
{
"code": null,
"e": 64608,
"s": 64307,
"text": "Secondary Storage − Secondary storage devices are used to store data for future use or as backup. Secondary storage includes memory devices that are not a part of the CPU chipset or motherboard, for example, magnetic disks, optical disks (DVD, CD, etc.), hard disks, flash drives, and magnetic tapes."
},
{
"code": null,
"e": 64927,
"s": 64608,
"text": "Tertiary Storage − Tertiary storage is used to store huge volumes of data. Since such storage devices are external to the computer system, they are the slowest in speed. These storage devices are mostly used to take the back up of an entire system. Optical disks and magnetic tapes are widely used as tertiary storage."
},
{
"code": null,
"e": 65246,
"s": 64927,
"text": "Tertiary Storage − Tertiary storage is used to store huge volumes of data. Since such storage devices are external to the computer system, they are the slowest in speed. These storage devices are mostly used to take the back up of an entire system. Optical disks and magnetic tapes are widely used as tertiary storage."
},
{
"code": null,
"e": 65626,
"s": 65246,
"text": "A computer system has a well-defined hierarchy of memory. A CPU has direct access to it main memory as well as its inbuilt registers. The access time of the main memory is obviously less than the CPU speed. To minimize this speed mismatch, cache memory is introduced. Cache memory provides the fastest access time and it contains data that is most frequently accessed by the CPU."
},
{
"code": null,
"e": 65842,
"s": 65626,
"text": "The memory with the fastest access is the costliest one. Larger storage devices offer slow speed and they are less expensive, however they can store huge volumes of data as compared to CPU registers or cache memory."
},
{
"code": null,
"e": 66316,
"s": 65842,
"text": "Hard disk drives are the most common secondary storage devices in present computer systems. These are called magnetic disks because they use the concept of magnetization to store information. Hard disks consist of metal disks coated with magnetizable material. These disks are placed vertically on a spindle. A read/write head moves in between the disks and is used to magnetize or de-magnetize the spot under it. A magnetized spot can be recognized as 0 (zero) or 1 (one)."
},
{
"code": null,
"e": 66565,
"s": 66316,
"text": "Hard disks are formatted in a well-defined order to store data efficiently. A hard disk plate has many concentric circles on it, called tracks. Every track is further divided into sectors. A sector on a hard disk typically stores 512 bytes of data."
},
{
"code": null,
"e": 66727,
"s": 66565,
"text": "RAID stands for Redundant Array of Independent Disks, which is a technology to connect multiple secondary storage devices and use them as a single storage media."
},
{
"code": null,
"e": 66880,
"s": 66727,
"text": "RAID consists of an array of disks in which multiple disks are connected together to achieve different goals. RAID levels define the use of disk arrays."
},
{
"code": null,
"e": 67190,
"s": 66880,
"text": "RAID 0 − In this level, a striped array of disks is implemented. The data is broken down into blocks and the blocks are distributed among disks. Each disk receives a block of data to write/read in parallel. It enhances the speed and performance of the storage device. There is no parity and backup in Level 0."
},
{
"code": null,
"e": 67500,
"s": 67190,
"text": "RAID 0 − In this level, a striped array of disks is implemented. The data is broken down into blocks and the blocks are distributed among disks. Each disk receives a block of data to write/read in parallel. It enhances the speed and performance of the storage device. There is no parity and backup in Level 0."
},
{
"code": null,
"e": 67727,
"s": 67500,
"text": "RAID 1 − RAID 1 uses mirroring techniques. When data is sent to a RAID controller, it sends a copy of data to all the disks in the array. RAID level 1 is also called mirroring and provides 100% redundancy in case of a failure."
},
{
"code": null,
"e": 67954,
"s": 67727,
"text": "RAID 1 − RAID 1 uses mirroring techniques. When data is sent to a RAID controller, it sends a copy of data to all the disks in the array. RAID level 1 is also called mirroring and provides 100% redundancy in case of a failure."
},
{
"code": null,
"e": 68285,
"s": 67954,
"text": "RAID 2 − RAID 2 records Error Correction Code using Hamming distance for its data, striped on different disks. Like level 0, each data bit in a word is recorded on a separate disk and ECC codes of the data words are stored on a different set disks. Due to its complex structure and high cost, RAID 2 is not commercially available."
},
{
"code": null,
"e": 68616,
"s": 68285,
"text": "RAID 2 − RAID 2 records Error Correction Code using Hamming distance for its data, striped on different disks. Like level 0, each data bit in a word is recorded on a separate disk and ECC codes of the data words are stored on a different set disks. Due to its complex structure and high cost, RAID 2 is not commercially available."
},
{
"code": null,
"e": 68798,
"s": 68616,
"text": "RAID 3 − RAID 3 stripes the data onto multiple disks. The parity bit generated for data word is stored on a different disk. This technique makes it to overcome single disk failures."
},
{
"code": null,
"e": 68980,
"s": 68798,
"text": "RAID 3 − RAID 3 stripes the data onto multiple disks. The parity bit generated for data word is stored on a different disk. This technique makes it to overcome single disk failures."
},
{
"code": null,
"e": 69280,
"s": 68980,
"text": "RAID 4 − In this level, an entire block of data is written onto data disks and then the parity is generated and stored on a different disk. Note that level 3 uses byte-level striping, whereas level 4 uses block-level striping. Both level 3 and level 4 require at least three disks to implement RAID."
},
{
"code": null,
"e": 69580,
"s": 69280,
"text": "RAID 4 − In this level, an entire block of data is written onto data disks and then the parity is generated and stored on a different disk. Note that level 3 uses byte-level striping, whereas level 4 uses block-level striping. Both level 3 and level 4 require at least three disks to implement RAID."
},
{
"code": null,
"e": 69792,
"s": 69580,
"text": "RAID 5 − RAID 5 writes whole data blocks onto different disks, but the parity bits generated for data block stripe are distributed among all the data disks rather than storing them on a different dedicated disk."
},
{
"code": null,
"e": 70004,
"s": 69792,
"text": "RAID 5 − RAID 5 writes whole data blocks onto different disks, but the parity bits generated for data block stripe are distributed among all the data disks rather than storing them on a different dedicated disk."
},
{
"code": null,
"e": 70272,
"s": 70004,
"text": "RAID 6 − RAID 6 is an extension of level 5. In this level, two independent parities are generated and stored in distributed fashion among multiple disks. Two parities provide additional fault tolerance. This level requires at least four disk drives to implement RAID."
},
{
"code": null,
"e": 70540,
"s": 70272,
"text": "RAID 6 − RAID 6 is an extension of level 5. In this level, two independent parities are generated and stored in distributed fashion among multiple disks. Two parities provide additional fault tolerance. This level requires at least four disk drives to implement RAID."
},
{
"code": null,
"e": 70785,
"s": 70540,
"text": "Relative data and information is stored collectively in file formats. A file is a sequence of records stored in binary format. A disk drive is formatted into several blocks that can store records. File records are mapped onto those disk blocks."
},
{
"code": null,
"e": 70924,
"s": 70785,
"text": "File Organization defines how file records are mapped onto disk blocks. We have four types of File Organization to organize file records −"
},
{
"code": null,
"e": 71271,
"s": 70924,
"text": "When a file is created using Heap File Organization, the Operating System allocates memory area to that file without any further accounting details. File records can be placed anywhere in that memory area. It is the responsibility of the software to manage the records. Heap File does not support any ordering, sequencing, or indexing on its own."
},
{
"code": null,
"e": 71579,
"s": 71271,
"text": "Every file record contains a data field (attribute) to uniquely identify that record. In sequential file organization, records are placed in the file in some sequential order based on the unique key field or search key. Practically, it is not possible to store all the records sequentially in physical form."
},
{
"code": null,
"e": 71770,
"s": 71579,
"text": "Hash File Organization uses Hash function computation on some fields of the records. The output of the hash function determines the location of disk block where the records are to be placed."
},
{
"code": null,
"e": 72013,
"s": 71770,
"text": "Clustered file organization is not considered good for large databases. In this mechanism, related records from one or more relations are kept in the same disk block, that is, the ordering of records is not based on primary key or search key."
},
{
"code": null,
"e": 72090,
"s": 72013,
"text": "Operations on database files can be broadly classified into two categories −"
},
{
"code": null,
"e": 72108,
"s": 72090,
"text": "Update Operations"
},
{
"code": null,
"e": 72126,
"s": 72108,
"text": "Update Operations"
},
{
"code": null,
"e": 72147,
"s": 72126,
"text": "Retrieval Operations"
},
{
"code": null,
"e": 72168,
"s": 72147,
"text": "Retrieval Operations"
},
{
"code": null,
"e": 72535,
"s": 72168,
"text": "Update operations change the data values by insertion, deletion, or update. Retrieval operations, on the other hand, do not alter the data but retrieve them after optional conditional filtering. In both types of operations, selection plays a significant role. Other than creation and deletion of a file, there could be several operations, which can be done on files."
},
{
"code": null,
"e": 72882,
"s": 72535,
"text": "Open − A file can be opened in one of the two modes, read mode or write mode. In read mode, the operating system does not allow anyone to alter data. In other words, data is read only. Files opened in read mode can be shared among several entities. Write mode allows data modification. Files opened in write mode can be read but cannot be shared."
},
{
"code": null,
"e": 73229,
"s": 72882,
"text": "Open − A file can be opened in one of the two modes, read mode or write mode. In read mode, the operating system does not allow anyone to alter data. In other words, data is read only. Files opened in read mode can be shared among several entities. Write mode allows data modification. Files opened in write mode can be read but cannot be shared."
},
{
"code": null,
"e": 73451,
"s": 73229,
"text": "Locate − Every file has a file pointer, which tells the current position where the data is to be read or written. This pointer can be adjusted accordingly. Using find (seek) operation, it can be moved forward or backward."
},
{
"code": null,
"e": 73673,
"s": 73451,
"text": "Locate − Every file has a file pointer, which tells the current position where the data is to be read or written. This pointer can be adjusted accordingly. Using find (seek) operation, it can be moved forward or backward."
},
{
"code": null,
"e": 73957,
"s": 73673,
"text": "Read − By default, when files are opened in read mode, the file pointer points to the beginning of the file. There are options where the user can tell the operating system where to locate the file pointer at the time of opening a file. The very next data to the file pointer is read."
},
{
"code": null,
"e": 74241,
"s": 73957,
"text": "Read − By default, when files are opened in read mode, the file pointer points to the beginning of the file. There are options where the user can tell the operating system where to locate the file pointer at the time of opening a file. The very next data to the file pointer is read."
},
{
"code": null,
"e": 74510,
"s": 74241,
"text": "Write − User can select to open a file in write mode, which enables them to edit its contents. It can be deletion, insertion, or modification. The file pointer can be located at the time of opening or can be dynamically changed if the operating system allows to do so."
},
{
"code": null,
"e": 74779,
"s": 74510,
"text": "Write − User can select to open a file in write mode, which enables them to edit its contents. It can be deletion, insertion, or modification. The file pointer can be located at the time of opening or can be dynamically changed if the operating system allows to do so."
},
{
"code": null,
"e": 75112,
"s": 74779,
"text": "Close − This is the most important operation from the operating system’s point of view. When a request to close a file is generated, the operating system\n\nremoves all the locks (if in shared mode),\nsaves the data (if altered) to the secondary storage media, and\nreleases all the buffers and file handlers associated with the file.\n\n"
},
{
"code": null,
"e": 75266,
"s": 75112,
"text": "Close − This is the most important operation from the operating system’s point of view. When a request to close a file is generated, the operating system"
},
{
"code": null,
"e": 75309,
"s": 75266,
"text": "removes all the locks (if in shared mode),"
},
{
"code": null,
"e": 75373,
"s": 75309,
"text": "saves the data (if altered) to the secondary storage media, and"
},
{
"code": null,
"e": 75442,
"s": 75373,
"text": "releases all the buffers and file handlers associated with the file."
},
{
"code": null,
"e": 75656,
"s": 75442,
"text": "The organization of data inside a file plays a major role here. The process to locate the file pointer to a desired record inside a file various based on whether the records are arranged sequentially or clustered."
},
{
"code": null,
"e": 75780,
"s": 75656,
"text": "We know that data is stored in the form of records. Every record has a key field, which helps it to be recognized uniquely."
},
{
"code": null,
"e": 76002,
"s": 75780,
"text": "Indexing is a data structure technique to efficiently retrieve records from the database files based on some attributes on which the indexing has been done. Indexing in database systems is similar to what we see in books."
},
{
"code": null,
"e": 76097,
"s": 76002,
"text": "Indexing is defined based on its indexing attributes. Indexing can be of the following types −"
},
{
"code": null,
"e": 76264,
"s": 76097,
"text": "Primary Index − Primary index is defined on an ordered data file. The data file is ordered on a key field. The key field is generally the primary key of the relation."
},
{
"code": null,
"e": 76431,
"s": 76264,
"text": "Primary Index − Primary index is defined on an ordered data file. The data file is ordered on a key field. The key field is generally the primary key of the relation."
},
{
"code": null,
"e": 76596,
"s": 76431,
"text": "Secondary Index − Secondary index may be generated from a field which is a candidate key and has a unique value in every record, or a non-key with duplicate values."
},
{
"code": null,
"e": 76761,
"s": 76596,
"text": "Secondary Index − Secondary index may be generated from a field which is a candidate key and has a unique value in every record, or a non-key with duplicate values."
},
{
"code": null,
"e": 76878,
"s": 76761,
"text": "Clustering Index − Clustering index is defined on an ordered data file. The data file is ordered on a non-key field."
},
{
"code": null,
"e": 76995,
"s": 76878,
"text": "Clustering Index − Clustering index is defined on an ordered data file. The data file is ordered on a non-key field."
},
{
"code": null,
"e": 77030,
"s": 76995,
"text": "Ordered Indexing is of two types −"
},
{
"code": null,
"e": 77042,
"s": 77030,
"text": "Dense Index"
},
{
"code": null,
"e": 77055,
"s": 77042,
"text": "Sparse Index"
},
{
"code": null,
"e": 77310,
"s": 77055,
"text": "In dense index, there is an index record for every search key value in the database. This makes searching faster but requires more space to store index records itself. Index records contain search key value and a pointer to the actual record on the disk."
},
{
"code": null,
"e": 77728,
"s": 77310,
"text": "In sparse index, index records are not created for every search key. An index record here contains a search key and an actual pointer to the data on the disk. To search a record, we first proceed by index record and reach at the actual location of the data. If the data we are looking for is not where we directly reach by following the index, then the system starts sequential search until the desired data is found."
},
{
"code": null,
"e": 78163,
"s": 77728,
"text": "Index records comprise search-key values and data pointers. Multilevel index is stored on the disk along with the actual database files. As the size of the database grows, so does the size of the indices. There is an immense need to keep the index records in the main memory so as to speed up the search operations. If single-level index is used, then a large size index cannot be kept in memory which leads to multiple disk accesses."
},
{
"code": null,
"e": 78396,
"s": 78163,
"text": "Multi-level Index helps in breaking down the index into several smaller indices in order to make the outermost level so small that it can be saved in a single disk block, which can easily be accommodated anywhere in the main memory."
},
{
"code": null,
"e": 78751,
"s": 78396,
"text": "A B+ tree is a balanced binary search tree that follows a multi-level index format. The leaf nodes of a B+ tree denote actual data pointers. B+ tree ensures that all leaf nodes remain at the same height, thus balanced. Additionally, the leaf nodes are linked using a link list; therefore, a B+ tree can support random access as well as sequential access."
},
{
"code": null,
"e": 78872,
"s": 78751,
"text": "Every leaf node is at equal distance from the root node. A B+ tree is of the order n where n is fixed for every B+ tree."
},
{
"code": null,
"e": 78889,
"s": 78872,
"text": "Internal nodes −"
},
{
"code": null,
"e": 78970,
"s": 78889,
"text": "Internal (non-leaf) nodes contain at least ⌈n/2⌉ pointers, except the root node."
},
{
"code": null,
"e": 79020,
"s": 78970,
"text": "At most, an internal node can contain n pointers."
},
{
"code": null,
"e": 79033,
"s": 79020,
"text": "Leaf nodes −"
},
{
"code": null,
"e": 79105,
"s": 79033,
"text": "Leaf nodes contain at least ⌈n/2⌉ record pointers and ⌈n/2⌉ key values."
},
{
"code": null,
"e": 79174,
"s": 79105,
"text": "At most, a leaf node can contain n record pointers and n key values."
},
{
"code": null,
"e": 79271,
"s": 79174,
"text": "Every leaf node contains one block pointer P to point to next leaf node and forms a linked list."
},
{
"code": null,
"e": 79344,
"s": 79271,
"text": "B+ trees are filled from bottom and each entry is done at the leaf node."
},
{
"code": null,
"e": 79417,
"s": 79344,
"text": "B+ trees are filled from bottom and each entry is done at the leaf node."
},
{
"code": null,
"e": 79650,
"s": 79417,
"text": "If a leaf node overflows −\n\nSplit node into two parts.\nPartition at i = ⌊(m+1)/2⌋.\nFirst i entries are stored in one node.\nRest of the entries (i+1 onwards) are moved to a new node.\nith key is duplicated at the parent of the leaf.\n\n"
},
{
"code": null,
"e": 79677,
"s": 79650,
"text": "Split node into two parts."
},
{
"code": null,
"e": 79704,
"s": 79677,
"text": "Split node into two parts."
},
{
"code": null,
"e": 79732,
"s": 79704,
"text": "Partition at i = ⌊(m+1)/2⌋."
},
{
"code": null,
"e": 79760,
"s": 79732,
"text": "Partition at i = ⌊(m+1)/2⌋."
},
{
"code": null,
"e": 79800,
"s": 79760,
"text": "First i entries are stored in one node."
},
{
"code": null,
"e": 79840,
"s": 79800,
"text": "First i entries are stored in one node."
},
{
"code": null,
"e": 79899,
"s": 79840,
"text": "Rest of the entries (i+1 onwards) are moved to a new node."
},
{
"code": null,
"e": 79958,
"s": 79899,
"text": "Rest of the entries (i+1 onwards) are moved to a new node."
},
{
"code": null,
"e": 80007,
"s": 79958,
"text": "ith key is duplicated at the parent of the leaf."
},
{
"code": null,
"e": 80056,
"s": 80007,
"text": "ith key is duplicated at the parent of the leaf."
},
{
"code": null,
"e": 80237,
"s": 80056,
"text": "If a non-leaf node overflows −\n\nSplit node into two parts.\nPartition the node at i = ⌈(m+1)/2⌉.\nEntries up to i are kept in one node.\nRest of the entries are moved to a new node.\n\n"
},
{
"code": null,
"e": 80268,
"s": 80237,
"text": "If a non-leaf node overflows −"
},
{
"code": null,
"e": 80295,
"s": 80268,
"text": "Split node into two parts."
},
{
"code": null,
"e": 80322,
"s": 80295,
"text": "Split node into two parts."
},
{
"code": null,
"e": 80359,
"s": 80322,
"text": "Partition the node at i = ⌈(m+1)/2⌉."
},
{
"code": null,
"e": 80396,
"s": 80359,
"text": "Partition the node at i = ⌈(m+1)/2⌉."
},
{
"code": null,
"e": 80434,
"s": 80396,
"text": "Entries up to i are kept in one node."
},
{
"code": null,
"e": 80472,
"s": 80434,
"text": "Entries up to i are kept in one node."
},
{
"code": null,
"e": 80517,
"s": 80472,
"text": "Rest of the entries are moved to a new node."
},
{
"code": null,
"e": 80562,
"s": 80517,
"text": "Rest of the entries are moved to a new node."
},
{
"code": null,
"e": 80609,
"s": 80562,
"text": "B+ tree entries are deleted at the leaf nodes."
},
{
"code": null,
"e": 80656,
"s": 80609,
"text": "B+ tree entries are deleted at the leaf nodes."
},
{
"code": null,
"e": 80786,
"s": 80656,
"text": "The target entry is searched and deleted.\n\nIf it is an internal node, delete and replace with the entry from the left position.\n\n"
},
{
"code": null,
"e": 80828,
"s": 80786,
"text": "The target entry is searched and deleted."
},
{
"code": null,
"e": 80913,
"s": 80828,
"text": "If it is an internal node, delete and replace with the entry from the left position."
},
{
"code": null,
"e": 80998,
"s": 80913,
"text": "If it is an internal node, delete and replace with the entry from the left position."
},
{
"code": null,
"e": 81109,
"s": 80998,
"text": "After deletion, underflow is tested,\n\nIf underflow occurs, distribute the entries from the nodes left to it.\n\n"
},
{
"code": null,
"e": 81146,
"s": 81109,
"text": "After deletion, underflow is tested,"
},
{
"code": null,
"e": 81217,
"s": 81146,
"text": "If underflow occurs, distribute the entries from the nodes left to it."
},
{
"code": null,
"e": 81288,
"s": 81217,
"text": "If underflow occurs, distribute the entries from the nodes left to it."
},
{
"code": null,
"e": 81378,
"s": 81288,
"text": "If distribution is not possible from left, then\n\nDistribute from the nodes right to it.\n\n"
},
{
"code": null,
"e": 81426,
"s": 81378,
"text": "If distribution is not possible from left, then"
},
{
"code": null,
"e": 81465,
"s": 81426,
"text": "Distribute from the nodes right to it."
},
{
"code": null,
"e": 81504,
"s": 81465,
"text": "Distribute from the nodes right to it."
},
{
"code": null,
"e": 81611,
"s": 81504,
"text": "If distribution is not possible from left or from right, then\n\nMerge the node with left and right to it.\n\n"
},
{
"code": null,
"e": 81673,
"s": 81611,
"text": "If distribution is not possible from left or from right, then"
},
{
"code": null,
"e": 81715,
"s": 81673,
"text": "Merge the node with left and right to it."
},
{
"code": null,
"e": 81757,
"s": 81715,
"text": "Merge the node with left and right to it."
},
{
"code": null,
"e": 82076,
"s": 81757,
"text": "For a huge database structure, it can be almost next to impossible to search all the index values through all its level and then reach the destination data block to retrieve the desired data. Hashing is an effective technique to calculate the direct location of a data record on the disk without using index structure."
},
{
"code": null,
"e": 82177,
"s": 82076,
"text": "Hashing uses hash functions with search keys as parameters to generate the address of a data record."
},
{
"code": null,
"e": 82364,
"s": 82177,
"text": "Bucket − A hash file stores data in bucket format. Bucket is considered a unit of storage. A bucket typically stores one complete disk block, which in turn can store one or more records."
},
{
"code": null,
"e": 82551,
"s": 82364,
"text": "Bucket − A hash file stores data in bucket format. Bucket is considered a unit of storage. A bucket typically stores one complete disk block, which in turn can store one or more records."
},
{
"code": null,
"e": 82751,
"s": 82551,
"text": "Hash Function − A hash function, h, is a mapping function that maps all the set of search-keys K to the address where actual records are placed. It is a function from search keys to bucket addresses."
},
{
"code": null,
"e": 82951,
"s": 82751,
"text": "Hash Function − A hash function, h, is a mapping function that maps all the set of search-keys K to the address where actual records are placed. It is a function from search keys to bucket addresses."
},
{
"code": null,
"e": 83264,
"s": 82951,
"text": "In static hashing, when a search-key value is provided, the hash function always computes the same address. For example, if mod-4 hash function is used, then it shall generate only 5 values. The output address shall always be same for that function. The number of buckets provided remains unchanged at all times."
},
{
"code": null,
"e": 83456,
"s": 83264,
"text": "Insertion − When a record is required to be entered using static hash, the hash function h computes the bucket address for search key K, where the record will be stored.\nBucket address = h(K)"
},
{
"code": null,
"e": 83626,
"s": 83456,
"text": "Insertion − When a record is required to be entered using static hash, the hash function h computes the bucket address for search key K, where the record will be stored."
},
{
"code": null,
"e": 83648,
"s": 83626,
"text": "Bucket address = h(K)"
},
{
"code": null,
"e": 83793,
"s": 83648,
"text": "Search − When a record needs to be retrieved, the same hash function can be used to retrieve the address of the bucket where the data is stored."
},
{
"code": null,
"e": 83938,
"s": 83793,
"text": "Search − When a record needs to be retrieved, the same hash function can be used to retrieve the address of the bucket where the data is stored."
},
{
"code": null,
"e": 84005,
"s": 83938,
"text": "Delete − This is simply a search followed by a deletion operation."
},
{
"code": null,
"e": 84072,
"s": 84005,
"text": "Delete − This is simply a search followed by a deletion operation."
},
{
"code": null,
"e": 84225,
"s": 84072,
"text": "The condition of bucket-overflow is known as collision. This is a fatal state for any static hash function. In this case, overflow chaining can be used."
},
{
"code": null,
"e": 84398,
"s": 84225,
"text": "Overflow Chaining − When buckets are full, a new bucket is allocated for the same hash result and is linked after the previous one. This mechanism is called Closed Hashing."
},
{
"code": null,
"e": 84571,
"s": 84398,
"text": "Overflow Chaining − When buckets are full, a new bucket is allocated for the same hash result and is linked after the previous one. This mechanism is called Closed Hashing."
},
{
"code": null,
"e": 84743,
"s": 84571,
"text": "Linear Probing − When a hash function generates an address at which data is already stored, the next free bucket is allocated to it. This mechanism is called Open Hashing."
},
{
"code": null,
"e": 84915,
"s": 84743,
"text": "Linear Probing − When a hash function generates an address at which data is already stored, the next free bucket is allocated to it. This mechanism is called Open Hashing."
},
{
"code": null,
"e": 85201,
"s": 84915,
"text": "The problem with static hashing is that it does not expand or shrink dynamically as the size of the database grows or shrinks. Dynamic hashing provides a mechanism in which data buckets are added and removed dynamically and on-demand. Dynamic hashing is also known as extended hashing."
},
{
"code": null,
"e": 85315,
"s": 85201,
"text": "Hash function, in dynamic hashing, is made to produce a large number of values and only a few are used initially."
},
{
"code": null,
"e": 85740,
"s": 85315,
"text": "The prefix of an entire hash value is taken as a hash index. Only a portion of the hash value is used for computing bucket addresses. Every hash index has a depth value to signify how many bits are used for computing a hash function. These bits can address 2n buckets. When all these bits are consumed − that is, when all the buckets are full − then the depth value is increased linearly and twice the buckets are allocated."
},
{
"code": null,
"e": 85843,
"s": 85740,
"text": "Querying − Look at the depth value of the hash index and use those bits to compute the bucket address."
},
{
"code": null,
"e": 85946,
"s": 85843,
"text": "Querying − Look at the depth value of the hash index and use those bits to compute the bucket address."
},
{
"code": null,
"e": 86001,
"s": 85946,
"text": "Update − Perform a query as above and update the data."
},
{
"code": null,
"e": 86056,
"s": 86001,
"text": "Update − Perform a query as above and update the data."
},
{
"code": null,
"e": 86131,
"s": 86056,
"text": "Deletion − Perform a query to locate the desired data and delete the same."
},
{
"code": null,
"e": 86206,
"s": 86131,
"text": "Deletion − Perform a query to locate the desired data and delete the same."
},
{
"code": null,
"e": 86477,
"s": 86206,
"text": "Insertion − Compute the address of the bucket\n\nIf the bucket is already full.\n\nAdd more buckets.\nAdd additional bits to the hash value.\nRe-compute the hash function.\n\n\nElse\n\nAdd data to the bucket,\n\n\nIf all the buckets are full, perform the remedies of static hashing.\n\n"
},
{
"code": null,
"e": 86523,
"s": 86477,
"text": "Insertion − Compute the address of the bucket"
},
{
"code": null,
"e": 86644,
"s": 86523,
"text": "If the bucket is already full.\n\nAdd more buckets.\nAdd additional bits to the hash value.\nRe-compute the hash function.\n\n"
},
{
"code": null,
"e": 86662,
"s": 86644,
"text": "Add more buckets."
},
{
"code": null,
"e": 86701,
"s": 86662,
"text": "Add additional bits to the hash value."
},
{
"code": null,
"e": 86731,
"s": 86701,
"text": "Re-compute the hash function."
},
{
"code": null,
"e": 86763,
"s": 86731,
"text": "Else\n\nAdd data to the bucket,\n\n"
},
{
"code": null,
"e": 86787,
"s": 86763,
"text": "Add data to the bucket,"
},
{
"code": null,
"e": 86856,
"s": 86787,
"text": "If all the buckets are full, perform the remedies of static hashing."
},
{
"code": null,
"e": 87024,
"s": 86856,
"text": "Hashing is not favorable when the data is organized in some ordering and the queries require a range of data. When data is discrete and random, hash performs the best."
},
{
"code": null,
"e": 87126,
"s": 87024,
"text": "Hashing algorithms have high complexity than indexing. All hash operations are done in constant time."
},
{
"code": null,
"e": 87254,
"s": 87126,
"text": "A transaction can be defined as a group of tasks. A single task is the minimum processing unit which cannot be divided further."
},
{
"code": null,
"e": 87448,
"s": 87254,
"text": "Let’s take an example of a simple transaction. Suppose a bank employee transfers Rs 500 from A's account to B's account. This very simple and small transaction involves several low-level tasks."
},
{
"code": null,
"e": 87460,
"s": 87448,
"text": "A’s Account"
},
{
"code": null,
"e": 87574,
"s": 87460,
"text": "Open_Account(A)\nOld_Balance = A.balance\nNew_Balance = Old_Balance - 500\nA.balance = New_Balance\nClose_Account(A)\n"
},
{
"code": null,
"e": 87586,
"s": 87574,
"text": "B’s Account"
},
{
"code": null,
"e": 87700,
"s": 87586,
"text": "Open_Account(B)\nOld_Balance = B.balance\nNew_Balance = Old_Balance + 500\nB.balance = New_Balance\nClose_Account(B)\n"
},
{
"code": null,
"e": 87991,
"s": 87700,
"text": "A transaction is a very small unit of a program and it may contain several lowlevel tasks. A transaction in a database system must maintain Atomicity, Consistency, Isolation, and Durability − commonly known as ACID properties − in order to ensure accuracy, completeness, and data integrity."
},
{
"code": null,
"e": 88356,
"s": 87991,
"text": "Atomicity − This property states that a transaction must be treated as an atomic unit, that is, either all of its operations are executed or none. There must be no state in a database where a transaction is left partially completed. States should be defined either before the execution of the transaction or after the execution/abortion/failure of the transaction."
},
{
"code": null,
"e": 88721,
"s": 88356,
"text": "Atomicity − This property states that a transaction must be treated as an atomic unit, that is, either all of its operations are executed or none. There must be no state in a database where a transaction is left partially completed. States should be defined either before the execution of the transaction or after the execution/abortion/failure of the transaction."
},
{
"code": null,
"e": 89044,
"s": 88721,
"text": "Consistency − The database must remain in a consistent state after any transaction. No transaction should have any adverse effect on the data residing in the database. If the database was in a consistent state before the execution of a transaction, it must remain consistent after the execution of the transaction as well."
},
{
"code": null,
"e": 89367,
"s": 89044,
"text": "Consistency − The database must remain in a consistent state after any transaction. No transaction should have any adverse effect on the data residing in the database. If the database was in a consistent state before the execution of a transaction, it must remain consistent after the execution of the transaction as well."
},
{
"code": null,
"e": 89770,
"s": 89367,
"text": "Durability − The database should be durable enough to hold all its latest updates even if the system fails or restarts. If a transaction updates a chunk of data in a database and commits, then the database will hold the modified data. If a transaction commits but the system fails before the data could be written on to the disk, then that data will be updated once the system springs back into action."
},
{
"code": null,
"e": 90173,
"s": 89770,
"text": "Durability − The database should be durable enough to hold all its latest updates even if the system fails or restarts. If a transaction updates a chunk of data in a database and commits, then the database will hold the modified data. If a transaction commits but the system fails before the data could be written on to the disk, then that data will be updated once the system springs back into action."
},
{
"code": null,
"e": 90496,
"s": 90173,
"text": "Isolation − In a database system where more than one transaction are being executed simultaneously and in parallel, the property of isolation states that all the transactions will be carried out and executed as if it is the only transaction in the system. No transaction will affect the existence of any other transaction."
},
{
"code": null,
"e": 90819,
"s": 90496,
"text": "Isolation − In a database system where more than one transaction are being executed simultaneously and in parallel, the property of isolation states that all the transactions will be carried out and executed as if it is the only transaction in the system. No transaction will affect the existence of any other transaction."
},
{
"code": null,
"e": 91031,
"s": 90819,
"text": "When multiple transactions are being executed by the operating system in a multiprogramming environment, there are possibilities that instructions of one transactions are interleaved with some other transaction."
},
{
"code": null,
"e": 91212,
"s": 91031,
"text": "Schedule − A chronological execution sequence of a transaction is called a schedule. A schedule can have many transactions in it, each comprising of a number of instructions/tasks."
},
{
"code": null,
"e": 91393,
"s": 91212,
"text": "Schedule − A chronological execution sequence of a transaction is called a schedule. A schedule can have many transactions in it, each comprising of a number of instructions/tasks."
},
{
"code": null,
"e": 91749,
"s": 91393,
"text": "Serial Schedule − It is a schedule in which transactions are aligned in such a way that one transaction is executed first. When the first transaction completes its cycle, then the next transaction is executed. Transactions are ordered one after the other. This type of schedule is called a serial schedule, as transactions are executed in a serial manner."
},
{
"code": null,
"e": 92105,
"s": 91749,
"text": "Serial Schedule − It is a schedule in which transactions are aligned in such a way that one transaction is executed first. When the first transaction completes its cycle, then the next transaction is executed. Transactions are ordered one after the other. This type of schedule is called a serial schedule, as transactions are executed in a serial manner."
},
{
"code": null,
"e": 92627,
"s": 92105,
"text": "In a multi-transaction environment, serial schedules are considered as a benchmark. The execution sequence of an instruction in a transaction cannot be changed, but two transactions can have their instructions executed in a random fashion. This execution does no harm if two transactions are mutually independent and working on different segments of data; but in case these two transactions are working on the same data, then the results may vary. This ever-varying result may bring the database to an inconsistent state."
},
{
"code": null,
"e": 92797,
"s": 92627,
"text": "To resolve this problem, we allow parallel execution of a transaction schedule, if its transactions are either serializable or have some equivalence relation among them."
},
{
"code": null,
"e": 92853,
"s": 92797,
"text": "An equivalence schedule can be of the following types −"
},
{
"code": null,
"e": 93114,
"s": 92853,
"text": "If two schedules produce the same result after execution, they are said to be result equivalent. They may yield the same result for some value and different results for another set of values. That's why this equivalence is not generally considered significant."
},
{
"code": null,
"e": 93241,
"s": 93114,
"text": "Two schedules would be view equivalence if the transactions in both the schedules perform similar actions in a similar manner."
},
{
"code": null,
"e": 93255,
"s": 93241,
"text": "For example −"
},
{
"code": null,
"e": 93333,
"s": 93255,
"text": "If T reads the initial data in S1, then it also reads the initial data in S2."
},
{
"code": null,
"e": 93411,
"s": 93333,
"text": "If T reads the initial data in S1, then it also reads the initial data in S2."
},
{
"code": null,
"e": 93501,
"s": 93411,
"text": "If T reads the value written by J in S1, then it also reads the value written by J in S2."
},
{
"code": null,
"e": 93591,
"s": 93501,
"text": "If T reads the value written by J in S1, then it also reads the value written by J in S2."
},
{
"code": null,
"e": 93709,
"s": 93591,
"text": "If T performs the final write on the data value in S1, then it also performs the final write on the data value in S2."
},
{
"code": null,
"e": 93827,
"s": 93709,
"text": "If T performs the final write on the data value in S1, then it also performs the final write on the data value in S2."
},
{
"code": null,
"e": 93902,
"s": 93827,
"text": "Two schedules would be conflicting if they have the following properties −"
},
{
"code": null,
"e": 93940,
"s": 93902,
"text": "Both belong to separate transactions."
},
{
"code": null,
"e": 93974,
"s": 93940,
"text": "Both accesses the same data item."
},
{
"code": null,
"e": 94017,
"s": 93974,
"text": "At least one of them is \"write\" operation."
},
{
"code": null,
"e": 94140,
"s": 94017,
"text": "Two schedules having multiple transactions with conflicting operations are said to be conflict equivalent if and only if −"
},
{
"code": null,
"e": 94197,
"s": 94140,
"text": "Both the schedules contain the same set of Transactions."
},
{
"code": null,
"e": 94278,
"s": 94197,
"text": "The order of conflicting pairs of operation is maintained in both the schedules."
},
{
"code": null,
"e": 94457,
"s": 94278,
"text": "Note − View equivalent schedules are view serializable and conflict equivalent schedules are conflict serializable. All conflict serializable schedules are view serializable too."
},
{
"code": null,
"e": 94525,
"s": 94457,
"text": "A transaction in a database can be in one of the following states −"
},
{
"code": null,
"e": 94632,
"s": 94525,
"text": "Active − In this state, the transaction is being executed. This is the initial state of every transaction."
},
{
"code": null,
"e": 94739,
"s": 94632,
"text": "Active − In this state, the transaction is being executed. This is the initial state of every transaction."
},
{
"code": null,
"e": 94859,
"s": 94739,
"text": "Partially Committed − When a transaction executes its final operation, it is said to be in a partially committed state."
},
{
"code": null,
"e": 94979,
"s": 94859,
"text": "Partially Committed − When a transaction executes its final operation, it is said to be in a partially committed state."
},
{
"code": null,
"e": 95151,
"s": 94979,
"text": "Failed − A transaction is said to be in a failed state if any of the checks made by the database recovery system fails. A failed transaction can no longer proceed further."
},
{
"code": null,
"e": 95323,
"s": 95151,
"text": "Failed − A transaction is said to be in a failed state if any of the checks made by the database recovery system fails. A failed transaction can no longer proceed further."
},
{
"code": null,
"e": 95782,
"s": 95323,
"text": "Aborted − If any of the checks fails and the transaction has reached a failed state, then the recovery manager rolls back all its write operations on the database to bring the database back to its original state where it was prior to the execution of the transaction. Transactions in this state are called aborted. The database recovery module can select one of the two operations after a transaction aborts −\n\nRe-start the transaction\nKill the transaction\n\n"
},
{
"code": null,
"e": 96192,
"s": 95782,
"text": "Aborted − If any of the checks fails and the transaction has reached a failed state, then the recovery manager rolls back all its write operations on the database to bring the database back to its original state where it was prior to the execution of the transaction. Transactions in this state are called aborted. The database recovery module can select one of the two operations after a transaction aborts −"
},
{
"code": null,
"e": 96217,
"s": 96192,
"text": "Re-start the transaction"
},
{
"code": null,
"e": 96238,
"s": 96217,
"text": "Kill the transaction"
},
{
"code": null,
"e": 96409,
"s": 96238,
"text": "Committed − If a transaction executes all its operations successfully, it is said to be committed. All its effects are now permanently established on the database system."
},
{
"code": null,
"e": 96580,
"s": 96409,
"text": "Committed − If a transaction executes all its operations successfully, it is said to be committed. All its effects are now permanently established on the database system."
},
{
"code": null,
"e": 96934,
"s": 96580,
"text": "In a multiprogramming environment where multiple transactions can be executed simultaneously, it is highly important to control the concurrency of transactions. We have concurrency control protocols to ensure atomicity, isolation, and serializability of concurrent transactions. Concurrency control protocols can be broadly divided into two categories −"
},
{
"code": null,
"e": 96955,
"s": 96934,
"text": "Lock based protocols"
},
{
"code": null,
"e": 96982,
"s": 96955,
"text": "Time stamp based protocols"
},
{
"code": null,
"e": 97171,
"s": 96982,
"text": "Database systems equipped with lock-based protocols use a mechanism by which any transaction cannot read or write data until it acquires an appropriate lock on it. Locks are of two kinds −"
},
{
"code": null,
"e": 97263,
"s": 97171,
"text": "Binary Locks − A lock on a data item can be in two states; it is either locked or unlocked."
},
{
"code": null,
"e": 97355,
"s": 97263,
"text": "Binary Locks − A lock on a data item can be in two states; it is either locked or unlocked."
},
{
"code": null,
"e": 97723,
"s": 97355,
"text": "Shared/exclusive − This type of locking mechanism differentiates the locks based on their uses. If a lock is acquired on a data item to perform a write operation, it is an exclusive lock. Allowing more than one transaction to write on the same data item would lead the database into an inconsistent state. Read locks are shared because no data value is being changed."
},
{
"code": null,
"e": 98091,
"s": 97723,
"text": "Shared/exclusive − This type of locking mechanism differentiates the locks based on their uses. If a lock is acquired on a data item to perform a write operation, it is an exclusive lock. Allowing more than one transaction to write on the same data item would lead the database into an inconsistent state. Read locks are shared because no data value is being changed."
},
{
"code": null,
"e": 98142,
"s": 98091,
"text": "There are four types of lock protocols available −"
},
{
"code": null,
"e": 98345,
"s": 98142,
"text": "Simplistic lock-based protocols allow transactions to obtain a lock on every object before a 'write' operation is performed. Transactions may unlock the data item after completing the ‘write’ operation."
},
{
"code": null,
"e": 98779,
"s": 98345,
"text": "Pre-claiming protocols evaluate their operations and create a list of data items on which they need locks. Before initiating an execution, the transaction requests the system for all the locks it needs beforehand. If all the locks are granted, the transaction executes and releases all the locks when all its operations are over. If all the locks are not granted, the transaction rolls back and waits until all the locks are granted."
},
{
"code": null,
"e": 99207,
"s": 98779,
"text": "This locking protocol divides the execution phase of a transaction into three parts. In the first part, when the transaction starts executing, it seeks permission for the locks it requires. The second part is where the transaction acquires all the locks. As soon as the transaction releases its first lock, the third phase starts. In this phase, the transaction cannot demand any new locks; it only releases the acquired locks."
},
{
"code": null,
"e": 99411,
"s": 99207,
"text": "Two-phase locking has two phases, one is growing, where all the locks are being acquired by the transaction; and the second phase is shrinking, where the locks held by the transaction are being released."
},
{
"code": null,
"e": 99543,
"s": 99411,
"text": "To claim an exclusive (write) lock, a transaction must first acquire a shared (read) lock and then upgrade it to an exclusive lock."
},
{
"code": null,
"e": 99853,
"s": 99543,
"text": "The first phase of Strict-2PL is same as 2PL. After acquiring all the locks in the first phase, the transaction continues to execute normally. But in contrast to 2PL, Strict-2PL does not release a lock after using it. Strict-2PL holds all the locks until the commit point and releases all the locks at a time."
},
{
"code": null,
"e": 99907,
"s": 99853,
"text": "Strict-2PL does not have cascading abort as 2PL does."
},
{
"code": null,
"e": 100057,
"s": 99907,
"text": "The most commonly used concurrency protocol is the timestamp based protocol. This protocol uses either system time or logical counter as a timestamp."
},
{
"code": null,
"e": 100255,
"s": 100057,
"text": "Lock-based protocols manage the order between the conflicting pairs among transactions at the time of execution, whereas timestamp-based protocols start working as soon as a transaction is created."
},
{
"code": null,
"e": 100609,
"s": 100255,
"text": "Every transaction has a timestamp associated with it, and the ordering is determined by the age of the transaction. A transaction created at 0002 clock time would be older than all other transactions that come after it. For example, any transaction 'y' entering the system at 0004 is two seconds younger and the priority would be given to the older one."
},
{
"code": null,
"e": 100783,
"s": 100609,
"text": "In addition, every data item is given the latest read and write-timestamp. This lets the system know when the last ‘read and write’ operation was performed on the data item."
},
{
"code": null,
"e": 101065,
"s": 100783,
"text": "The timestamp-ordering protocol ensures serializability among transactions in their conflicting read and write operations. This is the responsibility of the protocol system that the conflicting pair of tasks should be executed according to the timestamp values of the transactions."
},
{
"code": null,
"e": 101119,
"s": 101065,
"text": "The timestamp of transaction Ti is denoted as TS(Ti)."
},
{
"code": null,
"e": 101180,
"s": 101119,
"text": "Read time-stamp of data-item X is denoted by R-timestamp(X)."
},
{
"code": null,
"e": 101242,
"s": 101180,
"text": "Write time-stamp of data-item X is denoted by W-timestamp(X)."
},
{
"code": null,
"e": 101289,
"s": 101242,
"text": "Timestamp ordering protocol works as follows −"
},
{
"code": null,
"e": 101338,
"s": 101289,
"text": "If a transaction Ti issues a read(X) operation −"
},
{
"code": null,
"e": 101387,
"s": 101338,
"text": "If a transaction Ti issues a read(X) operation −"
},
{
"code": null,
"e": 101437,
"s": 101387,
"text": "If TS(Ti) < W-timestamp(X)\n\nOperation rejected.\n\n"
},
{
"code": null,
"e": 101457,
"s": 101437,
"text": "Operation rejected."
},
{
"code": null,
"e": 101508,
"s": 101457,
"text": "If TS(Ti) >= W-timestamp(X)\n\nOperation executed.\n\n"
},
{
"code": null,
"e": 101528,
"s": 101508,
"text": "Operation executed."
},
{
"code": null,
"e": 101562,
"s": 101528,
"text": "All data-item timestamps updated."
},
{
"code": null,
"e": 101612,
"s": 101562,
"text": "If a transaction Ti issues a write(X) operation −"
},
{
"code": null,
"e": 101662,
"s": 101612,
"text": "If a transaction Ti issues a write(X) operation −"
},
{
"code": null,
"e": 101689,
"s": 101662,
"text": "If TS(Ti) < R-timestamp(X)"
},
{
"code": null,
"e": 101709,
"s": 101689,
"text": "Operation rejected."
},
{
"code": null,
"e": 101736,
"s": 101709,
"text": "If TS(Ti) < W-timestamp(X)"
},
{
"code": null,
"e": 101775,
"s": 101736,
"text": "Operation rejected and Ti rolled back."
},
{
"code": null,
"e": 101806,
"s": 101775,
"text": "Otherwise, operation executed."
},
{
"code": null,
"e": 101905,
"s": 101806,
"text": "This rule states if TS(Ti) < W-timestamp(X), then the operation is rejected and Ti is rolled back."
},
{
"code": null,
"e": 101987,
"s": 101905,
"text": "Time-stamp ordering rules can be modified to make the schedule view serializable."
},
{
"code": null,
"e": 102062,
"s": 101987,
"text": "Instead of making Ti rolled back, the 'write' operation itself is ignored."
},
{
"code": null,
"e": 102252,
"s": 102062,
"text": "In a multi-process system, deadlock is an unwanted situation that arises in a shared resource environment, where a process indefinitely waits for a resource that is held by another process."
},
{
"code": null,
"e": 102667,
"s": 102252,
"text": "For example, assume a set of transactions {T0, T1, T2, ...,Tn}. T0 needs a resource X to complete its task. Resource X is held by T1, and T1 is waiting for a resource Y, which is held by T2. T2 is waiting for resource Z, which is held by T0. Thus, all the processes wait for each other to release resources. In this situation, none of the processes can finish their task. This situation is known as a deadlock."
},
{
"code": null,
"e": 102827,
"s": 102667,
"text": "Deadlocks are not healthy for a system. In case a system is stuck in a deadlock, the transactions involved in the deadlock are either rolled back or restarted."
},
{
"code": null,
"e": 103161,
"s": 102827,
"text": "To prevent any deadlock situation in the system, the DBMS aggressively inspects all the operations, where transactions are about to execute. The DBMS inspects the operations and analyzes if they can create a deadlock situation. If it finds that a deadlock situation might occur, then that transaction is never allowed to be executed."
},
{
"code": null,
"e": 103300,
"s": 103161,
"text": "There are deadlock prevention schemes that use timestamp ordering mechanism of transactions in order to predetermine a deadlock situation."
},
{
"code": null,
"e": 103490,
"s": 103300,
"text": "In this scheme, if a transaction requests to lock a resource (data item), which is already held with a conflicting lock by another transaction, then one of the two possibilities may occur −"
},
{
"code": null,
"e": 103644,
"s": 103490,
"text": "If TS(Ti) < TS(Tj) − that is Ti, which is requesting a conflicting lock, is older than Tj − then Ti is allowed to wait until the data-item is available."
},
{
"code": null,
"e": 103798,
"s": 103644,
"text": "If TS(Ti) < TS(Tj) − that is Ti, which is requesting a conflicting lock, is older than Tj − then Ti is allowed to wait until the data-item is available."
},
{
"code": null,
"e": 103937,
"s": 103798,
"text": "If TS(Ti) > TS(tj) − that is Ti is younger than Tj − then Ti dies. Ti is restarted later with a random delay but with the same timestamp."
},
{
"code": null,
"e": 104076,
"s": 103937,
"text": "If TS(Ti) > TS(tj) − that is Ti is younger than Tj − then Ti dies. Ti is restarted later with a random delay but with the same timestamp."
},
{
"code": null,
"e": 104152,
"s": 104076,
"text": "This scheme allows the older transaction to wait but kills the younger one."
},
{
"code": null,
"e": 104340,
"s": 104152,
"text": "In this scheme, if a transaction requests to lock a resource (data item), which is already held with conflicting lock by some another transaction, one of the two possibilities may occur −"
},
{
"code": null,
"e": 104491,
"s": 104340,
"text": "If TS(Ti) < TS(Tj), then Ti forces Tj to be rolled back − that is Ti wounds Tj. Tj is restarted later with a random delay but with the same timestamp."
},
{
"code": null,
"e": 104642,
"s": 104491,
"text": "If TS(Ti) < TS(Tj), then Ti forces Tj to be rolled back − that is Ti wounds Tj. Tj is restarted later with a random delay but with the same timestamp."
},
{
"code": null,
"e": 104721,
"s": 104642,
"text": "If TS(Ti) > TS(Tj), then Ti is forced to wait until the resource is available."
},
{
"code": null,
"e": 104800,
"s": 104721,
"text": "If TS(Ti) > TS(Tj), then Ti is forced to wait until the resource is available."
},
{
"code": null,
"e": 104999,
"s": 104800,
"text": "This scheme, allows the younger transaction to wait; but when an older transaction requests an item held by a younger one, the older transaction forces the younger one to abort and release the item."
},
{
"code": null,
"e": 105086,
"s": 104999,
"text": "In both the cases, the transaction that enters the system at a later stage is aborted."
},
{
"code": null,
"e": 105466,
"s": 105086,
"text": "Aborting a transaction is not always a practical approach. Instead, deadlock avoidance mechanisms can be used to detect any deadlock situation in advance. Methods like \"wait-for graph\" are available but they are suitable for only those systems where transactions are lightweight having fewer instances of resource. In a bulky system, deadlock prevention techniques may work well."
},
{
"code": null,
"e": 105843,
"s": 105466,
"text": "This is a simple method available to track if any deadlock situation may arise. For each transaction entering into the system, a node is created. When a transaction Ti requests for a lock on an item, say X, which is held by some other transaction Tj, a directed edge is created from Ti to Tj. If Tj releases item X, the edge between them is dropped and Ti locks the data item."
},
{
"code": null,
"e": 106011,
"s": 105843,
"text": "The system maintains this wait-for graph for every transaction waiting for some data items held by others. The system keeps checking if there's any cycle in the graph."
},
{
"code": null,
"e": 106066,
"s": 106011,
"text": "Here, we can use any of the two following approaches −"
},
{
"code": null,
"e": 106294,
"s": 106066,
"text": "First, do not allow any request for an item, which is already locked by another transaction. This is not always feasible and may cause starvation, where a transaction indefinitely waits for a data item and can never acquire it."
},
{
"code": null,
"e": 106522,
"s": 106294,
"text": "First, do not allow any request for an item, which is already locked by another transaction. This is not always feasible and may cause starvation, where a transaction indefinitely waits for a data item and can never acquire it."
},
{
"code": null,
"e": 106865,
"s": 106522,
"text": "The second option is to roll back one of the transactions. It is not always feasible to roll back the younger transaction, as it may be important than the older one. With the help of some relative algorithm, a transaction is chosen, which is to be aborted. This transaction is known as the victim and the process is known as victim selection."
},
{
"code": null,
"e": 107208,
"s": 106865,
"text": "The second option is to roll back one of the transactions. It is not always feasible to roll back the younger transaction, as it may be important than the older one. With the help of some relative algorithm, a transaction is chosen, which is to be aborted. This transaction is known as the victim and the process is known as victim selection."
},
{
"code": null,
"e": 107607,
"s": 107208,
"text": "A volatile storage like RAM stores all the active logs, disk buffers, and related data. In addition, it stores all the transactions that are being currently executed. What happens if such a volatile storage crashes abruptly? It would obviously take away all the logs and active copies of the database. It makes recovery almost impossible, as everything that is required to recover the data is lost."
},
{
"code": null,
"e": 107681,
"s": 107607,
"text": "Following techniques may be adopted in case of loss of volatile storage −"
},
{
"code": null,
"e": 107781,
"s": 107681,
"text": "We can have checkpoints at multiple stages so as to save the contents of the database periodically."
},
{
"code": null,
"e": 107881,
"s": 107781,
"text": "We can have checkpoints at multiple stages so as to save the contents of the database periodically."
},
{
"code": null,
"e": 108052,
"s": 107881,
"text": "A state of active database in the volatile memory can be periodically dumped onto a stable storage, which may also contain logs and active transactions and buffer blocks."
},
{
"code": null,
"e": 108223,
"s": 108052,
"text": "A state of active database in the volatile memory can be periodically dumped onto a stable storage, which may also contain logs and active transactions and buffer blocks."
},
{
"code": null,
"e": 108345,
"s": 108223,
"text": "<dump> can be marked on a log file, whenever the database contents are dumped from a non-volatile memory to a stable one."
},
{
"code": null,
"e": 108467,
"s": 108345,
"text": "<dump> can be marked on a log file, whenever the database contents are dumped from a non-volatile memory to a stable one."
},
{
"code": null,
"e": 108540,
"s": 108467,
"text": "When the system recovers from a failure, it can restore the latest dump."
},
{
"code": null,
"e": 108613,
"s": 108540,
"text": "When the system recovers from a failure, it can restore the latest dump."
},
{
"code": null,
"e": 108674,
"s": 108613,
"text": "It can maintain a redo-list and an undo-list as checkpoints."
},
{
"code": null,
"e": 108735,
"s": 108674,
"text": "It can maintain a redo-list and an undo-list as checkpoints."
},
{
"code": null,
"e": 108859,
"s": 108735,
"text": "It can recover the system by consulting undo-redo lists to restore the state of all transactions up to the last checkpoint."
},
{
"code": null,
"e": 108983,
"s": 108859,
"text": "It can recover the system by consulting undo-redo lists to restore the state of all transactions up to the last checkpoint."
},
{
"code": null,
"e": 109230,
"s": 108983,
"text": "A catastrophic failure is one where a stable, secondary storage device gets corrupt. With the storage device, all the valuable data that is stored inside is lost. We have two different strategies to recover data from such a catastrophic failure −"
},
{
"code": null,
"e": 109373,
"s": 109230,
"text": "Remote backup &minu; Here a backup copy of the database is stored at a remote location from where it can be restored in case of a catastrophe."
},
{
"code": null,
"e": 109516,
"s": 109373,
"text": "Remote backup &minu; Here a backup copy of the database is stored at a remote location from where it can be restored in case of a catastrophe."
},
{
"code": null,
"e": 109715,
"s": 109516,
"text": "Alternatively, database backups can be taken on magnetic tapes and stored at a safer place. This backup can later be transferred onto a freshly installed database to bring it to the point of backup."
},
{
"code": null,
"e": 109914,
"s": 109715,
"text": "Alternatively, database backups can be taken on magnetic tapes and stored at a safer place. This backup can later be transferred onto a freshly installed database to bring it to the point of backup."
},
{
"code": null,
"e": 110299,
"s": 109914,
"text": "Grown-up databases are too bulky to be frequently backed up. In such cases, we have techniques where we can restore a database just by looking at its logs. So, all that we need to do here is to take a backup of all the logs at frequent intervals of time. The database can be backed up once a week, and the logs being very small can be backed up every day or as frequently as possible."
},
{
"code": null,
"e": 110520,
"s": 110299,
"text": "Remote backup provides a sense of security in case the primary location where the database is located gets destroyed. Remote backup can be offline or real-time or online. In case it is offline, it is maintained manually."
},
{
"code": null,
"e": 110850,
"s": 110520,
"text": "Online backup systems are more real-time and lifesavers for database administrators and investors. An online backup system is a mechanism where every bit of the real-time data is backed up simultaneously at two distant places. One of them is directly connected to the system and the other one is kept at a remote place as backup."
},
{
"code": null,
"e": 111060,
"s": 110850,
"text": "As soon as the primary database storage fails, the backup system senses the failure and switches the user system to the remote storage. Sometimes this is so instant that the users can’t even realize a failure."
},
{
"code": null,
"e": 111421,
"s": 111060,
"text": "DBMS is a highly complex system with hundreds of transactions being executed every second. The durability and robustness of a DBMS depends on its complex architecture and its underlying hardware and system software. If it fails or crashes amid transactions, it is expected that the system would follow some sort of algorithm or techniques to recover lost data."
},
{
"code": null,
"e": 111522,
"s": 111421,
"text": "To see where the problem has occurred, we generalize a failure into various categories, as follows −"
},
{
"code": null,
"e": 111725,
"s": 111522,
"text": "A transaction has to abort when it fails to execute or when it reaches a point from where it can’t go any further. This is called transaction failure where only a few transactions or processes are hurt."
},
{
"code": null,
"e": 111770,
"s": 111725,
"text": "Reasons for a transaction failure could be −"
},
{
"code": null,
"e": 111887,
"s": 111770,
"text": "Logical errors − Where a transaction cannot complete because it has some code error or any internal error condition."
},
{
"code": null,
"e": 112004,
"s": 111887,
"text": "Logical errors − Where a transaction cannot complete because it has some code error or any internal error condition."
},
{
"code": null,
"e": 112284,
"s": 112004,
"text": "System errors − Where the database system itself terminates an active transaction because the DBMS is not able to execute it, or it has to stop because of some system condition. For example, in case of deadlock or resource unavailability, the system aborts an active transaction."
},
{
"code": null,
"e": 112564,
"s": 112284,
"text": "System errors − Where the database system itself terminates an active transaction because the DBMS is not able to execute it, or it has to stop because of some system condition. For example, in case of deadlock or resource unavailability, the system aborts an active transaction."
},
{
"code": null,
"e": 112793,
"s": 112564,
"text": "There are problems − external to the system − that may cause the system to stop abruptly and cause the system to crash. For example, interruptions in power supply may cause the failure of underlying hardware or software failure."
},
{
"code": null,
"e": 112839,
"s": 112793,
"text": "Examples may include operating system errors."
},
{
"code": null,
"e": 112968,
"s": 112839,
"text": "In early days of technology evolution, it was a common problem where hard-disk drives or storage drives used to fail frequently."
},
{
"code": null,
"e": 113128,
"s": 112968,
"text": "Disk failures include formation of bad sectors, unreachability to the disk, disk head crash or any other failure, which destroys all or a part of disk storage."
},
{
"code": null,
"e": 113243,
"s": 113128,
"text": "We have already described the storage system. In brief, the storage structure can be divided into two categories −"
},
{
"code": null,
"e": 113585,
"s": 113243,
"text": "Volatile storage − As the name suggests, a volatile storage cannot survive system crashes. Volatile storage devices are placed very close to the CPU; normally they are embedded onto the chipset itself. For example, main memory and cache memory are examples of volatile storage. They are fast but can store only a small amount of information."
},
{
"code": null,
"e": 113927,
"s": 113585,
"text": "Volatile storage − As the name suggests, a volatile storage cannot survive system crashes. Volatile storage devices are placed very close to the CPU; normally they are embedded onto the chipset itself. For example, main memory and cache memory are examples of volatile storage. They are fast but can store only a small amount of information."
},
{
"code": null,
"e": 114175,
"s": 113927,
"text": "Non-volatile storage − These memories are made to survive system crashes. They are huge in data storage capacity, but slower in accessibility. Examples may include hard-disks, magnetic tapes, flash memory, and non-volatile (battery backed up) RAM."
},
{
"code": null,
"e": 114423,
"s": 114175,
"text": "Non-volatile storage − These memories are made to survive system crashes. They are huge in data storage capacity, but slower in accessibility. Examples may include hard-disks, magnetic tapes, flash memory, and non-volatile (battery backed up) RAM."
},
{
"code": null,
"e": 114783,
"s": 114423,
"text": "When a system crashes, it may have several transactions being executed and various files opened for them to modify the data items. Transactions are made of various operations, which are atomic in nature. But according to ACID properties of DBMS, atomicity of transactions as a whole must be maintained, that is, either all the operations are executed or none."
},
{
"code": null,
"e": 114853,
"s": 114783,
"text": "When a DBMS recovers from a crash, it should maintain the following −"
},
{
"code": null,
"e": 114932,
"s": 114853,
"text": "It should check the states of all the transactions, which were being executed."
},
{
"code": null,
"e": 115011,
"s": 114932,
"text": "It should check the states of all the transactions, which were being executed."
},
{
"code": null,
"e": 115133,
"s": 115011,
"text": "A transaction may be in the middle of some operation; the DBMS must ensure the atomicity of the transaction in this case."
},
{
"code": null,
"e": 115255,
"s": 115133,
"text": "A transaction may be in the middle of some operation; the DBMS must ensure the atomicity of the transaction in this case."
},
{
"code": null,
"e": 115347,
"s": 115255,
"text": "It should check whether the transaction can be completed now or it needs to be rolled back."
},
{
"code": null,
"e": 115439,
"s": 115347,
"text": "It should check whether the transaction can be completed now or it needs to be rolled back."
},
{
"code": null,
"e": 115516,
"s": 115439,
"text": "No transactions would be allowed to leave the DBMS in an inconsistent state."
},
{
"code": null,
"e": 115593,
"s": 115516,
"text": "No transactions would be allowed to leave the DBMS in an inconsistent state."
},
{
"code": null,
"e": 115720,
"s": 115593,
"text": "There are two types of techniques, which can help a DBMS in recovering as well as maintaining the atomicity of a transaction −"
},
{
"code": null,
"e": 115844,
"s": 115720,
"text": "Maintaining the logs of each transaction, and writing them onto some stable storage before actually modifying the database."
},
{
"code": null,
"e": 115968,
"s": 115844,
"text": "Maintaining the logs of each transaction, and writing them onto some stable storage before actually modifying the database."
},
{
"code": null,
"e": 116087,
"s": 115968,
"text": "Maintaining shadow paging, where the changes are done on a volatile memory, and later, the actual database is updated."
},
{
"code": null,
"e": 116206,
"s": 116087,
"text": "Maintaining shadow paging, where the changes are done on a volatile memory, and later, the actual database is updated."
},
{
"code": null,
"e": 116435,
"s": 116206,
"text": "Log is a sequence of records, which maintains the records of actions performed by a transaction. It is important that the logs are written prior to the actual modification and stored on a stable storage media, which is failsafe."
},
{
"code": null,
"e": 116473,
"s": 116435,
"text": "Log-based recovery works as follows −"
},
{
"code": null,
"e": 116521,
"s": 116473,
"text": "The log file is kept on a stable storage media."
},
{
"code": null,
"e": 116569,
"s": 116521,
"text": "The log file is kept on a stable storage media."
},
{
"code": null,
"e": 116654,
"s": 116569,
"text": "When a transaction enters the system and starts execution, it writes a log about it."
},
{
"code": null,
"e": 116739,
"s": 116654,
"text": "When a transaction enters the system and starts execution, it writes a log about it."
},
{
"code": null,
"e": 116752,
"s": 116739,
"text": "<Tn, Start>\n"
},
{
"code": null,
"e": 116820,
"s": 116752,
"text": "When the transaction modifies an item X, it write logs as follows −"
},
{
"code": null,
"e": 116888,
"s": 116820,
"text": "When the transaction modifies an item X, it write logs as follows −"
},
{
"code": null,
"e": 116905,
"s": 116888,
"text": "<Tn, X, V1, V2>\n"
},
{
"code": null,
"e": 116960,
"s": 116905,
"text": "It reads Tn has changed the value of X, from V1 to V2."
},
{
"code": null,
"e": 117001,
"s": 116960,
"text": "When the transaction finishes, it logs −"
},
{
"code": null,
"e": 117015,
"s": 117001,
"text": "<Tn, commit>\n"
},
{
"code": null,
"e": 117067,
"s": 117015,
"text": "The database can be modified using two approaches −"
},
{
"code": null,
"e": 117202,
"s": 117067,
"text": "Deferred database modification − All logs are written on to the stable storage and the database is updated when a transaction commits."
},
{
"code": null,
"e": 117337,
"s": 117202,
"text": "Deferred database modification − All logs are written on to the stable storage and the database is updated when a transaction commits."
},
{
"code": null,
"e": 117490,
"s": 117337,
"text": "Immediate database modification − Each log follows an actual database modification. That is, the database is modified immediately after every operation."
},
{
"code": null,
"e": 117643,
"s": 117490,
"text": "Immediate database modification − Each log follows an actual database modification. That is, the database is modified immediately after every operation."
},
{
"code": null,
"e": 117927,
"s": 117643,
"text": "When more than one transaction are being executed in parallel, the logs are interleaved. At the time of recovery, it would become hard for the recovery system to backtrack all logs, and then start recovering. To ease this situation, most modern DBMS use the concept of 'checkpoints'."
},
{
"code": null,
"e": 118360,
"s": 117927,
"text": "Keeping and maintaining logs in real time and in real environment may fill out all the memory space available in the system. As time passes, the log file may grow too big to be handled at all. Checkpoint is a mechanism where all the previous logs are removed from the system and stored permanently in a storage disk. Checkpoint declares a point before which the DBMS was in consistent state, and all the transactions were committed."
},
{
"code": null,
"e": 118462,
"s": 118360,
"text": "When a system with concurrent transactions crashes and recovers, it behaves in the following manner −"
},
{
"code": null,
"e": 118544,
"s": 118462,
"text": "The recovery system reads the logs backwards from the end to the last checkpoint."
},
{
"code": null,
"e": 118626,
"s": 118544,
"text": "The recovery system reads the logs backwards from the end to the last checkpoint."
},
{
"code": null,
"e": 118680,
"s": 118626,
"text": "It maintains two lists, an undo-list and a redo-list."
},
{
"code": null,
"e": 118734,
"s": 118680,
"text": "It maintains two lists, an undo-list and a redo-list."
},
{
"code": null,
"e": 118866,
"s": 118734,
"text": "If the recovery system sees a log with <Tn, Start> and <Tn, Commit> or just <Tn, Commit>, it puts the transaction in the redo-list."
},
{
"code": null,
"e": 118998,
"s": 118866,
"text": "If the recovery system sees a log with <Tn, Start> and <Tn, Commit> or just <Tn, Commit>, it puts the transaction in the redo-list."
},
{
"code": null,
"e": 119121,
"s": 118998,
"text": "If the recovery system sees a log with <Tn, Start> but no commit or abort log found, it puts the transaction in undo-list."
},
{
"code": null,
"e": 119244,
"s": 119121,
"text": "If the recovery system sees a log with <Tn, Start> but no commit or abort log found, it puts the transaction in undo-list."
},
{
"code": null,
"e": 119442,
"s": 119244,
"text": "All the transactions in the undo-list are then undone and their logs are removed. All the transactions in the redo-list and their previous logs are removed and then redone before saving their logs."
},
{
"code": null,
"e": 119479,
"s": 119442,
"text": "\n 178 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 119498,
"s": 119479,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 119533,
"s": 119498,
"text": "\n 194 Lectures \n 16 hours \n"
},
{
"code": null,
"e": 119552,
"s": 119533,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 119559,
"s": 119552,
"text": " Print"
},
{
"code": null,
"e": 119570,
"s": 119559,
"text": " Add Notes"
}
] |
Node.js querystring.parse() Method | 08 Oct, 2021
The querystring.parse() method is used to parse a URL query string into an object that contains the key and pair values of the query URL. The object returned does not inherit prototypes from the JavaScript object, therefore usual Object methods will not work. During parsing, the UTF-8 encoding format is assumed unless there is an alternative character encoding format. To decode alternative character encoding, the decodeURIComponent option has to be specified.
Syntax:
querystring.parse( str[, sep[, eq[, options]]]) )
Parameters: This function accepts four parameters as mentioned above and described below:
str: It is a String that specifies the URL query that has to be parsed.
sep: It is a String that specifies the substring used to delimit the key and value pairs in the specified query string. The default value is “&”.
eq: It is a String that specifies the substring used to delimit keys and values in the specified query string. The default value is “=”.
options: It is an object which can be used to modify the behavior of the method. It has the following parameters: decodeURIComponent: It is a function that would be used to decode percent-encoded characters in the query string. The default value is querystring.unescape().maxKeys: It is a number which specifies the maximum number of keys that should be parsed from the query string. A value of “0” would remove all the counting limits. The default value is “1000”.
decodeURIComponent: It is a function that would be used to decode percent-encoded characters in the query string. The default value is querystring.unescape().
maxKeys: It is a number which specifies the maximum number of keys that should be parsed from the query string. A value of “0” would remove all the counting limits. The default value is “1000”.
Return Value: It returns an object that has the key and value pairs parsed from the query string.
Below examples illustrate the querystring.parse() method in Node.js:
Example 1:
Node.js
// Import the querystring moduleconst querystring = require("querystring"); // Specify the URL query string// to be parsedlet urlQuery = "username=user1&units=kgs&units=pounds&permission=false"; // Use the parse() method on the stringlet parsedObject = querystring.parse(urlQuery); console.log("Parsed Query:", parsedObject); // Use the parse() method on the string// with sep as `&&` and eq as `-`urlQuery = "username-user1&&units-kgs&&units-pounds&&permission-false";parsedObject = querystring.parse(urlQuery, "&&", "-"); console.log("\nParsed Query:", parsedObject);
Output:
Parsed Query: [Object: null prototype] {
username: 'user1',
units: [ 'kgs', 'pounds' ],
permission: 'false'
}
Parsed Query: [Object: null prototype] {
username: 'user1',
units: [ 'kgs', 'pounds' ],
permission: 'false'
}
Example 2:
Node.js
// Import the querystring moduleconst querystring = require("querystring"); // Specify the URL query string// to be parsedlet urlQuery = "user=admin&articles=1&articles=2&articles=3&access=true"; // Use the parse() method on the string// with default valueslet parsedObject = querystring.parse(urlQuery, "&", "="); console.log("Parsed Query:", parsedObject); // Use the parse() method on the string// with maxKeys set to 1parsedObject = querystring.parse(urlQuery, "&", "=", { maxKeys: 1 }); console.log("\nParsed Query:", parsedObject); // Use the parse() method on the string// with maxKeys set to 2parsedObject = querystring.parse(urlQuery, "&", "=", { maxKeys: 2 }); console.log("\nParsed Query:", parsedObject); // Use the parse() method on the string// with maxKeys set to 0 (no limits)parsedObject = querystring.parse(urlQuery, "&", "=", { maxKeys: 0 }); console.log("\nParsed Query:", parsedObject);
Output:
Parsed Query: [Object: null prototype] {
user: 'admin',
articles: [ '1', '2', '3' ],
access: 'true'
}
Parsed Query: [Object: null prototype] { user: 'admin' }
Parsed Query: [Object: null prototype]
{ user: 'admin', articles: '1' }
Parsed Query: [Object: null prototype] {
user: 'admin',
articles: [ '1', '2', '3' ],
access: 'true'
}
Reference: https://nodejs.org/api/querystring.html#querystring_querystring_parse_str_sep_eq_options
Node.js- querystring-Module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to update NPM ?
Difference between promise and async await in Node.js
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 493,
"s": 28,
"text": "The querystring.parse() method is used to parse a URL query string into an object that contains the key and pair values of the query URL. The object returned does not inherit prototypes from the JavaScript object, therefore usual Object methods will not work. During parsing, the UTF-8 encoding format is assumed unless there is an alternative character encoding format. To decode alternative character encoding, the decodeURIComponent option has to be specified. "
},
{
"code": null,
"e": 502,
"s": 493,
"text": "Syntax: "
},
{
"code": null,
"e": 553,
"s": 502,
"text": "querystring.parse( str[, sep[, eq[, options]]]) )\n"
},
{
"code": null,
"e": 644,
"s": 553,
"text": "Parameters: This function accepts four parameters as mentioned above and described below: "
},
{
"code": null,
"e": 716,
"s": 644,
"text": "str: It is a String that specifies the URL query that has to be parsed."
},
{
"code": null,
"e": 862,
"s": 716,
"text": "sep: It is a String that specifies the substring used to delimit the key and value pairs in the specified query string. The default value is “&”."
},
{
"code": null,
"e": 999,
"s": 862,
"text": "eq: It is a String that specifies the substring used to delimit keys and values in the specified query string. The default value is “=”."
},
{
"code": null,
"e": 1465,
"s": 999,
"text": "options: It is an object which can be used to modify the behavior of the method. It has the following parameters: decodeURIComponent: It is a function that would be used to decode percent-encoded characters in the query string. The default value is querystring.unescape().maxKeys: It is a number which specifies the maximum number of keys that should be parsed from the query string. A value of “0” would remove all the counting limits. The default value is “1000”."
},
{
"code": null,
"e": 1624,
"s": 1465,
"text": "decodeURIComponent: It is a function that would be used to decode percent-encoded characters in the query string. The default value is querystring.unescape()."
},
{
"code": null,
"e": 1818,
"s": 1624,
"text": "maxKeys: It is a number which specifies the maximum number of keys that should be parsed from the query string. A value of “0” would remove all the counting limits. The default value is “1000”."
},
{
"code": null,
"e": 1916,
"s": 1818,
"text": "Return Value: It returns an object that has the key and value pairs parsed from the query string."
},
{
"code": null,
"e": 1985,
"s": 1916,
"text": "Below examples illustrate the querystring.parse() method in Node.js:"
},
{
"code": null,
"e": 1996,
"s": 1985,
"text": "Example 1:"
},
{
"code": null,
"e": 2004,
"s": 1996,
"text": "Node.js"
},
{
"code": "// Import the querystring moduleconst querystring = require(\"querystring\"); // Specify the URL query string// to be parsedlet urlQuery = \"username=user1&units=kgs&units=pounds&permission=false\"; // Use the parse() method on the stringlet parsedObject = querystring.parse(urlQuery); console.log(\"Parsed Query:\", parsedObject); // Use the parse() method on the string// with sep as `&&` and eq as `-`urlQuery = \"username-user1&&units-kgs&&units-pounds&&permission-false\";parsedObject = querystring.parse(urlQuery, \"&&\", \"-\"); console.log(\"\\nParsed Query:\", parsedObject);",
"e": 2583,
"s": 2004,
"text": null
},
{
"code": null,
"e": 2591,
"s": 2583,
"text": "Output:"
},
{
"code": null,
"e": 2825,
"s": 2591,
"text": "Parsed Query: [Object: null prototype] {\n username: 'user1',\n units: [ 'kgs', 'pounds' ],\n permission: 'false'\n}\n\nParsed Query: [Object: null prototype] {\n username: 'user1',\n units: [ 'kgs', 'pounds' ],\n permission: 'false'\n}\n"
},
{
"code": null,
"e": 2836,
"s": 2825,
"text": "Example 2:"
},
{
"code": null,
"e": 2844,
"s": 2836,
"text": "Node.js"
},
{
"code": "// Import the querystring moduleconst querystring = require(\"querystring\"); // Specify the URL query string// to be parsedlet urlQuery = \"user=admin&articles=1&articles=2&articles=3&access=true\"; // Use the parse() method on the string// with default valueslet parsedObject = querystring.parse(urlQuery, \"&\", \"=\"); console.log(\"Parsed Query:\", parsedObject); // Use the parse() method on the string// with maxKeys set to 1parsedObject = querystring.parse(urlQuery, \"&\", \"=\", { maxKeys: 1 }); console.log(\"\\nParsed Query:\", parsedObject); // Use the parse() method on the string// with maxKeys set to 2parsedObject = querystring.parse(urlQuery, \"&\", \"=\", { maxKeys: 2 }); console.log(\"\\nParsed Query:\", parsedObject); // Use the parse() method on the string// with maxKeys set to 0 (no limits)parsedObject = querystring.parse(urlQuery, \"&\", \"=\", { maxKeys: 0 }); console.log(\"\\nParsed Query:\", parsedObject);",
"e": 3769,
"s": 2844,
"text": null
},
{
"code": null,
"e": 3777,
"s": 3769,
"text": "Output:"
},
{
"code": null,
"e": 4141,
"s": 3777,
"text": "Parsed Query: [Object: null prototype] {\n user: 'admin',\n articles: [ '1', '2', '3' ],\n access: 'true'\n}\n\nParsed Query: [Object: null prototype] { user: 'admin' }\n\nParsed Query: [Object: null prototype] \n { user: 'admin', articles: '1' }\n\nParsed Query: [Object: null prototype] {\n user: 'admin',\n articles: [ '1', '2', '3' ],\n access: 'true'\n}\n"
},
{
"code": null,
"e": 4242,
"s": 4141,
"text": "Reference: https://nodejs.org/api/querystring.html#querystring_querystring_parse_str_sep_eq_options "
},
{
"code": null,
"e": 4270,
"s": 4242,
"text": "Node.js- querystring-Module"
},
{
"code": null,
"e": 4278,
"s": 4270,
"text": "Node.js"
},
{
"code": null,
"e": 4295,
"s": 4278,
"text": "Web Technologies"
},
{
"code": null,
"e": 4393,
"s": 4295,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4441,
"s": 4393,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 4474,
"s": 4441,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 4504,
"s": 4474,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 4524,
"s": 4504,
"text": "How to update NPM ?"
},
{
"code": null,
"e": 4578,
"s": 4524,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 4640,
"s": 4578,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4701,
"s": 4640,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4751,
"s": 4701,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 4794,
"s": 4751,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
LCA in a tree using Binary Lifting Technique | 04 Sep, 2021
Given a binary tree, the task is to find the Lowest Common Ancestor of the given two nodes in the tree. Let G be a tree then LCA of two nodes u and v is defined as the node w in the tree which is an ancestor of both u and v and is farthest from the root node.If one node is the ancestor of another one than that particular node is the LCA of those two nodes.Example:
Input:
Output: The LCA of 6 and 9 is 1. The LCA of 5 and 9 is 1. The LCA of 6 and 8 is 3. The LCA of 6 and 1 is 1.
Approach: The article describes an approach known as Binary Lifting to find the Lowest Common Ancestor of two nodes in a tree. There can be many approaches to solve the LCA problem. We are discussing the Binary Lifting Technique, the others can be read from here and here. Binary Lifting is a dynamic programming approach where we pre-compute an array memo[1, n][1, log(n)] where memo[i][j] contains 2^j-th ancestor of node i. For computing the values of memo[][], the following recursion may be used
memo state:
memo[i][j] = i-th node’s 2^(j)th ancestor in the path
memo initialization:
memo[i][j] = memo[i][0] (first parent (2^0) of each node is given)
memo trans:
memo[i][j] = memo[ memo [i][j – 1]]
meaning: A(i,2^j)=A( A(i , 2^(j-1) ) , 2^(j-1) )
To find the (2^j)-th ancestor of i, recursively find i-th node’s 2^(j-1)th ancestor’s 2^(j-1)th ancestor. (2^(j) = 2^(j-1) + 2^(j-1))
So:
memo[i][j] = parent[i] if j = 0 and memo[i][j] = memo[memo[i][j – 1]][j – 1] if j > 0.
We first check whether a node is an ancestor of other or not and if one node is ancestor of other then it is the LCA of these two nodes otherwise we find a node which is not the common ancestor of both u and v and is highest(i.e. a node x such that x is not the common ancestor of u and v but memo[x][0] is) in the tree. After finding such a node (let it be x), we print the first ancestor of x i.e. memo[x][0] which will be the required LCA.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Pre-processing to calculate values of memo[][]void dfs(int u, int p, int **memo, int *lev, int log, vector<int> *g){ // Using recursion formula to calculate // the values of memo[][] memo[u][0] = p; for (int i = 1; i <= log; i++) memo[u][i] = memo[memo[u][i - 1]][i - 1]; for (int v : g[u]) { if (v != p) { lev[v] = lev[u] + 1; dfs(v, u, memo, lev, log, g); } }} // Function to return the LCA of nodes u and vint lca(int u, int v, int log, int *lev, int **memo){ // The node which is present farthest // from the root node is taken as u // If v is farther from root node // then swap the two if (lev[u] < lev[v]) swap(u, v); // Finding the ancestor of u // which is at same level as v for (int i = log; i >= 0; i--) if ((lev[u] - pow(2, i)) >= lev[v]) u = memo[u][i]; // If v is the ancestor of u // then v is the LCA of u and v if (u == v) return u; // Finding the node closest to the root which is // not the common ancestor of u and v i.e. a node // x such that x is not the common ancestor of u // and v but memo[x][0] is for (int i = log; i >= 0; i--) { if (memo[u][i] != memo[v][i]) { u = memo[u][i]; v = memo[v][i]; } } // Returning the first ancestor // of above found node return memo[u][0];} // Driver Codeint main(){ // Number of nodes int n = 9; // vector to store tree vector<int> g[n + 1]; int log = (int)ceil(log2(n)); int **memo = new int *[n + 1]; for (int i = 0; i < n + 1; i++) memo[i] = new int[log + 1]; // Stores the level of each node int *lev = new int[n + 1]; // Initialising memo values with -1 for (int i = 0; i <= n; i++) memset(memo[i], -1, sizeof memo[i]); // Add edges g[1].push_back(2); g[2].push_back(1); g[1].push_back(3); g[3].push_back(1); g[1].push_back(4); g[4].push_back(1); g[2].push_back(5); g[5].push_back(2); g[3].push_back(6); g[6].push_back(3); g[3].push_back(7); g[7].push_back(3); g[3].push_back(8); g[8].push_back(3); g[4].push_back(9); g[9].push_back(4); dfs(1, 1, memo, lev, log, g); cout << "The LCA of 6 and 9 is " << lca(6, 9, log, lev, memo) << endl; cout << "The LCA of 5 and 9 is " << lca(5, 9, log, lev, memo) << endl; cout << "The LCA of 6 and 8 is " << lca(6, 8, log, lev, memo) << endl; cout << "The LCA of 6 and 1 is " << lca(6, 1, log, lev, memo) << endl; return 0;} // This code is contributed by// sanjeev2552
// Java implementation of the approachimport java.util.*;public class GFG { // ArrayList to store tree static ArrayList<Integer> g[]; static int memo[][], lev[], log; // Pre-processing to calculate values of memo[][] static void dfs(int u, int p) { // Using recursion formula to calculate // the values of memo[][] memo[u][0] = p; for (int i = 1; i <= log; i++) memo[u][i] = memo[memo[u][i - 1]][i - 1]; for (int v : g[u]) { if (v != p) { // Calculating the level of each node lev[v] = lev[u] + 1; dfs(v, u); } } } // Function to return the LCA of nodes u and v static int lca(int u, int v) { // The node which is present farthest // from the root node is taken as u // If v is farther from root node // then swap the two if (lev[u] < lev[v]) { int temp = u; u = v; v = temp; } // Finding the ancestor of u // which is at same level as v for (int i = log; i >= 0; i--) { if ((lev[u] - (int)Math.pow(2, i)) >= lev[v]) u = memo[u][i]; } // If v is the ancestor of u // then v is the LCA of u and v if (u == v) return u; // Finding the node closest to the root which is // not the common ancestor of u and v i.e. a node // x such that x is not the common ancestor of u // and v but memo[x][0] is for (int i = log; i >= 0; i--) { if (memo[u][i] != memo[v][i]) { u = memo[u][i]; v = memo[v][i]; } } // Returning the first ancestor // of above found node return memo[u][0]; } // Driver code public static void main(String args[]) { // Number of nodes int n = 9; g = new ArrayList[n + 1]; // log(n) with base 2 log = (int)Math.ceil(Math.log(n) / Math.log(2)); memo = new int[n + 1][log + 1]; // Stores the level of each node lev = new int[n + 1]; // Initialising memo values with -1 for (int i = 0; i <= n; i++) Arrays.fill(memo[i], -1); for (int i = 0; i <= n; i++) g[i] = new ArrayList<>(); // Add edges g[1].add(2); g[2].add(1); g[1].add(3); g[3].add(1); g[1].add(4); g[4].add(1); g[2].add(5); g[5].add(2); g[3].add(6); g[6].add(3); g[3].add(7); g[7].add(3); g[3].add(8); g[8].add(3); g[4].add(9); g[9].add(4); dfs(1, 1); System.out.println("The LCA of 6 and 9 is " + lca(6, 9)); System.out.println("The LCA of 5 and 9 is " + lca(5, 9)); System.out.println("The LCA of 6 and 8 is " + lca(6, 8)); System.out.println("The LCA of 6 and 1 is " + lca(6, 1)); }}
# Python3 implementation of the above approachimport math # Pre-processing to calculate values of memo[][]def dfs(u, p, memo, lev, log, g): # Using recursion formula to calculate # the values of memo[][] memo[u][0] = p for i in range(1, log + 1): memo[u][i] = memo[memo[u][i - 1]][i - 1] for v in g[u]: if v != p: lev[v] = lev[u] + 1 dfs(v, u, memo, lev, log, g) # Function to return the LCA of nodes u and vdef lca(u, v, log, lev, memo): # The node which is present farthest # from the root node is taken as u # If v is farther from root node # then swap the two if lev[u] < lev[v]: swap(u, v) # Finding the ancestor of u # which is at same level as v for i in range(log, -1, -1): if (lev[u] - pow(2, i)) >= lev[v]: u = memo[u][i] # If v is the ancestor of u # then v is the LCA of u and v if u == v: return v # Finding the node closest to the # root which is not the common ancestor # of u and v i.e. a node x such that x # is not the common ancestor of u # and v but memo[x][0] is for i in range(log, -1, -1): if memo[u][i] != memo[v][i]: u = memo[u][i] v = memo[v][i] # Returning the first ancestor # of above found node return memo[u][0] # Driver code # Number of nodesn = 9 log = math.ceil(math.log(n, 2))g = [[] for i in range(n + 1)] memo = [[-1 for i in range(log + 1)] for j in range(n + 1)] # Stores the level of each node lev = [0 for i in range(n + 1)] # Add edgesg[1].append(2)g[2].append(1)g[1].append(3)g[3].append(1)g[1].append(4)g[4].append(1)g[2].append(5)g[5].append(2)g[3].append(6)g[6].append(3)g[3].append(7)g[7].append(3)g[3].append(8)g[8].append(3)g[4].append(9)g[9].append(4) dfs(1, 1, memo, lev, log, g) print("The LCA of 6 and 9 is", lca(6, 9, log, lev, memo))print("The LCA of 5 and 9 is", lca(5, 9, log, lev, memo))print("The LCA of 6 and 8 is", lca(6, 8, log, lev, memo))print("The LCA of 6 and 1 is", lca(6, 1, log, lev, memo)) # This code is contributed by Bhaskar
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // List to store tree static List<int> []g; static int [,]memo; static int []lev; static int log; // Pre-processing to calculate // values of memo[,] static void dfs(int u, int p) { // Using recursion formula to // calculate the values of memo[,] memo[u, 0] = p; for (int i = 1; i <= log; i++) memo[u, i] = memo[memo[u, i - 1], i - 1]; foreach (int v in g[u]) { if (v != p) { // Calculating the level of each node lev[v] = lev[u] + 1; dfs(v, u); } } } // Function to return the LCA of // nodes u and v static int lca(int u, int v) { // The node which is present farthest // from the root node is taken as u // If v is farther from root node // then swap the two if (lev[u] < lev[v]) { int temp = u; u = v; v = temp; } // Finding the ancestor of u // which is at same level as v for (int i = log; i >= 0; i--) { if ((lev[u] - (int)Math.Pow(2, i)) >= lev[v]) u = memo[u, i]; } // If v is the ancestor of u // then v is the LCA of u and v if (u == v) return u; // Finding the node closest to the root // which is not the common ancestor of // u and v i.e. a node x such that // x is not the common ancestor of u // and v but memo[x,0] is for (int i = log; i >= 0; i--) { if (memo[u, i] != memo[v, i]) { u = memo[u, i]; v = memo[v, i]; } } // Returning the first ancestor // of above found node return memo[u, 0]; } // Driver code public static void Main(String []args) { // Number of nodes int n = 9; g = new List<int>[n + 1]; // log(n) with base 2 log = (int)Math.Ceiling(Math.Log(n) / Math.Log(2)); memo = new int[n + 1, log + 1]; // Stores the level of each node lev = new int[n + 1]; // Initialising memo values with -1 for (int i = 0; i <= n; i++) for (int j = 0; j <= log; j++) memo[i, j] = -1; for (int i = 0; i <= n; i++) g[i] = new List<int>(); // Add edges g[1].Add(2); g[2].Add(1); g[1].Add(3); g[3].Add(1); g[1].Add(4); g[4].Add(1); g[2].Add(5); g[5].Add(2); g[3].Add(6); g[6].Add(3); g[3].Add(7); g[7].Add(3); g[3].Add(8); g[8].Add(3); g[4].Add(9); g[9].Add(4); dfs(1, 1); Console.WriteLine("The LCA of 6 and 9 is " + lca(6, 9)); Console.WriteLine("The LCA of 5 and 9 is " + lca(5, 9)); Console.WriteLine("The LCA of 6 and 8 is " + lca(6, 8)); Console.WriteLine("The LCA of 6 and 1 is " + lca(6, 1)); }} // This code is contributed by PrinciRaj1992
<script> // JavaScript implementation of the approach // ArrayList to store tree let g; let memo, lev, log; // Pre-processing to calculate values of memo[][] function dfs(u, p) { // Using recursion formula to calculate // the values of memo[][] memo[u][0] = p; for (let i = 1; i <= log; i++) memo[u][i] = memo[memo[u][i - 1]][i - 1]; for (let v = 0; v < g[u].length; v++) { if (g[u][v] != p) { // Calculating the level of each node lev[g[u][v]] = lev[u] + 1; dfs(g[u][v], u); } } } // Function to return the LCA of nodes u and v function lca(u, v) { // The node which is present farthest // from the root node is taken as u // If v is farther from root node // then swap the two if (lev[u] < lev[v]) { let temp = u; u = v; v = temp; } // Finding the ancestor of u // which is at same level as v for (let i = log; i >= 0; i--) { if ((lev[u] - Math.pow(2, i)) >= lev[v]) u = memo[u][i]; } // If v is the ancestor of u // then v is the LCA of u and v if (u == v) return u; // Finding the node closest to the root which is // not the common ancestor of u and v i.e. a node // x such that x is not the common ancestor of u // and v but memo[x][0] is for (let i = log; i >= 0; i--) { if (memo[u][i] != memo[v][i]) { u = memo[u][i]; v = memo[v][i]; } } // Returning the first ancestor // of above found node return memo[u][0]; } // Number of nodes let n = 9; g = new Array(n + 1); // log(n) with base 2 log = Math.ceil(Math.log(n) / Math.log(2)); memo = new Array(n + 1); // Stores the level of each node lev = new Array(n + 1); lev.fill(0); // Initialising memo values with -1 for (let i = 0; i <= n; i++) { memo[i] = new Array(log+1); for (let j = 0; j < log+1; j++) { memo[i][j] = -1; } } for (let i = 0; i <= n; i++) g[i] = []; // Add edges g[1].push(2); g[2].push(1); g[1].push(3); g[3].push(1); g[1].push(4); g[4].push(1); g[2].push(5); g[5].push(2); g[3].push(6); g[6].push(3); g[3].push(7); g[7].push(3); g[3].push(8); g[8].push(3); g[4].push(9); g[9].push(4); dfs(1, 1); document.write("The LCA of 6 and 9 is " + lca(6, 9) + "</br>"); document.write("The LCA of 5 and 9 is " + lca(5, 9) + "</br>"); document.write("The LCA of 6 and 8 is " + lca(6, 8) + "</br>"); document.write("The LCA of 6 and 1 is " + lca(6, 1)); </script>
The LCA of 6 and 9 is 1
The LCA of 5 and 9 is 1
The LCA of 6 and 8 is 3
The LCA of 6 and 1 is 1
Time Complexity: The time taken in pre-processing is O(NlogN) and every query takes O(logN) time. So the overall time complexity of the solution is O(NlogN).Auxiliary Space: O(NlogN)
princiraj1992
sanjeev2552
bpandey23012002
darkhash
decode2207
pankajsharmagfg
gaurav2146
Binary Tree
LCA
Data Structures
Dynamic Programming
Tree
Data Structures
Dynamic Programming
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Sep, 2021"
},
{
"code": null,
"e": 421,
"s": 52,
"text": "Given a binary tree, the task is to find the Lowest Common Ancestor of the given two nodes in the tree. Let G be a tree then LCA of two nodes u and v is defined as the node w in the tree which is an ancestor of both u and v and is farthest from the root node.If one node is the ancestor of another one than that particular node is the LCA of those two nodes.Example: "
},
{
"code": null,
"e": 430,
"s": 421,
"text": "Input: "
},
{
"code": null,
"e": 540,
"s": 430,
"text": "Output: The LCA of 6 and 9 is 1. The LCA of 5 and 9 is 1. The LCA of 6 and 8 is 3. The LCA of 6 and 1 is 1. "
},
{
"code": null,
"e": 1043,
"s": 540,
"text": "Approach: The article describes an approach known as Binary Lifting to find the Lowest Common Ancestor of two nodes in a tree. There can be many approaches to solve the LCA problem. We are discussing the Binary Lifting Technique, the others can be read from here and here. Binary Lifting is a dynamic programming approach where we pre-compute an array memo[1, n][1, log(n)] where memo[i][j] contains 2^j-th ancestor of node i. For computing the values of memo[][], the following recursion may be used "
},
{
"code": null,
"e": 1057,
"s": 1043,
"text": "memo state: "
},
{
"code": null,
"e": 1116,
"s": 1057,
"text": " memo[i][j] = i-th node’s 2^(j)th ancestor in the path "
},
{
"code": null,
"e": 1139,
"s": 1116,
"text": "memo initialization: "
},
{
"code": null,
"e": 1209,
"s": 1139,
"text": " memo[i][j] = memo[i][0] (first parent (2^0) of each node is given)"
},
{
"code": null,
"e": 1221,
"s": 1209,
"text": "memo trans:"
},
{
"code": null,
"e": 1260,
"s": 1221,
"text": " memo[i][j] = memo[ memo [i][j – 1]]"
},
{
"code": null,
"e": 1310,
"s": 1260,
"text": "meaning: A(i,2^j)=A( A(i , 2^(j-1) ) , 2^(j-1) ) "
},
{
"code": null,
"e": 1444,
"s": 1310,
"text": "To find the (2^j)-th ancestor of i, recursively find i-th node’s 2^(j-1)th ancestor’s 2^(j-1)th ancestor. (2^(j) = 2^(j-1) + 2^(j-1))"
},
{
"code": null,
"e": 1448,
"s": 1444,
"text": "So:"
},
{
"code": null,
"e": 1537,
"s": 1448,
"text": "memo[i][j] = parent[i] if j = 0 and memo[i][j] = memo[memo[i][j – 1]][j – 1] if j > 0. "
},
{
"code": null,
"e": 2032,
"s": 1537,
"text": "We first check whether a node is an ancestor of other or not and if one node is ancestor of other then it is the LCA of these two nodes otherwise we find a node which is not the common ancestor of both u and v and is highest(i.e. a node x such that x is not the common ancestor of u and v but memo[x][0] is) in the tree. After finding such a node (let it be x), we print the first ancestor of x i.e. memo[x][0] which will be the required LCA.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 2036,
"s": 2032,
"text": "C++"
},
{
"code": null,
"e": 2041,
"s": 2036,
"text": "Java"
},
{
"code": null,
"e": 2049,
"s": 2041,
"text": "Python3"
},
{
"code": null,
"e": 2052,
"s": 2049,
"text": "C#"
},
{
"code": null,
"e": 2063,
"s": 2052,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Pre-processing to calculate values of memo[][]void dfs(int u, int p, int **memo, int *lev, int log, vector<int> *g){ // Using recursion formula to calculate // the values of memo[][] memo[u][0] = p; for (int i = 1; i <= log; i++) memo[u][i] = memo[memo[u][i - 1]][i - 1]; for (int v : g[u]) { if (v != p) { lev[v] = lev[u] + 1; dfs(v, u, memo, lev, log, g); } }} // Function to return the LCA of nodes u and vint lca(int u, int v, int log, int *lev, int **memo){ // The node which is present farthest // from the root node is taken as u // If v is farther from root node // then swap the two if (lev[u] < lev[v]) swap(u, v); // Finding the ancestor of u // which is at same level as v for (int i = log; i >= 0; i--) if ((lev[u] - pow(2, i)) >= lev[v]) u = memo[u][i]; // If v is the ancestor of u // then v is the LCA of u and v if (u == v) return u; // Finding the node closest to the root which is // not the common ancestor of u and v i.e. a node // x such that x is not the common ancestor of u // and v but memo[x][0] is for (int i = log; i >= 0; i--) { if (memo[u][i] != memo[v][i]) { u = memo[u][i]; v = memo[v][i]; } } // Returning the first ancestor // of above found node return memo[u][0];} // Driver Codeint main(){ // Number of nodes int n = 9; // vector to store tree vector<int> g[n + 1]; int log = (int)ceil(log2(n)); int **memo = new int *[n + 1]; for (int i = 0; i < n + 1; i++) memo[i] = new int[log + 1]; // Stores the level of each node int *lev = new int[n + 1]; // Initialising memo values with -1 for (int i = 0; i <= n; i++) memset(memo[i], -1, sizeof memo[i]); // Add edges g[1].push_back(2); g[2].push_back(1); g[1].push_back(3); g[3].push_back(1); g[1].push_back(4); g[4].push_back(1); g[2].push_back(5); g[5].push_back(2); g[3].push_back(6); g[6].push_back(3); g[3].push_back(7); g[7].push_back(3); g[3].push_back(8); g[8].push_back(3); g[4].push_back(9); g[9].push_back(4); dfs(1, 1, memo, lev, log, g); cout << \"The LCA of 6 and 9 is \" << lca(6, 9, log, lev, memo) << endl; cout << \"The LCA of 5 and 9 is \" << lca(5, 9, log, lev, memo) << endl; cout << \"The LCA of 6 and 8 is \" << lca(6, 8, log, lev, memo) << endl; cout << \"The LCA of 6 and 1 is \" << lca(6, 1, log, lev, memo) << endl; return 0;} // This code is contributed by// sanjeev2552",
"e": 4757,
"s": 2063,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*;public class GFG { // ArrayList to store tree static ArrayList<Integer> g[]; static int memo[][], lev[], log; // Pre-processing to calculate values of memo[][] static void dfs(int u, int p) { // Using recursion formula to calculate // the values of memo[][] memo[u][0] = p; for (int i = 1; i <= log; i++) memo[u][i] = memo[memo[u][i - 1]][i - 1]; for (int v : g[u]) { if (v != p) { // Calculating the level of each node lev[v] = lev[u] + 1; dfs(v, u); } } } // Function to return the LCA of nodes u and v static int lca(int u, int v) { // The node which is present farthest // from the root node is taken as u // If v is farther from root node // then swap the two if (lev[u] < lev[v]) { int temp = u; u = v; v = temp; } // Finding the ancestor of u // which is at same level as v for (int i = log; i >= 0; i--) { if ((lev[u] - (int)Math.pow(2, i)) >= lev[v]) u = memo[u][i]; } // If v is the ancestor of u // then v is the LCA of u and v if (u == v) return u; // Finding the node closest to the root which is // not the common ancestor of u and v i.e. a node // x such that x is not the common ancestor of u // and v but memo[x][0] is for (int i = log; i >= 0; i--) { if (memo[u][i] != memo[v][i]) { u = memo[u][i]; v = memo[v][i]; } } // Returning the first ancestor // of above found node return memo[u][0]; } // Driver code public static void main(String args[]) { // Number of nodes int n = 9; g = new ArrayList[n + 1]; // log(n) with base 2 log = (int)Math.ceil(Math.log(n) / Math.log(2)); memo = new int[n + 1][log + 1]; // Stores the level of each node lev = new int[n + 1]; // Initialising memo values with -1 for (int i = 0; i <= n; i++) Arrays.fill(memo[i], -1); for (int i = 0; i <= n; i++) g[i] = new ArrayList<>(); // Add edges g[1].add(2); g[2].add(1); g[1].add(3); g[3].add(1); g[1].add(4); g[4].add(1); g[2].add(5); g[5].add(2); g[3].add(6); g[6].add(3); g[3].add(7); g[7].add(3); g[3].add(8); g[8].add(3); g[4].add(9); g[9].add(4); dfs(1, 1); System.out.println(\"The LCA of 6 and 9 is \" + lca(6, 9)); System.out.println(\"The LCA of 5 and 9 is \" + lca(5, 9)); System.out.println(\"The LCA of 6 and 8 is \" + lca(6, 8)); System.out.println(\"The LCA of 6 and 1 is \" + lca(6, 1)); }}",
"e": 7719,
"s": 4757,
"text": null
},
{
"code": "# Python3 implementation of the above approachimport math # Pre-processing to calculate values of memo[][]def dfs(u, p, memo, lev, log, g): # Using recursion formula to calculate # the values of memo[][] memo[u][0] = p for i in range(1, log + 1): memo[u][i] = memo[memo[u][i - 1]][i - 1] for v in g[u]: if v != p: lev[v] = lev[u] + 1 dfs(v, u, memo, lev, log, g) # Function to return the LCA of nodes u and vdef lca(u, v, log, lev, memo): # The node which is present farthest # from the root node is taken as u # If v is farther from root node # then swap the two if lev[u] < lev[v]: swap(u, v) # Finding the ancestor of u # which is at same level as v for i in range(log, -1, -1): if (lev[u] - pow(2, i)) >= lev[v]: u = memo[u][i] # If v is the ancestor of u # then v is the LCA of u and v if u == v: return v # Finding the node closest to the # root which is not the common ancestor # of u and v i.e. a node x such that x # is not the common ancestor of u # and v but memo[x][0] is for i in range(log, -1, -1): if memo[u][i] != memo[v][i]: u = memo[u][i] v = memo[v][i] # Returning the first ancestor # of above found node return memo[u][0] # Driver code # Number of nodesn = 9 log = math.ceil(math.log(n, 2))g = [[] for i in range(n + 1)] memo = [[-1 for i in range(log + 1)] for j in range(n + 1)] # Stores the level of each node lev = [0 for i in range(n + 1)] # Add edgesg[1].append(2)g[2].append(1)g[1].append(3)g[3].append(1)g[1].append(4)g[4].append(1)g[2].append(5)g[5].append(2)g[3].append(6)g[6].append(3)g[3].append(7)g[7].append(3)g[3].append(8)g[8].append(3)g[4].append(9)g[9].append(4) dfs(1, 1, memo, lev, log, g) print(\"The LCA of 6 and 9 is\", lca(6, 9, log, lev, memo))print(\"The LCA of 5 and 9 is\", lca(5, 9, log, lev, memo))print(\"The LCA of 6 and 8 is\", lca(6, 8, log, lev, memo))print(\"The LCA of 6 and 1 is\", lca(6, 1, log, lev, memo)) # This code is contributed by Bhaskar",
"e": 9882,
"s": 7719,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // List to store tree static List<int> []g; static int [,]memo; static int []lev; static int log; // Pre-processing to calculate // values of memo[,] static void dfs(int u, int p) { // Using recursion formula to // calculate the values of memo[,] memo[u, 0] = p; for (int i = 1; i <= log; i++) memo[u, i] = memo[memo[u, i - 1], i - 1]; foreach (int v in g[u]) { if (v != p) { // Calculating the level of each node lev[v] = lev[u] + 1; dfs(v, u); } } } // Function to return the LCA of // nodes u and v static int lca(int u, int v) { // The node which is present farthest // from the root node is taken as u // If v is farther from root node // then swap the two if (lev[u] < lev[v]) { int temp = u; u = v; v = temp; } // Finding the ancestor of u // which is at same level as v for (int i = log; i >= 0; i--) { if ((lev[u] - (int)Math.Pow(2, i)) >= lev[v]) u = memo[u, i]; } // If v is the ancestor of u // then v is the LCA of u and v if (u == v) return u; // Finding the node closest to the root // which is not the common ancestor of // u and v i.e. a node x such that // x is not the common ancestor of u // and v but memo[x,0] is for (int i = log; i >= 0; i--) { if (memo[u, i] != memo[v, i]) { u = memo[u, i]; v = memo[v, i]; } } // Returning the first ancestor // of above found node return memo[u, 0]; } // Driver code public static void Main(String []args) { // Number of nodes int n = 9; g = new List<int>[n + 1]; // log(n) with base 2 log = (int)Math.Ceiling(Math.Log(n) / Math.Log(2)); memo = new int[n + 1, log + 1]; // Stores the level of each node lev = new int[n + 1]; // Initialising memo values with -1 for (int i = 0; i <= n; i++) for (int j = 0; j <= log; j++) memo[i, j] = -1; for (int i = 0; i <= n; i++) g[i] = new List<int>(); // Add edges g[1].Add(2); g[2].Add(1); g[1].Add(3); g[3].Add(1); g[1].Add(4); g[4].Add(1); g[2].Add(5); g[5].Add(2); g[3].Add(6); g[6].Add(3); g[3].Add(7); g[7].Add(3); g[3].Add(8); g[8].Add(3); g[4].Add(9); g[9].Add(4); dfs(1, 1); Console.WriteLine(\"The LCA of 6 and 9 is \" + lca(6, 9)); Console.WriteLine(\"The LCA of 5 and 9 is \" + lca(5, 9)); Console.WriteLine(\"The LCA of 6 and 8 is \" + lca(6, 8)); Console.WriteLine(\"The LCA of 6 and 1 is \" + lca(6, 1)); }} // This code is contributed by PrinciRaj1992",
"e": 13219,
"s": 9882,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // ArrayList to store tree let g; let memo, lev, log; // Pre-processing to calculate values of memo[][] function dfs(u, p) { // Using recursion formula to calculate // the values of memo[][] memo[u][0] = p; for (let i = 1; i <= log; i++) memo[u][i] = memo[memo[u][i - 1]][i - 1]; for (let v = 0; v < g[u].length; v++) { if (g[u][v] != p) { // Calculating the level of each node lev[g[u][v]] = lev[u] + 1; dfs(g[u][v], u); } } } // Function to return the LCA of nodes u and v function lca(u, v) { // The node which is present farthest // from the root node is taken as u // If v is farther from root node // then swap the two if (lev[u] < lev[v]) { let temp = u; u = v; v = temp; } // Finding the ancestor of u // which is at same level as v for (let i = log; i >= 0; i--) { if ((lev[u] - Math.pow(2, i)) >= lev[v]) u = memo[u][i]; } // If v is the ancestor of u // then v is the LCA of u and v if (u == v) return u; // Finding the node closest to the root which is // not the common ancestor of u and v i.e. a node // x such that x is not the common ancestor of u // and v but memo[x][0] is for (let i = log; i >= 0; i--) { if (memo[u][i] != memo[v][i]) { u = memo[u][i]; v = memo[v][i]; } } // Returning the first ancestor // of above found node return memo[u][0]; } // Number of nodes let n = 9; g = new Array(n + 1); // log(n) with base 2 log = Math.ceil(Math.log(n) / Math.log(2)); memo = new Array(n + 1); // Stores the level of each node lev = new Array(n + 1); lev.fill(0); // Initialising memo values with -1 for (let i = 0; i <= n; i++) { memo[i] = new Array(log+1); for (let j = 0; j < log+1; j++) { memo[i][j] = -1; } } for (let i = 0; i <= n; i++) g[i] = []; // Add edges g[1].push(2); g[2].push(1); g[1].push(3); g[3].push(1); g[1].push(4); g[4].push(1); g[2].push(5); g[5].push(2); g[3].push(6); g[6].push(3); g[3].push(7); g[7].push(3); g[3].push(8); g[8].push(3); g[4].push(9); g[9].push(4); dfs(1, 1); document.write(\"The LCA of 6 and 9 is \" + lca(6, 9) + \"</br>\"); document.write(\"The LCA of 5 and 9 is \" + lca(5, 9) + \"</br>\"); document.write(\"The LCA of 6 and 8 is \" + lca(6, 8) + \"</br>\"); document.write(\"The LCA of 6 and 1 is \" + lca(6, 1)); </script>",
"e": 16067,
"s": 13219,
"text": null
},
{
"code": null,
"e": 16163,
"s": 16067,
"text": "The LCA of 6 and 9 is 1\nThe LCA of 5 and 9 is 1\nThe LCA of 6 and 8 is 3\nThe LCA of 6 and 1 is 1"
},
{
"code": null,
"e": 16350,
"s": 16165,
"text": "Time Complexity: The time taken in pre-processing is O(NlogN) and every query takes O(logN) time. So the overall time complexity of the solution is O(NlogN).Auxiliary Space: O(NlogN) "
},
{
"code": null,
"e": 16364,
"s": 16350,
"text": "princiraj1992"
},
{
"code": null,
"e": 16376,
"s": 16364,
"text": "sanjeev2552"
},
{
"code": null,
"e": 16392,
"s": 16376,
"text": "bpandey23012002"
},
{
"code": null,
"e": 16401,
"s": 16392,
"text": "darkhash"
},
{
"code": null,
"e": 16412,
"s": 16401,
"text": "decode2207"
},
{
"code": null,
"e": 16428,
"s": 16412,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 16439,
"s": 16428,
"text": "gaurav2146"
},
{
"code": null,
"e": 16451,
"s": 16439,
"text": "Binary Tree"
},
{
"code": null,
"e": 16455,
"s": 16451,
"text": "LCA"
},
{
"code": null,
"e": 16471,
"s": 16455,
"text": "Data Structures"
},
{
"code": null,
"e": 16491,
"s": 16471,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 16496,
"s": 16491,
"text": "Tree"
},
{
"code": null,
"e": 16512,
"s": 16496,
"text": "Data Structures"
},
{
"code": null,
"e": 16532,
"s": 16512,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 16537,
"s": 16532,
"text": "Tree"
}
] |
PyQt5 – setChecked() method for Check Box | 22 Apr, 2020
setChecked method is used to change the state of check box. By default it is un-checked after clicking on the check box widget its states get changed into checked, but with the help of setChecked method we can do it directly without clicking it.
Syntax : checkbox.setChecked(True)
Argument : It takes bool as argument.
Action performed : It will change the state of check box.
Below is the implementation.
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating the check-box checkbox = QCheckBox('Check Box', self) # setting geometry of check box checkbox.setGeometry(200, 150, 100, 30) # setting check box state to checked checkbox.setChecked(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 274,
"s": 28,
"text": "setChecked method is used to change the state of check box. By default it is un-checked after clicking on the check box widget its states get changed into checked, but with the help of setChecked method we can do it directly without clicking it."
},
{
"code": null,
"e": 309,
"s": 274,
"text": "Syntax : checkbox.setChecked(True)"
},
{
"code": null,
"e": 347,
"s": 309,
"text": "Argument : It takes bool as argument."
},
{
"code": null,
"e": 405,
"s": 347,
"text": "Action performed : It will change the state of check box."
},
{
"code": null,
"e": 434,
"s": 405,
"text": "Below is the implementation."
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating the check-box checkbox = QCheckBox('Check Box', self) # setting geometry of check box checkbox.setGeometry(200, 150, 100, 30) # setting check box state to checked checkbox.setChecked(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 1345,
"s": 434,
"text": null
},
{
"code": null,
"e": 1354,
"s": 1345,
"text": "Output :"
},
{
"code": null,
"e": 1365,
"s": 1354,
"text": "Python-gui"
},
{
"code": null,
"e": 1377,
"s": 1365,
"text": "Python-PyQt"
},
{
"code": null,
"e": 1384,
"s": 1377,
"text": "Python"
},
{
"code": null,
"e": 1482,
"s": 1384,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1500,
"s": 1482,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1542,
"s": 1500,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1564,
"s": 1542,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1599,
"s": 1564,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1625,
"s": 1599,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1657,
"s": 1625,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1686,
"s": 1657,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1713,
"s": 1686,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1734,
"s": 1713,
"text": "Python OOPs Concepts"
}
] |
How to use php serialize() and unserialize() Function | 30 Sep, 2019
In PHP, the complex data can not be transported or can not be stored. If you want to execute continuously a complex set of data beyond a single script then this serialize() and unserialize() functions are handy to deal with those complex data structures. The serialize() function is just given a compatible shape to a complex data structure that the PHP can handle that data after that you can reverse the work by using the unserialize() function.
Most often, we need to store a complex array in the database or in a file from PHP. Some of us might have surely searched for some built-in function to accomplish this task. Complex arrays are arrays with elements of more than one data-types or array. But, we already have a handy solution to handle this situation.
Serialize() Function: The serialize() is an inbuilt function PHP that is used to serialize the given array. The serialize() function accepts a single parameter which is the data we want to serialize and returns a serialized string.
Syntax:serialize( $values_in_form_of_array )
serialize( $values_in_form_of_array )
Below program illustrate the Serialize() function.Program:<?php // Complex array $myvar = array( 'hello', 42, array(1, 'two'), 'apple'); // Convert to a string $string = serialize($myvar); // Printing the serialized data echo $string; ?>
<?php // Complex array $myvar = array( 'hello', 42, array(1, 'two'), 'apple'); // Convert to a string $string = serialize($myvar); // Printing the serialized data echo $string; ?>
Output:a:4:{i:0;s:5:"hello";i:1;i:42;i:2;a:2:{i:
0;i:1;i:1;s:3:"two";}i:3;s:5:"apple";}
a:4:{i:0;s:5:"hello";i:1;i:42;i:2;a:2:{i:
0;i:1;i:1;s:3:"two";}i:3;s:5:"apple";}
Unserialize() Function: The unserialize() is an inbuilt function php that is used to unserialize the given serialized array to get back to the original value of the complex array, $myvar.
Syntax:unserialize( $serialized_array )
unserialize( $serialized_array )
Below program illustrate both serialize() and unserialize() functions:Program:<?php // Complex array $myvar = array( 'hello', 42, array(1, 'two'), 'apple'); // Serialize the above data $string = serialize($myvar); // Unserializing the data in $string $newvar = unserialize($string); // Printing the unserialized data print_r($newvar); ?>
<?php // Complex array $myvar = array( 'hello', 42, array(1, 'two'), 'apple'); // Serialize the above data $string = serialize($myvar); // Unserializing the data in $string $newvar = unserialize($string); // Printing the unserialized data print_r($newvar); ?>
Output:Array
(
[0] => hello
[1] => 42
[2] => Array
(
[0] => 1
[1] => two
)
[3] => apple
)
Array
(
[0] => hello
[1] => 42
[2] => Array
(
[0] => 1
[1] => two
)
[3] => apple
)
Note: For more depth knowledge you can check PHP | Serializing Data article.
PHP-basics
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
PHP in_array() Function
How to delete an array element based on key in PHP?
How to pop an alert message box using PHP ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Sep, 2019"
},
{
"code": null,
"e": 476,
"s": 28,
"text": "In PHP, the complex data can not be transported or can not be stored. If you want to execute continuously a complex set of data beyond a single script then this serialize() and unserialize() functions are handy to deal with those complex data structures. The serialize() function is just given a compatible shape to a complex data structure that the PHP can handle that data after that you can reverse the work by using the unserialize() function."
},
{
"code": null,
"e": 792,
"s": 476,
"text": "Most often, we need to store a complex array in the database or in a file from PHP. Some of us might have surely searched for some built-in function to accomplish this task. Complex arrays are arrays with elements of more than one data-types or array. But, we already have a handy solution to handle this situation."
},
{
"code": null,
"e": 1024,
"s": 792,
"text": "Serialize() Function: The serialize() is an inbuilt function PHP that is used to serialize the given array. The serialize() function accepts a single parameter which is the data we want to serialize and returns a serialized string."
},
{
"code": null,
"e": 1069,
"s": 1024,
"text": "Syntax:serialize( $values_in_form_of_array )"
},
{
"code": null,
"e": 1107,
"s": 1069,
"text": "serialize( $values_in_form_of_array )"
},
{
"code": null,
"e": 1370,
"s": 1107,
"text": "Below program illustrate the Serialize() function.Program:<?php // Complex array $myvar = array( 'hello', 42, array(1, 'two'), 'apple'); // Convert to a string $string = serialize($myvar); // Printing the serialized data echo $string; ?> "
},
{
"code": "<?php // Complex array $myvar = array( 'hello', 42, array(1, 'two'), 'apple'); // Convert to a string $string = serialize($myvar); // Printing the serialized data echo $string; ?> ",
"e": 1575,
"s": 1370,
"text": null
},
{
"code": null,
"e": 1663,
"s": 1575,
"text": "Output:a:4:{i:0;s:5:\"hello\";i:1;i:42;i:2;a:2:{i:\n0;i:1;i:1;s:3:\"two\";}i:3;s:5:\"apple\";}"
},
{
"code": null,
"e": 1744,
"s": 1663,
"text": "a:4:{i:0;s:5:\"hello\";i:1;i:42;i:2;a:2:{i:\n0;i:1;i:1;s:3:\"two\";}i:3;s:5:\"apple\";}"
},
{
"code": null,
"e": 1932,
"s": 1744,
"text": "Unserialize() Function: The unserialize() is an inbuilt function php that is used to unserialize the given serialized array to get back to the original value of the complex array, $myvar."
},
{
"code": null,
"e": 1972,
"s": 1932,
"text": "Syntax:unserialize( $serialized_array )"
},
{
"code": null,
"e": 2005,
"s": 1972,
"text": "unserialize( $serialized_array )"
},
{
"code": null,
"e": 2370,
"s": 2005,
"text": "Below program illustrate both serialize() and unserialize() functions:Program:<?php // Complex array $myvar = array( 'hello', 42, array(1, 'two'), 'apple'); // Serialize the above data $string = serialize($myvar); // Unserializing the data in $string $newvar = unserialize($string); // Printing the unserialized data print_r($newvar); ?> "
},
{
"code": "<?php // Complex array $myvar = array( 'hello', 42, array(1, 'two'), 'apple'); // Serialize the above data $string = serialize($myvar); // Unserializing the data in $string $newvar = unserialize($string); // Printing the unserialized data print_r($newvar); ?> ",
"e": 2657,
"s": 2370,
"text": null
},
{
"code": null,
"e": 2805,
"s": 2657,
"text": "Output:Array\n(\n [0] => hello\n [1] => 42\n [2] => Array\n (\n [0] => 1\n [1] => two\n )\n\n [3] => apple\n)\n"
},
{
"code": null,
"e": 2946,
"s": 2805,
"text": "Array\n(\n [0] => hello\n [1] => 42\n [2] => Array\n (\n [0] => 1\n [1] => two\n )\n\n [3] => apple\n)\n"
},
{
"code": null,
"e": 3023,
"s": 2946,
"text": "Note: For more depth knowledge you can check PHP | Serializing Data article."
},
{
"code": null,
"e": 3034,
"s": 3023,
"text": "PHP-basics"
},
{
"code": null,
"e": 3041,
"s": 3034,
"text": "Picked"
},
{
"code": null,
"e": 3045,
"s": 3041,
"text": "PHP"
},
{
"code": null,
"e": 3062,
"s": 3045,
"text": "Web Technologies"
},
{
"code": null,
"e": 3066,
"s": 3062,
"text": "PHP"
},
{
"code": null,
"e": 3164,
"s": 3066,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3209,
"s": 3164,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 3259,
"s": 3209,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 3283,
"s": 3259,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 3335,
"s": 3283,
"text": "How to delete an array element based on key in PHP?"
},
{
"code": null,
"e": 3379,
"s": 3335,
"text": "How to pop an alert message box using PHP ?"
},
{
"code": null,
"e": 3441,
"s": 3379,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3474,
"s": 3441,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3535,
"s": 3474,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3585,
"s": 3535,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to copy text to the clipboard in React.js ? | 12 Mar, 2021
The following example covers how to copy text to the clipboard in React JS using useState() hook.
Prerequisite:
Basic knowledge of npm & create-react-app command.
Basic knowledge of styled-components.
Basic Knowledge of useState() React hooks.
Basic Setup: You will start a new project using create-react-app using the following command:
npx create-react-app react-copy-text
Now go to your react-copy-text folder by typing the given command in the terminal.
cd react-copy-text
Required module: Install the dependencies required in this project by typing the given command in the terminal.
npm install --save styled-components
npm install --save react-copy-to-clipboard
Now create the components folder in src then go to the components folder and create two files Clipboard.js and Styles.js.
Project Structure: The file structure in the project will look like this.
Example: We create a state with the first element copyText as an initial state having a value of the empty string and the second element as function setCopyText() for updating the state. Then a function is created by the name handleCopyText which sets the state value to the text we enter the input field. Another function copyToClipboard is created to copy the updated state value to the clipboard.
When we enter a text in our input field, handleCopyText function gets triggered through onChange event which sets the state to that entered value. Now when we click on the button ‘Copy to Clipboard’, the function copyToClipboard gets triggered through onClick event which copies the state value to the clipboard with copy() function. Now we can copy our text anywhere by just clicking Ctrl+V key.
Clipboard.js
import React,{useState} from 'react'import copy from "copy-to-clipboard"; import { Heading, Input1, Input2, Container, Button } from './Styles' const Clipboard = () => { const [copyText, setCopyText] = useState(''); const handleCopyText = (e) => { setCopyText(e.target.value); } const copyToClipboard = () => { copy(copyText); alert(`You have copied "${copyText}"`); } return ( <div> <Heading>GeeksForGeeks</Heading> <Container> <Input1 type="text" value={copyText} onChange={handleCopyText} placeholder='Enter the text you want to copy' /> <Button onClick={copyToClipboard}> Copy to Clipboard </Button> <Input2 type="text" placeholder='Enter the text you have copied' /> </Container> </div> )} export default Clipboard;
Styles.js
import styled from 'styled-components'; export const Container = styled.div` width: 600px; margin: 40px auto; position: relative;`export const Heading = styled.h1` text-align: center; color: green;`; export const Input1 = styled.input` height: 50px; width: 100%; padding: 0; font-size: 25px;`export const Input2 = styled.input` height: 50px; width: 100%; padding: 0; font-size: 25px; margin-top: 70px;` export const Button = styled.button` padding: 20px; font-size: 20px; position: relative; left: 30%; margin-top: 10px; cursor: pointer;`;
App.js
import Clipboard from './components/Clipboard' function App() { return ( <Clipboard /> );} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS useNavigate() Hook
How to install bootstrap in React.js ?
How to create a multi-page website using React.js ?
How to do crud operations in ReactJS ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n12 Mar, 2021"
},
{
"code": null,
"e": 150,
"s": 52,
"text": "The following example covers how to copy text to the clipboard in React JS using useState() hook."
},
{
"code": null,
"e": 164,
"s": 150,
"text": "Prerequisite:"
},
{
"code": null,
"e": 215,
"s": 164,
"text": "Basic knowledge of npm & create-react-app command."
},
{
"code": null,
"e": 253,
"s": 215,
"text": "Basic knowledge of styled-components."
},
{
"code": null,
"e": 296,
"s": 253,
"text": "Basic Knowledge of useState() React hooks."
},
{
"code": null,
"e": 390,
"s": 296,
"text": "Basic Setup: You will start a new project using create-react-app using the following command:"
},
{
"code": null,
"e": 427,
"s": 390,
"text": "npx create-react-app react-copy-text"
},
{
"code": null,
"e": 510,
"s": 427,
"text": "Now go to your react-copy-text folder by typing the given command in the terminal."
},
{
"code": null,
"e": 529,
"s": 510,
"text": "cd react-copy-text"
},
{
"code": null,
"e": 641,
"s": 529,
"text": "Required module: Install the dependencies required in this project by typing the given command in the terminal."
},
{
"code": null,
"e": 721,
"s": 641,
"text": "npm install --save styled-components\nnpm install --save react-copy-to-clipboard"
},
{
"code": null,
"e": 843,
"s": 721,
"text": "Now create the components folder in src then go to the components folder and create two files Clipboard.js and Styles.js."
},
{
"code": null,
"e": 917,
"s": 843,
"text": "Project Structure: The file structure in the project will look like this."
},
{
"code": null,
"e": 1317,
"s": 917,
"text": "Example: We create a state with the first element copyText as an initial state having a value of the empty string and the second element as function setCopyText() for updating the state. Then a function is created by the name handleCopyText which sets the state value to the text we enter the input field. Another function copyToClipboard is created to copy the updated state value to the clipboard."
},
{
"code": null,
"e": 1714,
"s": 1317,
"text": "When we enter a text in our input field, handleCopyText function gets triggered through onChange event which sets the state to that entered value. Now when we click on the button ‘Copy to Clipboard’, the function copyToClipboard gets triggered through onClick event which copies the state value to the clipboard with copy() function. Now we can copy our text anywhere by just clicking Ctrl+V key."
},
{
"code": null,
"e": 1727,
"s": 1714,
"text": "Clipboard.js"
},
{
"code": "import React,{useState} from 'react'import copy from \"copy-to-clipboard\"; import { Heading, Input1, Input2, Container, Button } from './Styles' const Clipboard = () => { const [copyText, setCopyText] = useState(''); const handleCopyText = (e) => { setCopyText(e.target.value); } const copyToClipboard = () => { copy(copyText); alert(`You have copied \"${copyText}\"`); } return ( <div> <Heading>GeeksForGeeks</Heading> <Container> <Input1 type=\"text\" value={copyText} onChange={handleCopyText} placeholder='Enter the text you want to copy' /> <Button onClick={copyToClipboard}> Copy to Clipboard </Button> <Input2 type=\"text\" placeholder='Enter the text you have copied' /> </Container> </div> )} export default Clipboard;",
"e": 2691,
"s": 1727,
"text": null
},
{
"code": null,
"e": 2701,
"s": 2691,
"text": "Styles.js"
},
{
"code": "import styled from 'styled-components'; export const Container = styled.div` width: 600px; margin: 40px auto; position: relative;`export const Heading = styled.h1` text-align: center; color: green;`; export const Input1 = styled.input` height: 50px; width: 100%; padding: 0; font-size: 25px;`export const Input2 = styled.input` height: 50px; width: 100%; padding: 0; font-size: 25px; margin-top: 70px;` export const Button = styled.button` padding: 20px; font-size: 20px; position: relative; left: 30%; margin-top: 10px; cursor: pointer;`;",
"e": 3284,
"s": 2701,
"text": null
},
{
"code": null,
"e": 3291,
"s": 3284,
"text": "App.js"
},
{
"code": "import Clipboard from './components/Clipboard' function App() { return ( <Clipboard /> );} export default App;",
"e": 3409,
"s": 3291,
"text": null
},
{
"code": null,
"e": 3522,
"s": 3409,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 3532,
"s": 3522,
"text": "npm start"
},
{
"code": null,
"e": 3631,
"s": 3532,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 3647,
"s": 3631,
"text": "React-Questions"
},
{
"code": null,
"e": 3655,
"s": 3647,
"text": "ReactJS"
},
{
"code": null,
"e": 3672,
"s": 3655,
"text": "Web Technologies"
},
{
"code": null,
"e": 3770,
"s": 3672,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3808,
"s": 3770,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 3835,
"s": 3808,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 3874,
"s": 3835,
"text": "How to install bootstrap in React.js ?"
},
{
"code": null,
"e": 3926,
"s": 3874,
"text": "How to create a multi-page website using React.js ?"
},
{
"code": null,
"e": 3965,
"s": 3926,
"text": "How to do crud operations in ReactJS ?"
},
{
"code": null,
"e": 3998,
"s": 3965,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4060,
"s": 3998,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4121,
"s": 4060,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4171,
"s": 4121,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
VueJS - Directives | Directives are instruction for VueJS to do things in a certain way. We have already seen directives such as v-if, v-show, v-else, v-for, v-bind , v-model, v-on, etc.
In this chapter, we will take a look at custom directives. We will create global directives similar to how we did for components.
Vue.directive('nameofthedirective', {
bind(e1, binding, vnode) {
}
})
We need to create a directive using Vue.directive. It takes the name of the directive as shown above. Let us consider an example to show the details of the working of directives.
<html>
<head>
<title>VueJs Instance</title>
<script type = "text/javascript" src = "js/vue.js"></script>
</head>
<body>
<div id = "databinding">
<div v-changestyle>VueJS Directive</div>
</div>
<script type = "text/javascript">
Vue.directive("changestyle",{
bind(e1,binding, vnode) {
console.log(e1);
e1.style.color = "red";
e1.style.fontSize = "30px";
}
});
var vm = new Vue({
el: '#databinding',
data: {
},
methods : {
},
});
</script>
</body>
</html>
In this example, we have created a custom directive changestyle as shown in the following piece of code.
Vue.directive("changestyle",{
bind(e1,binding, vnode) {
console.log(e1);
e1.style.color = "red";
e1.style.fontSize = "30px";
}
});
We are assigning the following changestyle to a div.
<div v-changestyle>VueJS Directive</div>
If we see in the browser, it will display the text VueJs Directive in red color and the fontsize is increased to 30px.
We have used the bind method, which is a part of the directive. It takes three arguments e1, the element to which the custom directive needs to be applied. Binding is like arguments passed to the custom directive, e.g. v-changestyle = ”{color:’green’}”, where green will be read in the binding argument and vnode is the element, i.e. nodename.
In the next example, we have consoled all the arguments and its shows what details each of them give.
Following is an example with a value passed to the custom directive.
<html>
<head>
<title>VueJs Instance</title>
<script type = "text/javascript" src = "js/vue.js"></script>
</head>
<body>
<div id = "databinding">
<div v-changestyle = "{color:'green'}">VueJS Directive</div>
</div>
<script type = "text/javascript">
Vue.directive("changestyle",{
bind(e1,binding, vnode) {
console.log(e1);
console.log(binding.value.color);
console.log(vnode);
e1.style.color=binding.value.color;
e1.style.fontSize = "30px";
}
});
var vm = new Vue({
el: '#databinding',
data: {
},
methods : {
},
});
</script>
</body>
</html>
The color of the text is changed to green. The value is passed using the following piece of code.
<div v-changestyle = "{color:'green'}">VueJS Directive</div>
And it is accessed using the following piece of code.
Vue.directive("changestyle",{
bind(e1,binding, vnode) {
console.log(e1);
console.log(binding.value.color);
console.log(vnode);
e1.style.color=binding.value.color;
e1.style.fontSize = "30px";
}
});
VueJS supports filters that help with text formatting. It is used along with v-bind and interpolations ({{}}). We need a pipe symbol at the end of JavaScript expression for filters.
<html>
<head>
<title>VueJs Instance</title>
<script type = "text/javascript" src = "js/vue.js"></script>
</head>
<body>
<div id = "databinding">
<input v-model = "name" placeholder = "Enter Name" /><br/>
<span style = "font-size:25px;"><b>Letter count is : {{name | countletters}}</b></span>
</div>
<script type = "text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
name : ""
},
filters : {
countletters : function(value) {
return value.length;
}
}
});
</script>
</body>
</html>
In the above example, we have created a simple filter countletters. Countletters filter counts the numbers of characters entered in the textbox. To make use of filters, we need to use the filter property and define the filter used, by the following piece of code.
filters : {
countletters : function(value) {
return value.length;
}
}
We are defining the method countletters and returning the length of the string entered.
To use filter in the display, we have used the pipe operator and the name of the filter, i.e. countletters.
<span style = "font-size:25px;"><b>Letter count is : {{name | countletters}}</b></span>
Following is the display in the browser.
We can also pass arguments to the filter using the following piece of code.
<span style = "font-size:25px;"><b>Letter count is : {{name | countletters('a1', 'a2')}}</b></span>
Now, the countletters will have three params, i.e. message, a1, and a2.
We can also pass multiple filters to the interpolation using the following piece of code.
<span style = "font-size:25px;"><b>Letter count is : {{name | countlettersA, countlettersB}}</b></span>
In the filter property countlettersA and countlettersB will be the two methods and the countlettersA will pass the details to countlettersB. | [
{
"code": null,
"e": 2236,
"s": 2070,
"text": "Directives are instruction for VueJS to do things in a certain way. We have already seen directives such as v-if, v-show, v-else, v-for, v-bind , v-model, v-on, etc."
},
{
"code": null,
"e": 2366,
"s": 2236,
"text": "In this chapter, we will take a look at custom directives. We will create global directives similar to how we did for components."
},
{
"code": null,
"e": 2443,
"s": 2366,
"text": "Vue.directive('nameofthedirective', {\n bind(e1, binding, vnode) {\n }\n})\n"
},
{
"code": null,
"e": 2622,
"s": 2443,
"text": "We need to create a directive using Vue.directive. It takes the name of the directive as shown above. Let us consider an example to show the details of the working of directives."
},
{
"code": null,
"e": 3297,
"s": 2622,
"text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"databinding\">\n <div v-changestyle>VueJS Directive</div>\n </div>\n <script type = \"text/javascript\">\n Vue.directive(\"changestyle\",{\n bind(e1,binding, vnode) {\n console.log(e1);\n e1.style.color = \"red\";\n e1.style.fontSize = \"30px\";\n }\n });\n var vm = new Vue({\n el: '#databinding',\n data: {\n },\n methods : {\n },\n });\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 3402,
"s": 3297,
"text": "In this example, we have created a custom directive changestyle as shown in the following piece of code."
},
{
"code": null,
"e": 3557,
"s": 3402,
"text": "Vue.directive(\"changestyle\",{\n bind(e1,binding, vnode) {\n console.log(e1);\n e1.style.color = \"red\";\n e1.style.fontSize = \"30px\";\n }\n});"
},
{
"code": null,
"e": 3610,
"s": 3557,
"text": "We are assigning the following changestyle to a div."
},
{
"code": null,
"e": 3651,
"s": 3610,
"text": "<div v-changestyle>VueJS Directive</div>"
},
{
"code": null,
"e": 3770,
"s": 3651,
"text": "If we see in the browser, it will display the text VueJs Directive in red color and the fontsize is increased to 30px."
},
{
"code": null,
"e": 4114,
"s": 3770,
"text": "We have used the bind method, which is a part of the directive. It takes three arguments e1, the element to which the custom directive needs to be applied. Binding is like arguments passed to the custom directive, e.g. v-changestyle = ”{color:’green’}”, where green will be read in the binding argument and vnode is the element, i.e. nodename."
},
{
"code": null,
"e": 4216,
"s": 4114,
"text": "In the next example, we have consoled all the arguments and its shows what details each of them give."
},
{
"code": null,
"e": 4285,
"s": 4216,
"text": "Following is an example with a value passed to the custom directive."
},
{
"code": null,
"e": 5076,
"s": 4285,
"text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"databinding\">\n <div v-changestyle = \"{color:'green'}\">VueJS Directive</div>\n </div>\n <script type = \"text/javascript\">\n Vue.directive(\"changestyle\",{\n bind(e1,binding, vnode) {\n console.log(e1);\n console.log(binding.value.color);\n console.log(vnode);\n e1.style.color=binding.value.color;\n e1.style.fontSize = \"30px\";\n }\n });\n var vm = new Vue({\n el: '#databinding',\n data: {\n },\n methods : {\n },\n });\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 5174,
"s": 5076,
"text": "The color of the text is changed to green. The value is passed using the following piece of code."
},
{
"code": null,
"e": 5522,
"s": 5174,
"text": "<div v-changestyle = \"{color:'green'}\">VueJS Directive</div>\nAnd it is accessed using the following piece of code.\nVue.directive(\"changestyle\",{\n bind(e1,binding, vnode) {\n console.log(e1);\n console.log(binding.value.color);\n console.log(vnode);\n e1.style.color=binding.value.color;\n e1.style.fontSize = \"30px\";\n }\n});"
},
{
"code": null,
"e": 5704,
"s": 5522,
"text": "VueJS supports filters that help with text formatting. It is used along with v-bind and interpolations ({{}}). We need a pipe symbol at the end of JavaScript expression for filters."
},
{
"code": null,
"e": 6405,
"s": 5704,
"text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"databinding\">\n <input v-model = \"name\" placeholder = \"Enter Name\" /><br/>\n <span style = \"font-size:25px;\"><b>Letter count is : {{name | countletters}}</b></span>\n </div>\n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#databinding',\n data: {\n name : \"\"\n },\n filters : {\n countletters : function(value) {\n return value.length;\n }\n }\n });\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 6669,
"s": 6405,
"text": "In the above example, we have created a simple filter countletters. Countletters filter counts the numbers of characters entered in the textbox. To make use of filters, we need to use the filter property and define the filter used, by the following piece of code."
},
{
"code": null,
"e": 6751,
"s": 6669,
"text": "filters : {\n countletters : function(value) {\n return value.length;\n }\n}"
},
{
"code": null,
"e": 6839,
"s": 6751,
"text": "We are defining the method countletters and returning the length of the string entered."
},
{
"code": null,
"e": 6947,
"s": 6839,
"text": "To use filter in the display, we have used the pipe operator and the name of the filter, i.e. countletters."
},
{
"code": null,
"e": 7035,
"s": 6947,
"text": "<span style = \"font-size:25px;\"><b>Letter count is : {{name | countletters}}</b></span>"
},
{
"code": null,
"e": 7076,
"s": 7035,
"text": "Following is the display in the browser."
},
{
"code": null,
"e": 7152,
"s": 7076,
"text": "We can also pass arguments to the filter using the following piece of code."
},
{
"code": null,
"e": 7252,
"s": 7152,
"text": "<span style = \"font-size:25px;\"><b>Letter count is : {{name | countletters('a1', 'a2')}}</b></span>"
},
{
"code": null,
"e": 7324,
"s": 7252,
"text": "Now, the countletters will have three params, i.e. message, a1, and a2."
},
{
"code": null,
"e": 7414,
"s": 7324,
"text": "We can also pass multiple filters to the interpolation using the following piece of code."
},
{
"code": null,
"e": 7518,
"s": 7414,
"text": "<span style = \"font-size:25px;\"><b>Letter count is : {{name | countlettersA, countlettersB}}</b></span>"
}
] |
Top 50 IP addressing interview questions and answers | 15 Sep, 2021
1. What is IP address?
IP address is an address having information about how to reach a specific host, especially outside the LAN. An IP address is 32 bit unique address having an address space of 232. Generally, there are two notations in which IP address is written, dotted decimal notation and hexadecimal notation. For more details, please refer introduction of Classful IP addressing.
2. What are the different classes of IP addresses and give the range of each class?
IP address is an address having information about how to reach a specific host, especially outside the LAN. An IP address is 32-bit unique address having an address space of 232.
For more details, please refer introduction of Classful IP addressing.
3. What is subnet mask?
A subnet mask is a 32-bit number that is used to identify the subnet of an IP address. The subnet mask is a combination of 1’s and 0’s. 1’s represents network and subnet ID while 0’s represents the host ID. In this case, the subnet mask is,
11111111.11111111.11111111.11000000
or
255.255.255.192
So, in order to get the network to which the destination address belongs, we have to bitwise & with a subnet mask.
11111111.11111111.11111111.11000000
&& 11001000.00000001.00000010.00010100
-----------------------------------------------------
11001000.00000001.00000010.00000000
The address belongs to,
11001000.00000001.00000010.00000000
or
200.1.2.0
For more details, please refer Role of Subnet Mask article.
4. Why CIDR is used?
The problem with this classful addressing method is that millions of class A addresses are wasted, many of the class B addresses are wasted, whereas, number of addresses available in class C is so small that it cannot cater to the needs of organizations. Class D addresses are used for multicast routing and are therefore available as a single block only. Class E addresses are reserved. Since there are these problems, Classful networking was replaced by Classless Inter-Domain Routing (CIDR). For more details, please refer CIDR full-form to the article.
5. What is the LOOPBACK address?
Loopback Address is used to let a system send a message to itself to make sure that the TCP/IP stack is installed correctly on the machine. For more details, please refer Local Broadcast and Loopback address article.
6. What is a Default Gateway?
In organizational systems, a gateway is a node that routes the traffic from a workstation to another network segment. The default gateway commonly connects the internal networks and the outside network (Internet). In such a situation, the gateway node could also act as a proxy server and a firewall. The gateway is also associated with both a router, which uses headers and forwarding tables to determine where packets are sent and a switch, which provides the actual path for the packet in and out of the gateway.
For more details, please refer to Working of different layers in the Computer network article.
7. Why Hop limit field is used?
Hop Limit: Hop Limit field is the same as TTL in IPv4 packets. It indicates the maximum number of intermediate nodes IPv6 packet is allowed to travel. Its value gets decremented by one, by each node that forwards the packet and the packet is discarded if the value decreases to 0. This is used to discard the packets that are stuck in an infinite loop because of some routing error.
For more details, please refer to Internet Protocol version 6 (IPv6) Header article.
8. What protocol is used by PING?
ICMP (Internet Control Message Protocol) is used by PING. For more details, please refer to the Difference between Ping and Traceroute article.
9. What is used of Tracert?
Traceroute is a widely used command-line utility available in almost all operating systems. It shows you the complete route to a destination address. It also shows the time is taken (or delays) between intermediate routers. For more details, please refer to the Difference between Ping and Traceroute article.
10. Name the ports used by FTP protocol?
Basically, FTP protocol uses two ports:
Control connection: For sending control information like user identification, password, commands to change the remote directory, commands to retrieve and store files, etc., FTP makes use of connections. The control connection is initiated on port number 21.
Data connection: For sending the actual file, FTP makes use of a data connection. A data connection is initiated on port number 20. For more details, please refer to File Transfer Protocol (FTP) in the Application Layer article.
11. What is MAC address?
MAC Addresses are unique 48-bit hardware numbers of computers, which are embedded into a network card (known as Network Interface Card) during the time of manufacturing. The MAC Address is also known as the Physical Address of a network device. In IEEE 802 standard, the Data Link Layer is divided into two sublayers –
Logical Link Control(LLC) SublayerMedia Access Control(MAC) Sublayer
Logical Link Control(LLC) Sublayer
Media Access Control(MAC) Sublayer
The MAC address is used by the Media Access Control (MAC) sublayer of the Data-Link Layer. MAC Address is unique worldwide since millions of network devices exist and we need to uniquely identify each.
For more details, please refer to Introduction of MAC Address in Computer Network article.
12. Explain ARP?
Address Resolution Protocol is a communication protocol used for discovering physical addresses associated with a given network address. Typically, ARP is a network layer to data link layer mapping process, which is used to discover MAC addresses for a given Internet Protocol Address.In order to send the data to the destination, having an IP address is necessary but not sufficient; we also need the physical address of the destination machine. ARP is used to get the physical address (MAC address) of the destination machine.
Before sending the IP packet, the MAC address of the destination must be known. If not so, then the sender broadcasts the ARP-discovery packet requesting the MAC address of the intended destination. Since ARP-discovery is broadcast, every host inside that network will get this message but the packet will be discarded by everyone except that intended receiver host whose IP is associated. Now, this receiver will send a unicast packet with its MAC address (ARP-reply) to the sender of the ARP-discovery packet. After the original sender receives the ARP-reply, it updates ARP-cache and starts sending a unicast message to the destination.
For more details, please refer to the How Address Resolution Protocol works article.
13. What is MTU?
A maximum transmission unit also called MTU, is a term used in networking and operating systems. It defines the largest size of the packet that can be transmitted as a single entity in a network connection. The size of the MTU dictates the amount of data that can be transmitted in bytes over a network. For more details, please refer What is MTU article.
14. If a class B network on the Internet has a subnet mask of 255.255.248.0, what is the maximum number of hosts per subnet?The binary representation of the subnet mask is 11111111.11111111.11111000. 00000000. There are 21 bits set in a subnet. So 11 (32-21) bits are left for host ids. The total possible value of host ids is 2^11 = 2048. Out of these 2048 values, 2 addresses are reserved. The address with all bits as 1 is reserved as broadcast address and the address with all host id bits as 0 is used as a network address of the subnet.In general, the number of addresses usable for addressing specific hosts in each network is always 2^N – 2 where N is the number of bits for host id. So the answer is 2046.
15. What is IP multicast?
Multicasting has one/more senders and one/more recipients participate in data transfer traffic. In multicasting, traffic reclines between the boundaries of unicast and broadcast. Its server’s direct single copies of data streams and that are then simulated and routed to hosts that request it. IP multicast requires the support of some other protocols such as Internet Group Management Protocol (IGMP), Multicast routing for its work. And also, in Classful IP, addressing Class D is reserved for multicast groups.
16. Difference between public and private IP addresses?
Public IP address–A public IP address is an Internet Protocol address, encrypted by various servers/devices. That’s when you connect these devices with your internet connection. This is the same IP address we show on our homepage. So why the second page? Well, not all people speak the IP language. We want to make it as easy as possible for everyone to get the information they need. Some even call this their external IP address. A public Internet Protocol address is an Internet Protocol address accessed over the Internet. Like the postal address used to deliver mail to your home, the public Internet Protocol address is a different international Internet Protocol address assigned to a computer device. The web server, email server, and any server device that has direct access to the Internet are those who will enter the public Internet Protocol address. Internet Address Protocol is unique worldwide and is only supplied with a unique device.Private IP address–Everything that connects to your Internet network has a private IP address. This includes computers, smartphones, and tablets but also any Bluetooth-enabled devices such as speakers, printers, or smart TVs. With the growing internet of things, the number of private IP addresses you have at home is likely to increase. Your router needs a way to identify these things separately, and most things need a way to get to know each other. Therefore, your router generates private IP addresses that are unique identifiers for each device that separates the network.
Public IP address–A public IP address is an Internet Protocol address, encrypted by various servers/devices. That’s when you connect these devices with your internet connection. This is the same IP address we show on our homepage. So why the second page? Well, not all people speak the IP language. We want to make it as easy as possible for everyone to get the information they need. Some even call this their external IP address. A public Internet Protocol address is an Internet Protocol address accessed over the Internet. Like the postal address used to deliver mail to your home, the public Internet Protocol address is a different international Internet Protocol address assigned to a computer device. The web server, email server, and any server device that has direct access to the Internet are those who will enter the public Internet Protocol address. Internet Address Protocol is unique worldwide and is only supplied with a unique device.
Private IP address–Everything that connects to your Internet network has a private IP address. This includes computers, smartphones, and tablets but also any Bluetooth-enabled devices such as speakers, printers, or smart TVs. With the growing internet of things, the number of private IP addresses you have at home is likely to increase. Your router needs a way to identify these things separately, and most things need a way to get to know each other. Therefore, your router generates private IP addresses that are unique identifiers for each device that separates the network.
17. Can you explain what subnetting?
When a bigger network is divided into smaller networks, in order to maintain security, then that is known as Subnetting. so, maintenance is easier for smaller networks. For more details please read an introduction to a subnetting article.
18. Do you know what is Network Address Translation?
To access the Internet, one public IP address is needed, but we can use a private IP address on our private network. The idea of NAT is to allow multiple devices to access the Internet through a single public address. To achieve this, the translation of a private IP address to a public IP address is required. Network Address Translation (NAT) is a process in which one or more local IP addresses is translated into one or more Global IP addresses and vice versa in order to provide Internet access to the local hosts. Also, it does the translation of port numbers i.e. masks the port number of the host with another port number in the packet that will be routed to the destination. It then makes the corresponding entries of IP address and port number in the NAT table. NAT generally operates on a router or firewall. For more details, please refer to Network Address Translation.
19. An organization requires a range of IP addresses to assign one to each of its 1500 computers. The organization has approached an Internet Service Provider (ISP) for this task. The ISP uses CIDR and serves the requests from the available IP address space 202.61.0.0/17. The ISP wants to assign address space to the organization which will minimize the number of routing entries in the ISP’s router using route aggregation. To calculate the address spaces are potential candidates from which the ISP can allow any one of the organizations?
Subnet Mask for the given IP address:
202.61.0.0/17
⇒ 11111111 11111111 10000000 00000000
⇒ 255.255.128.0
Now, since we need 1500 hosts, so, bits for host address,
= ceiling (log2 (1500))
= ceiling (10.55)
= 11 bits for host address
So, the last 11 bits will be for host addresses:
00000000.00000000 → 00000111.11111111 (0.0 → 7.255)
00001000.00000000 → 00010000.00000000 (8.0 - 15.255)
00001111.11111111 → 00010111.11111111 (16.0 - 23.255)
Sequences are 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 96, 104, 112, 120.
Hence, 64 and 104 are present in the sequence, so 202.61.104.0 / 21 and 202.61.64.0 / 21 are the possible IP addresses.
20. Explain the difference between Static and Dynamic IP?
For more details, please refer to Difference between Static and Dynamic IP addresses.
21. How will my computer get its IP Address?
To get IP address :
Click on start ->Programs->Accessories->Command prompt.Type ipconfig on command prompt and press enter key.
Click on start ->Programs->Accessories->Command prompt.
Type ipconfig on command prompt and press enter key.
By using these steps, you can get your PC IP address, Subnet Mask, and default gateway details.
22. What are the features of Gateway?
Gateways provide a wide variety of features. Some of which are:
Gateways work as a network bridge for data transmission as it makes the transmission of data possible to transmit with more ease and does not demand high storage capacity.
Gateways create a structural temporary storeroom for the data transmitted by the server and data requests made by the user end.
Gateways made the transmission more feasible as it queued up all the data and divide it into small packets of data rather than sending it bulk. Data transmitted through Gateway is divided into various useful and small packets each having its individual significance and a role to play while processing data.
Gateways made the data more secure if the modifications to the gateway could be done which then could create more reliability over smart devices.
Gateways optimize the data for search engines, applications, and servers by implanting better readability to the content so that a machine could understand and optimize data with ease. For more details, please refer to the Introduction of Gateways.
23. Is Ipv6 Backward Compatible With Ipv4?
No, IPv6 is not backward compatible with IPv4 protocol. For more details, please refer to the Internet protocol version 6 article.
24. Is It Possible To Have An Ipv4 And An Ipv6 Addresses Simultaneously?
Yes, it is possible to have an IPv4 and IPv6 addresses simultaneously. For more details, please refer to the Internet protocol version 6 and the difference between IPv4 and IPv6 articles.
25. What is TTL?
The lifespan or lifetime of data that is being sent. Once after that specified time is over or elapsed, the data will be discarded Or it can also be stated as the number of hops that packet is set to exist in the network, after which that packet is discarded. The purpose of the TTL field is to avoid a situation in which an undeliverable datagram keeps circulating in the network. For more details, please refer to the difference between RTT and TTL article.
26. If the TTL field has the value of 10. How many routers (max) can process this datagram?
TTL stands for Time to Live. This field specifies the life of the IP packet based on the number of hops it makes ( number of routers it goes through). TTL field is decremented by one each time the datagram is processed by a router. When the value is 0, the packet is automatically destroyed. For more details, please refer to the difference between RTT and TTL articles.
27. If the value in the protocol field is 17, the transport layer protocol used is which protocol?
If the value in the protocol field is 17, the transport layer protocol uses UDP (User Datagram Protocol). For more details, please refer to UDP article.
28. What happens in classless addressing, if there are no classes but addresses are still granted?
In classless addressing, there are no classes but addresses are still granted in blocks. The total number of addresses in a block of classless IP addresses = 2(32 – CIDR_value). For more details, please refer to the introduction of Classful IP addressing.
29. Suppose two IPv6 nodes want to interoperate using IPv6 datagrams, but they are connected to each other by intervening IPv4 routers. Then what is the best solution?
If two IPv6 nodes want to interoperate using IPv6 datagrams, they are connected to each other by intervening IPv4 routers. Then tunneling is the best solution. For more details, please refer to Internet protocol version 6 article.
30. What is IANA?
IANA, the Internet Assigned Numbers Authority, is an administrative function of the Internet that keeps track of IP addresses, domain names, and protocol parameter identifiers that are used by Internet standards. Some of these identifiers are parameters, such as those used by Internet protocols (like TCP, ICMP or UDP) to specify functions and behaviour; some of them represent Internet addresses and others represent domain names. Regardless of the type of identifier, the IANA function (IANA for short below) ensures that values are managed for uniqueness and made available in publicly accessible registries.
31. What is DHCP?
DHCP is an abbreviation for Dynamic Host Configuration Protocol. It is an application layer protocol used by hosts for obtaining network setup information. The DHCP is controlled by a DHCP server that dynamically distributes network configuration parameters such as IP addresses, subnet mask, and gateway address. For more details, please refer to Dynamic Host Configuration Protocol (DHCP) article.
32. How can you manage a network using a router?
Routers have built-in console that lets you configure different settings, like security and data logging.We can assign restrictions to computers, such as what resources they are allowed to access, or what particular time of the day they can browse the internet.We can even put restrictions on what websites are not viewable across the entire network. For more details, please refer to the introduction of a Router.
33. What is ipconfig?
IPCONFIG stands for Internet Protocol Configuration. This is a command-line application that displays all the current TCP/IP (Transmission Control Protocol/Internet Protocol) network configuration, refreshes the DHCP (Dynamic Host Configuration Protocol) and DNS (Domain Name Server). It also displays an IP address, subnet mask, and a default gateway for all adapters. It is available for Microsoft Windows, ReactOS, and Apple macOS. ReactOS version was developed by Ged Murphy and licensed under the General Public License. For more details, please refer to ipconfig full form article.
34. When you move the NIC cards from one PC to another PC, does the MAC address get transferred as well?
Yes, if we move the NIC cards from one PC to another PC, then the MAC address also gets transferred, because the MAC address is hard-wired into the NIC circuit, not the personal computer. This also means that a PC can have a different MAC address when another one replaces the NIC card.
35. Explain clustering support?
Clustering support refers to the ability of a network operating system to connect multiple servers in a fault-tolerant group. The main purpose of this is the in the event that one server fails, all processing will continue on with the next server in the cluster.
36. What is Brouter?
Brouter – It is also known as the bridging router is a device that combines features of both bridge and router. It can work either at the data link layer or a network layer. Working as a router, it is capable of routing packets across networks, and working as the bridge, it is capable of filtering local area network traffic. For more details, please refer to the difference between Router and Brouter article.
37. Explain the features of VPN?
VPN also ensures security by providing an encrypted tunnel between client and vpn server.VPN is used to bypass many blocked sites.VPN facilitates anonymous browsing by hiding your ip address.Also, the most appropriate Search engine optimization(SEO) is done by analyzing the data from VPN providers which provide country-wise states for browsing a particular product. This method of SEO is used widely by many internet marketing managers to form new strategies.For more details, please refer to Virtual Private Network.
VPN also ensures security by providing an encrypted tunnel between client and vpn server.
VPN is used to bypass many blocked sites.
VPN facilitates anonymous browsing by hiding your ip address.
Also, the most appropriate Search engine optimization(SEO) is done by analyzing the data from VPN providers which provide country-wise states for browsing a particular product. This method of SEO is used widely by many internet marketing managers to form new strategies.For more details, please refer to Virtual Private Network.
38. What are the important differences between MAC address and IP address?
39. What is 127.0.0.1?
In IPv4, IP addresses that start with decimal 127 or that has 01111111 in the first octet are loopback addresses(127.X.X.X). Typically 127.0.0.1 is used as the local loopback address.This leads to the wastage of many potential IP addresses. But in IPv6 ::1 is used as local loopback address and therefore there isn’t any wastage of addresses.
40. What is a DNS?
DNS is a host name to IP address translation service. DNS is a distributed database implemented in a hierarchy of name servers. It is an application layer protocol for message exchange between clients and servers. For more details, please refer to DNS in the application layer.
41. What is the use of a proxy server?
Proxy server refers to a server that acts as an intermediary between the request made by clients, and a particular server for some services or requests for some resources. There are different types of proxy servers available that are put into use according to the purpose of a request made by the clients to the servers. The basic purpose of Proxy servers is to protect the direct connection of Internet clients and internet resources. The proxy server also prevents the identification of the client’s IP address when the client makes any request is made to any other servers. For more details, please refer to Proxy server article.
42. What is the difference between ipconfig and ifconfig commands?
IPCONFIG stands for Internet Protocol Configuration. This is a command-line application that displays all the current TCP/IP (Transmission Control Protocol/Internet Protocol) network configuration, refreshes the DHCP (Dynamic Host Configuration Protocol) and DNS (Domain Name Server). It also displays IP address, subnet mask, and default gateway for all adapters. It is available for Microsoft Windows, ReactOS, and Apple macOS. ReactOS version was developed by Ged Murphy and licensed under the General Public License.
ifconfig(interface configuration) command is used to configure the kernel-resident network interfaces. It is used at boot time to set up the interfaces as necessary. After that, it is usually used when needed during debugging or when you need system tuning. Also, this command is used to assign the IP address and netmask to an interface or to enable or disable a given interface. For more details, please refer to
43. What is the importance of APIPA in networking?
Automatic Private IP Addressing is important in networking because communication can be established properly if you don’t get a response from DHCP Server. APIPA regulates the service, by which the response and status of the main DHCP server at a specific period of time. Apart from that, it can be used as a backup to DHCP because when DHCP stops working, APIPA has the ability to assign IP to the networking hosts.It stops unwanted broadcasting. It uses ARP(Address Resolution Protocol) to confirm the address isn’t currently in use. For more details, please refer to What is APIPA.
44. What is the difference between Firewall and Antivirus?
45. What is SLIP?
SLIP stands for Serial Line Internet Protocol. It is a TCP/IP implementation which was described under RFC 1055 (Request for Comments). SLIP establishes point-to-point serial connections which can be used in dial-up connections, serial ports and routers. It frames the encapsulated IP packets across a serial line for establishing connection while using line speed between 12000 bps and 19.2 Kbps. SLIP was introduced in 1984 when Rick Adams used it to connect 4.2 Berkeley Unix and Sun Microsystems workstations. It soon caught up with the rest of the world as a credible TCP/IP implementation. It has now become obsolete after being replaced by PPP (Point to Point Protocol) which solves many deficiencies present in it. For more details, please refer to
46. What is Kerberos protocol?
Kerberos provides a centralized authentication server whose function is to authenticate users to servers and servers to users. In Kerberos Authentication server and database is used for client authentication. Kerberos runs as a third-party trusted server known as the Key Distribution Center (KDC). Each user and service on the network is a principal.
The main components of Kerberos are:
Authentication Server (AS):The Authentication Server performs the initial authentication and ticket for Ticket Granting Service.
Database:The Authentication Server verifies the access rights of users in the database.
Ticket Granting Server (TGS):The Ticket Granting Server issues the ticket for the Server.
For more details, please refer to Kerberos article.
47. What is HSRP?
Hot Standby Router Protocol (HSRP) is a CISCO proprietary protocol, which provides redundancy for a local subnet. In HSRP, two or more routers give an illusion of a virtual router.
HSRP allows you to configure two or more routers as standby routers and only a single router as an active router at a time. All the routers in a single HSRP group share a single MAC address and IP address, which acts as a default gateway to the local network. The Active router is responsible for forwarding the traffic. If it fails, the Standby router takes up all the responsibilities of the active router and forwards the traffic.
For more details, please refer to HSRP protocol.
48. Why is the MAC address called the Physical address?
The MAC address is a physical address (also called a hardware address) because it physically identifies an item of hardware. MAC addresses use three types of number systems and all use the same format, only the size of the identifier differs. The addresses can be “Universally Managed” or “Locally Managed”. For more details, please refer to Introduction of MAC Address in Computer Network article.
49. Process of DHCP(DORA)?
In DHCP, the client and the server exchange mainly 4 DHCP messages in order to make a connection. This process is known as DORA process (discovery, offer, request, and acknowledgment), but there are 8 DHCP messages in the process. For more details, please refer to Dynamic Host Configuration Protocol (DHCP) article.
50. What is ‘APIPA’?
APIPA stands for Automatic Private IP Addressing (APIPA). It is a feature or characteristic in operating systems (eg. Windows) which enables computers to self-configure an IP address and subnet mask automatically when their DHCP(Dynamic Host Configuration Protocol) server isn’t reachable. The IP address range for APIPA is (169.254.0.1 to 169.254.255.254) having 65, 534 usable IP addresses, with the subnet mask of 255.255.0.0. For more details please read What is APIPA article.
anikakapoor
interview-questions
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Sep, 2021"
},
{
"code": null,
"e": 51,
"s": 28,
"text": "1. What is IP address?"
},
{
"code": null,
"e": 419,
"s": 51,
"text": "IP address is an address having information about how to reach a specific host, especially outside the LAN. An IP address is 32 bit unique address having an address space of 232. Generally, there are two notations in which IP address is written, dotted decimal notation and hexadecimal notation. For more details, please refer introduction of Classful IP addressing."
},
{
"code": null,
"e": 503,
"s": 419,
"text": "2. What are the different classes of IP addresses and give the range of each class?"
},
{
"code": null,
"e": 683,
"s": 503,
"text": "IP address is an address having information about how to reach a specific host, especially outside the LAN. An IP address is 32-bit unique address having an address space of 232."
},
{
"code": null,
"e": 754,
"s": 683,
"text": "For more details, please refer introduction of Classful IP addressing."
},
{
"code": null,
"e": 778,
"s": 754,
"text": "3. What is subnet mask?"
},
{
"code": null,
"e": 1019,
"s": 778,
"text": "A subnet mask is a 32-bit number that is used to identify the subnet of an IP address. The subnet mask is a combination of 1’s and 0’s. 1’s represents network and subnet ID while 0’s represents the host ID. In this case, the subnet mask is,"
},
{
"code": null,
"e": 1076,
"s": 1019,
"text": "11111111.11111111.11111111.11000000 \nor\n255.255.255.192 "
},
{
"code": null,
"e": 1191,
"s": 1076,
"text": "So, in order to get the network to which the destination address belongs, we have to bitwise & with a subnet mask."
},
{
"code": null,
"e": 1366,
"s": 1191,
"text": " 11111111.11111111.11111111.11000000\n&& 11001000.00000001.00000010.00010100\n-----------------------------------------------------\n 11001000.00000001.00000010.00000000 "
},
{
"code": null,
"e": 1390,
"s": 1366,
"text": "The address belongs to,"
},
{
"code": null,
"e": 1441,
"s": 1390,
"text": "11001000.00000001.00000010.00000000 \nor\n200.1.2.0 "
},
{
"code": null,
"e": 1501,
"s": 1441,
"text": "For more details, please refer Role of Subnet Mask article."
},
{
"code": null,
"e": 1522,
"s": 1501,
"text": "4. Why CIDR is used?"
},
{
"code": null,
"e": 2079,
"s": 1522,
"text": "The problem with this classful addressing method is that millions of class A addresses are wasted, many of the class B addresses are wasted, whereas, number of addresses available in class C is so small that it cannot cater to the needs of organizations. Class D addresses are used for multicast routing and are therefore available as a single block only. Class E addresses are reserved. Since there are these problems, Classful networking was replaced by Classless Inter-Domain Routing (CIDR). For more details, please refer CIDR full-form to the article."
},
{
"code": null,
"e": 2112,
"s": 2079,
"text": "5. What is the LOOPBACK address?"
},
{
"code": null,
"e": 2329,
"s": 2112,
"text": "Loopback Address is used to let a system send a message to itself to make sure that the TCP/IP stack is installed correctly on the machine. For more details, please refer Local Broadcast and Loopback address article."
},
{
"code": null,
"e": 2359,
"s": 2329,
"text": "6. What is a Default Gateway?"
},
{
"code": null,
"e": 2876,
"s": 2359,
"text": "In organizational systems, a gateway is a node that routes the traffic from a workstation to another network segment. The default gateway commonly connects the internal networks and the outside network (Internet). In such a situation, the gateway node could also act as a proxy server and a firewall. The gateway is also associated with both a router, which uses headers and forwarding tables to determine where packets are sent and a switch, which provides the actual path for the packet in and out of the gateway. "
},
{
"code": null,
"e": 2972,
"s": 2876,
"text": "For more details, please refer to Working of different layers in the Computer network article. "
},
{
"code": null,
"e": 3005,
"s": 2972,
"text": "7. Why Hop limit field is used?"
},
{
"code": null,
"e": 3388,
"s": 3005,
"text": "Hop Limit: Hop Limit field is the same as TTL in IPv4 packets. It indicates the maximum number of intermediate nodes IPv6 packet is allowed to travel. Its value gets decremented by one, by each node that forwards the packet and the packet is discarded if the value decreases to 0. This is used to discard the packets that are stuck in an infinite loop because of some routing error."
},
{
"code": null,
"e": 3473,
"s": 3388,
"text": "For more details, please refer to Internet Protocol version 6 (IPv6) Header article."
},
{
"code": null,
"e": 3507,
"s": 3473,
"text": "8. What protocol is used by PING?"
},
{
"code": null,
"e": 3651,
"s": 3507,
"text": "ICMP (Internet Control Message Protocol) is used by PING. For more details, please refer to the Difference between Ping and Traceroute article."
},
{
"code": null,
"e": 3679,
"s": 3651,
"text": "9. What is used of Tracert?"
},
{
"code": null,
"e": 3989,
"s": 3679,
"text": "Traceroute is a widely used command-line utility available in almost all operating systems. It shows you the complete route to a destination address. It also shows the time is taken (or delays) between intermediate routers. For more details, please refer to the Difference between Ping and Traceroute article."
},
{
"code": null,
"e": 4030,
"s": 3989,
"text": "10. Name the ports used by FTP protocol?"
},
{
"code": null,
"e": 4070,
"s": 4030,
"text": "Basically, FTP protocol uses two ports:"
},
{
"code": null,
"e": 4328,
"s": 4070,
"text": "Control connection: For sending control information like user identification, password, commands to change the remote directory, commands to retrieve and store files, etc., FTP makes use of connections. The control connection is initiated on port number 21."
},
{
"code": null,
"e": 4557,
"s": 4328,
"text": "Data connection: For sending the actual file, FTP makes use of a data connection. A data connection is initiated on port number 20. For more details, please refer to File Transfer Protocol (FTP) in the Application Layer article."
},
{
"code": null,
"e": 4582,
"s": 4557,
"text": "11. What is MAC address?"
},
{
"code": null,
"e": 4902,
"s": 4582,
"text": "MAC Addresses are unique 48-bit hardware numbers of computers, which are embedded into a network card (known as Network Interface Card) during the time of manufacturing. The MAC Address is also known as the Physical Address of a network device. In IEEE 802 standard, the Data Link Layer is divided into two sublayers – "
},
{
"code": null,
"e": 4971,
"s": 4902,
"text": "Logical Link Control(LLC) SublayerMedia Access Control(MAC) Sublayer"
},
{
"code": null,
"e": 5006,
"s": 4971,
"text": "Logical Link Control(LLC) Sublayer"
},
{
"code": null,
"e": 5041,
"s": 5006,
"text": "Media Access Control(MAC) Sublayer"
},
{
"code": null,
"e": 5244,
"s": 5041,
"text": "The MAC address is used by the Media Access Control (MAC) sublayer of the Data-Link Layer. MAC Address is unique worldwide since millions of network devices exist and we need to uniquely identify each. "
},
{
"code": null,
"e": 5335,
"s": 5244,
"text": "For more details, please refer to Introduction of MAC Address in Computer Network article."
},
{
"code": null,
"e": 5352,
"s": 5335,
"text": "12. Explain ARP?"
},
{
"code": null,
"e": 5881,
"s": 5352,
"text": "Address Resolution Protocol is a communication protocol used for discovering physical addresses associated with a given network address. Typically, ARP is a network layer to data link layer mapping process, which is used to discover MAC addresses for a given Internet Protocol Address.In order to send the data to the destination, having an IP address is necessary but not sufficient; we also need the physical address of the destination machine. ARP is used to get the physical address (MAC address) of the destination machine."
},
{
"code": null,
"e": 6521,
"s": 5881,
"text": "Before sending the IP packet, the MAC address of the destination must be known. If not so, then the sender broadcasts the ARP-discovery packet requesting the MAC address of the intended destination. Since ARP-discovery is broadcast, every host inside that network will get this message but the packet will be discarded by everyone except that intended receiver host whose IP is associated. Now, this receiver will send a unicast packet with its MAC address (ARP-reply) to the sender of the ARP-discovery packet. After the original sender receives the ARP-reply, it updates ARP-cache and starts sending a unicast message to the destination."
},
{
"code": null,
"e": 6606,
"s": 6521,
"text": "For more details, please refer to the How Address Resolution Protocol works article."
},
{
"code": null,
"e": 6624,
"s": 6606,
"text": "13. What is MTU?"
},
{
"code": null,
"e": 6980,
"s": 6624,
"text": "A maximum transmission unit also called MTU, is a term used in networking and operating systems. It defines the largest size of the packet that can be transmitted as a single entity in a network connection. The size of the MTU dictates the amount of data that can be transmitted in bytes over a network. For more details, please refer What is MTU article."
},
{
"code": null,
"e": 7695,
"s": 6980,
"text": "14. If a class B network on the Internet has a subnet mask of 255.255.248.0, what is the maximum number of hosts per subnet?The binary representation of the subnet mask is 11111111.11111111.11111000. 00000000. There are 21 bits set in a subnet. So 11 (32-21) bits are left for host ids. The total possible value of host ids is 2^11 = 2048. Out of these 2048 values, 2 addresses are reserved. The address with all bits as 1 is reserved as broadcast address and the address with all host id bits as 0 is used as a network address of the subnet.In general, the number of addresses usable for addressing specific hosts in each network is always 2^N – 2 where N is the number of bits for host id. So the answer is 2046."
},
{
"code": null,
"e": 7721,
"s": 7695,
"text": "15. What is IP multicast?"
},
{
"code": null,
"e": 8235,
"s": 7721,
"text": "Multicasting has one/more senders and one/more recipients participate in data transfer traffic. In multicasting, traffic reclines between the boundaries of unicast and broadcast. Its server’s direct single copies of data streams and that are then simulated and routed to hosts that request it. IP multicast requires the support of some other protocols such as Internet Group Management Protocol (IGMP), Multicast routing for its work. And also, in Classful IP, addressing Class D is reserved for multicast groups."
},
{
"code": null,
"e": 8291,
"s": 8235,
"text": "16. Difference between public and private IP addresses?"
},
{
"code": null,
"e": 9821,
"s": 8291,
"text": "Public IP address–A public IP address is an Internet Protocol address, encrypted by various servers/devices. That’s when you connect these devices with your internet connection. This is the same IP address we show on our homepage. So why the second page? Well, not all people speak the IP language. We want to make it as easy as possible for everyone to get the information they need. Some even call this their external IP address. A public Internet Protocol address is an Internet Protocol address accessed over the Internet. Like the postal address used to deliver mail to your home, the public Internet Protocol address is a different international Internet Protocol address assigned to a computer device. The web server, email server, and any server device that has direct access to the Internet are those who will enter the public Internet Protocol address. Internet Address Protocol is unique worldwide and is only supplied with a unique device.Private IP address–Everything that connects to your Internet network has a private IP address. This includes computers, smartphones, and tablets but also any Bluetooth-enabled devices such as speakers, printers, or smart TVs. With the growing internet of things, the number of private IP addresses you have at home is likely to increase. Your router needs a way to identify these things separately, and most things need a way to get to know each other. Therefore, your router generates private IP addresses that are unique identifiers for each device that separates the network."
},
{
"code": null,
"e": 10773,
"s": 9821,
"text": "Public IP address–A public IP address is an Internet Protocol address, encrypted by various servers/devices. That’s when you connect these devices with your internet connection. This is the same IP address we show on our homepage. So why the second page? Well, not all people speak the IP language. We want to make it as easy as possible for everyone to get the information they need. Some even call this their external IP address. A public Internet Protocol address is an Internet Protocol address accessed over the Internet. Like the postal address used to deliver mail to your home, the public Internet Protocol address is a different international Internet Protocol address assigned to a computer device. The web server, email server, and any server device that has direct access to the Internet are those who will enter the public Internet Protocol address. Internet Address Protocol is unique worldwide and is only supplied with a unique device."
},
{
"code": null,
"e": 11352,
"s": 10773,
"text": "Private IP address–Everything that connects to your Internet network has a private IP address. This includes computers, smartphones, and tablets but also any Bluetooth-enabled devices such as speakers, printers, or smart TVs. With the growing internet of things, the number of private IP addresses you have at home is likely to increase. Your router needs a way to identify these things separately, and most things need a way to get to know each other. Therefore, your router generates private IP addresses that are unique identifiers for each device that separates the network."
},
{
"code": null,
"e": 11389,
"s": 11352,
"text": "17. Can you explain what subnetting?"
},
{
"code": null,
"e": 11628,
"s": 11389,
"text": "When a bigger network is divided into smaller networks, in order to maintain security, then that is known as Subnetting. so, maintenance is easier for smaller networks. For more details please read an introduction to a subnetting article."
},
{
"code": null,
"e": 11681,
"s": 11628,
"text": "18. Do you know what is Network Address Translation?"
},
{
"code": null,
"e": 12564,
"s": 11681,
"text": "To access the Internet, one public IP address is needed, but we can use a private IP address on our private network. The idea of NAT is to allow multiple devices to access the Internet through a single public address. To achieve this, the translation of a private IP address to a public IP address is required. Network Address Translation (NAT) is a process in which one or more local IP addresses is translated into one or more Global IP addresses and vice versa in order to provide Internet access to the local hosts. Also, it does the translation of port numbers i.e. masks the port number of the host with another port number in the packet that will be routed to the destination. It then makes the corresponding entries of IP address and port number in the NAT table. NAT generally operates on a router or firewall. For more details, please refer to Network Address Translation."
},
{
"code": null,
"e": 13106,
"s": 12564,
"text": "19. An organization requires a range of IP addresses to assign one to each of its 1500 computers. The organization has approached an Internet Service Provider (ISP) for this task. The ISP uses CIDR and serves the requests from the available IP address space 202.61.0.0/17. The ISP wants to assign address space to the organization which will minimize the number of routing entries in the ISP’s router using route aggregation. To calculate the address spaces are potential candidates from which the ISP can allow any one of the organizations?"
},
{
"code": null,
"e": 13144,
"s": 13106,
"text": "Subnet Mask for the given IP address:"
},
{
"code": null,
"e": 13214,
"s": 13144,
"text": "202.61.0.0/17 \n⇒ 11111111 11111111 10000000 00000000\n⇒ 255.255.128.0 "
},
{
"code": null,
"e": 13272,
"s": 13214,
"text": "Now, since we need 1500 hosts, so, bits for host address,"
},
{
"code": null,
"e": 13344,
"s": 13272,
"text": "= ceiling (log2 (1500)) \n= ceiling (10.55) \n= 11 bits for host address "
},
{
"code": null,
"e": 13393,
"s": 13344,
"text": "So, the last 11 bits will be for host addresses:"
},
{
"code": null,
"e": 13557,
"s": 13393,
"text": "00000000.00000000 → 00000111.11111111 (0.0 → 7.255)\n\n00001000.00000000 → 00010000.00000000 (8.0 - 15.255)\n\n00001111.11111111 → 00010111.11111111 (16.0 - 23.255) "
},
{
"code": null,
"e": 13632,
"s": 13557,
"text": "Sequences are 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 96, 104, 112, 120."
},
{
"code": null,
"e": 13752,
"s": 13632,
"text": "Hence, 64 and 104 are present in the sequence, so 202.61.104.0 / 21 and 202.61.64.0 / 21 are the possible IP addresses."
},
{
"code": null,
"e": 13810,
"s": 13752,
"text": "20. Explain the difference between Static and Dynamic IP?"
},
{
"code": null,
"e": 13896,
"s": 13810,
"text": "For more details, please refer to Difference between Static and Dynamic IP addresses."
},
{
"code": null,
"e": 13941,
"s": 13896,
"text": "21. How will my computer get its IP Address?"
},
{
"code": null,
"e": 13961,
"s": 13941,
"text": "To get IP address :"
},
{
"code": null,
"e": 14069,
"s": 13961,
"text": "Click on start ->Programs->Accessories->Command prompt.Type ipconfig on command prompt and press enter key."
},
{
"code": null,
"e": 14125,
"s": 14069,
"text": "Click on start ->Programs->Accessories->Command prompt."
},
{
"code": null,
"e": 14178,
"s": 14125,
"text": "Type ipconfig on command prompt and press enter key."
},
{
"code": null,
"e": 14274,
"s": 14178,
"text": "By using these steps, you can get your PC IP address, Subnet Mask, and default gateway details."
},
{
"code": null,
"e": 14312,
"s": 14274,
"text": "22. What are the features of Gateway?"
},
{
"code": null,
"e": 14376,
"s": 14312,
"text": "Gateways provide a wide variety of features. Some of which are:"
},
{
"code": null,
"e": 14548,
"s": 14376,
"text": "Gateways work as a network bridge for data transmission as it makes the transmission of data possible to transmit with more ease and does not demand high storage capacity."
},
{
"code": null,
"e": 14676,
"s": 14548,
"text": "Gateways create a structural temporary storeroom for the data transmitted by the server and data requests made by the user end."
},
{
"code": null,
"e": 14984,
"s": 14676,
"text": "Gateways made the transmission more feasible as it queued up all the data and divide it into small packets of data rather than sending it bulk. Data transmitted through Gateway is divided into various useful and small packets each having its individual significance and a role to play while processing data."
},
{
"code": null,
"e": 15130,
"s": 14984,
"text": "Gateways made the data more secure if the modifications to the gateway could be done which then could create more reliability over smart devices."
},
{
"code": null,
"e": 15379,
"s": 15130,
"text": "Gateways optimize the data for search engines, applications, and servers by implanting better readability to the content so that a machine could understand and optimize data with ease. For more details, please refer to the Introduction of Gateways."
},
{
"code": null,
"e": 15422,
"s": 15379,
"text": "23. Is Ipv6 Backward Compatible With Ipv4?"
},
{
"code": null,
"e": 15554,
"s": 15422,
"text": "No, IPv6 is not backward compatible with IPv4 protocol. For more details, please refer to the Internet protocol version 6 article."
},
{
"code": null,
"e": 15627,
"s": 15554,
"text": "24. Is It Possible To Have An Ipv4 And An Ipv6 Addresses Simultaneously?"
},
{
"code": null,
"e": 15816,
"s": 15627,
"text": "Yes, it is possible to have an IPv4 and IPv6 addresses simultaneously. For more details, please refer to the Internet protocol version 6 and the difference between IPv4 and IPv6 articles."
},
{
"code": null,
"e": 15833,
"s": 15816,
"text": "25. What is TTL?"
},
{
"code": null,
"e": 16293,
"s": 15833,
"text": "The lifespan or lifetime of data that is being sent. Once after that specified time is over or elapsed, the data will be discarded Or it can also be stated as the number of hops that packet is set to exist in the network, after which that packet is discarded. The purpose of the TTL field is to avoid a situation in which an undeliverable datagram keeps circulating in the network. For more details, please refer to the difference between RTT and TTL article."
},
{
"code": null,
"e": 16385,
"s": 16293,
"text": "26. If the TTL field has the value of 10. How many routers (max) can process this datagram?"
},
{
"code": null,
"e": 16756,
"s": 16385,
"text": "TTL stands for Time to Live. This field specifies the life of the IP packet based on the number of hops it makes ( number of routers it goes through). TTL field is decremented by one each time the datagram is processed by a router. When the value is 0, the packet is automatically destroyed. For more details, please refer to the difference between RTT and TTL articles."
},
{
"code": null,
"e": 16855,
"s": 16756,
"text": "27. If the value in the protocol field is 17, the transport layer protocol used is which protocol?"
},
{
"code": null,
"e": 17008,
"s": 16855,
"text": "If the value in the protocol field is 17, the transport layer protocol uses UDP (User Datagram Protocol). For more details, please refer to UDP article."
},
{
"code": null,
"e": 17108,
"s": 17008,
"text": "28. What happens in classless addressing, if there are no classes but addresses are still granted?"
},
{
"code": null,
"e": 17365,
"s": 17108,
"text": "In classless addressing, there are no classes but addresses are still granted in blocks. The total number of addresses in a block of classless IP addresses = 2(32 – CIDR_value). For more details, please refer to the introduction of Classful IP addressing."
},
{
"code": null,
"e": 17534,
"s": 17365,
"text": "29. Suppose two IPv6 nodes want to interoperate using IPv6 datagrams, but they are connected to each other by intervening IPv4 routers. Then what is the best solution?"
},
{
"code": null,
"e": 17767,
"s": 17534,
"text": "If two IPv6 nodes want to interoperate using IPv6 datagrams, they are connected to each other by intervening IPv4 routers. Then tunneling is the best solution. For more details, please refer to Internet protocol version 6 article."
},
{
"code": null,
"e": 17785,
"s": 17767,
"text": "30. What is IANA?"
},
{
"code": null,
"e": 18398,
"s": 17785,
"text": "IANA, the Internet Assigned Numbers Authority, is an administrative function of the Internet that keeps track of IP addresses, domain names, and protocol parameter identifiers that are used by Internet standards. Some of these identifiers are parameters, such as those used by Internet protocols (like TCP, ICMP or UDP) to specify functions and behaviour; some of them represent Internet addresses and others represent domain names. Regardless of the type of identifier, the IANA function (IANA for short below) ensures that values are managed for uniqueness and made available in publicly accessible registries."
},
{
"code": null,
"e": 18416,
"s": 18398,
"text": "31. What is DHCP?"
},
{
"code": null,
"e": 18817,
"s": 18416,
"text": "DHCP is an abbreviation for Dynamic Host Configuration Protocol. It is an application layer protocol used by hosts for obtaining network setup information. The DHCP is controlled by a DHCP server that dynamically distributes network configuration parameters such as IP addresses, subnet mask, and gateway address. For more details, please refer to Dynamic Host Configuration Protocol (DHCP) article."
},
{
"code": null,
"e": 18866,
"s": 18817,
"text": "32. How can you manage a network using a router?"
},
{
"code": null,
"e": 19281,
"s": 18866,
"text": "Routers have built-in console that lets you configure different settings, like security and data logging.We can assign restrictions to computers, such as what resources they are allowed to access, or what particular time of the day they can browse the internet.We can even put restrictions on what websites are not viewable across the entire network. For more details, please refer to the introduction of a Router."
},
{
"code": null,
"e": 19303,
"s": 19281,
"text": "33. What is ipconfig?"
},
{
"code": null,
"e": 19891,
"s": 19303,
"text": "IPCONFIG stands for Internet Protocol Configuration. This is a command-line application that displays all the current TCP/IP (Transmission Control Protocol/Internet Protocol) network configuration, refreshes the DHCP (Dynamic Host Configuration Protocol) and DNS (Domain Name Server). It also displays an IP address, subnet mask, and a default gateway for all adapters. It is available for Microsoft Windows, ReactOS, and Apple macOS. ReactOS version was developed by Ged Murphy and licensed under the General Public License. For more details, please refer to ipconfig full form article."
},
{
"code": null,
"e": 19996,
"s": 19891,
"text": "34. When you move the NIC cards from one PC to another PC, does the MAC address get transferred as well?"
},
{
"code": null,
"e": 20284,
"s": 19996,
"text": "Yes, if we move the NIC cards from one PC to another PC, then the MAC address also gets transferred, because the MAC address is hard-wired into the NIC circuit, not the personal computer. This also means that a PC can have a different MAC address when another one replaces the NIC card. "
},
{
"code": null,
"e": 20316,
"s": 20284,
"text": "35. Explain clustering support?"
},
{
"code": null,
"e": 20579,
"s": 20316,
"text": "Clustering support refers to the ability of a network operating system to connect multiple servers in a fault-tolerant group. The main purpose of this is the in the event that one server fails, all processing will continue on with the next server in the cluster."
},
{
"code": null,
"e": 20600,
"s": 20579,
"text": "36. What is Brouter?"
},
{
"code": null,
"e": 21013,
"s": 20600,
"text": " Brouter – It is also known as the bridging router is a device that combines features of both bridge and router. It can work either at the data link layer or a network layer. Working as a router, it is capable of routing packets across networks, and working as the bridge, it is capable of filtering local area network traffic. For more details, please refer to the difference between Router and Brouter article."
},
{
"code": null,
"e": 21046,
"s": 21013,
"text": "37. Explain the features of VPN?"
},
{
"code": null,
"e": 21566,
"s": 21046,
"text": "VPN also ensures security by providing an encrypted tunnel between client and vpn server.VPN is used to bypass many blocked sites.VPN facilitates anonymous browsing by hiding your ip address.Also, the most appropriate Search engine optimization(SEO) is done by analyzing the data from VPN providers which provide country-wise states for browsing a particular product. This method of SEO is used widely by many internet marketing managers to form new strategies.For more details, please refer to Virtual Private Network."
},
{
"code": null,
"e": 21656,
"s": 21566,
"text": "VPN also ensures security by providing an encrypted tunnel between client and vpn server."
},
{
"code": null,
"e": 21698,
"s": 21656,
"text": "VPN is used to bypass many blocked sites."
},
{
"code": null,
"e": 21760,
"s": 21698,
"text": "VPN facilitates anonymous browsing by hiding your ip address."
},
{
"code": null,
"e": 22089,
"s": 21760,
"text": "Also, the most appropriate Search engine optimization(SEO) is done by analyzing the data from VPN providers which provide country-wise states for browsing a particular product. This method of SEO is used widely by many internet marketing managers to form new strategies.For more details, please refer to Virtual Private Network."
},
{
"code": null,
"e": 22164,
"s": 22089,
"text": "38. What are the important differences between MAC address and IP address?"
},
{
"code": null,
"e": 22187,
"s": 22164,
"text": "39. What is 127.0.0.1?"
},
{
"code": null,
"e": 22530,
"s": 22187,
"text": "In IPv4, IP addresses that start with decimal 127 or that has 01111111 in the first octet are loopback addresses(127.X.X.X). Typically 127.0.0.1 is used as the local loopback address.This leads to the wastage of many potential IP addresses. But in IPv6 ::1 is used as local loopback address and therefore there isn’t any wastage of addresses."
},
{
"code": null,
"e": 22549,
"s": 22530,
"text": "40. What is a DNS?"
},
{
"code": null,
"e": 22827,
"s": 22549,
"text": "DNS is a host name to IP address translation service. DNS is a distributed database implemented in a hierarchy of name servers. It is an application layer protocol for message exchange between clients and servers. For more details, please refer to DNS in the application layer."
},
{
"code": null,
"e": 22866,
"s": 22827,
"text": "41. What is the use of a proxy server?"
},
{
"code": null,
"e": 23499,
"s": 22866,
"text": "Proxy server refers to a server that acts as an intermediary between the request made by clients, and a particular server for some services or requests for some resources. There are different types of proxy servers available that are put into use according to the purpose of a request made by the clients to the servers. The basic purpose of Proxy servers is to protect the direct connection of Internet clients and internet resources. The proxy server also prevents the identification of the client’s IP address when the client makes any request is made to any other servers. For more details, please refer to Proxy server article."
},
{
"code": null,
"e": 23566,
"s": 23499,
"text": "42. What is the difference between ipconfig and ifconfig commands?"
},
{
"code": null,
"e": 24087,
"s": 23566,
"text": "IPCONFIG stands for Internet Protocol Configuration. This is a command-line application that displays all the current TCP/IP (Transmission Control Protocol/Internet Protocol) network configuration, refreshes the DHCP (Dynamic Host Configuration Protocol) and DNS (Domain Name Server). It also displays IP address, subnet mask, and default gateway for all adapters. It is available for Microsoft Windows, ReactOS, and Apple macOS. ReactOS version was developed by Ged Murphy and licensed under the General Public License."
},
{
"code": null,
"e": 24502,
"s": 24087,
"text": "ifconfig(interface configuration) command is used to configure the kernel-resident network interfaces. It is used at boot time to set up the interfaces as necessary. After that, it is usually used when needed during debugging or when you need system tuning. Also, this command is used to assign the IP address and netmask to an interface or to enable or disable a given interface. For more details, please refer to"
},
{
"code": null,
"e": 24553,
"s": 24502,
"text": "43. What is the importance of APIPA in networking?"
},
{
"code": null,
"e": 25137,
"s": 24553,
"text": "Automatic Private IP Addressing is important in networking because communication can be established properly if you don’t get a response from DHCP Server. APIPA regulates the service, by which the response and status of the main DHCP server at a specific period of time. Apart from that, it can be used as a backup to DHCP because when DHCP stops working, APIPA has the ability to assign IP to the networking hosts.It stops unwanted broadcasting. It uses ARP(Address Resolution Protocol) to confirm the address isn’t currently in use. For more details, please refer to What is APIPA."
},
{
"code": null,
"e": 25196,
"s": 25137,
"text": "44. What is the difference between Firewall and Antivirus?"
},
{
"code": null,
"e": 25214,
"s": 25196,
"text": "45. What is SLIP?"
},
{
"code": null,
"e": 25972,
"s": 25214,
"text": "SLIP stands for Serial Line Internet Protocol. It is a TCP/IP implementation which was described under RFC 1055 (Request for Comments). SLIP establishes point-to-point serial connections which can be used in dial-up connections, serial ports and routers. It frames the encapsulated IP packets across a serial line for establishing connection while using line speed between 12000 bps and 19.2 Kbps. SLIP was introduced in 1984 when Rick Adams used it to connect 4.2 Berkeley Unix and Sun Microsystems workstations. It soon caught up with the rest of the world as a credible TCP/IP implementation. It has now become obsolete after being replaced by PPP (Point to Point Protocol) which solves many deficiencies present in it. For more details, please refer to"
},
{
"code": null,
"e": 26004,
"s": 25972,
"text": "46. What is Kerberos protocol?"
},
{
"code": null,
"e": 26356,
"s": 26004,
"text": "Kerberos provides a centralized authentication server whose function is to authenticate users to servers and servers to users. In Kerberos Authentication server and database is used for client authentication. Kerberos runs as a third-party trusted server known as the Key Distribution Center (KDC). Each user and service on the network is a principal."
},
{
"code": null,
"e": 26393,
"s": 26356,
"text": "The main components of Kerberos are:"
},
{
"code": null,
"e": 26522,
"s": 26393,
"text": "Authentication Server (AS):The Authentication Server performs the initial authentication and ticket for Ticket Granting Service."
},
{
"code": null,
"e": 26610,
"s": 26522,
"text": "Database:The Authentication Server verifies the access rights of users in the database."
},
{
"code": null,
"e": 26700,
"s": 26610,
"text": "Ticket Granting Server (TGS):The Ticket Granting Server issues the ticket for the Server."
},
{
"code": null,
"e": 26752,
"s": 26700,
"text": "For more details, please refer to Kerberos article."
},
{
"code": null,
"e": 26771,
"s": 26752,
"text": "47. What is HSRP?"
},
{
"code": null,
"e": 26952,
"s": 26771,
"text": "Hot Standby Router Protocol (HSRP) is a CISCO proprietary protocol, which provides redundancy for a local subnet. In HSRP, two or more routers give an illusion of a virtual router."
},
{
"code": null,
"e": 27386,
"s": 26952,
"text": "HSRP allows you to configure two or more routers as standby routers and only a single router as an active router at a time. All the routers in a single HSRP group share a single MAC address and IP address, which acts as a default gateway to the local network. The Active router is responsible for forwarding the traffic. If it fails, the Standby router takes up all the responsibilities of the active router and forwards the traffic."
},
{
"code": null,
"e": 27435,
"s": 27386,
"text": "For more details, please refer to HSRP protocol."
},
{
"code": null,
"e": 27491,
"s": 27435,
"text": "48. Why is the MAC address called the Physical address?"
},
{
"code": null,
"e": 27890,
"s": 27491,
"text": "The MAC address is a physical address (also called a hardware address) because it physically identifies an item of hardware. MAC addresses use three types of number systems and all use the same format, only the size of the identifier differs. The addresses can be “Universally Managed” or “Locally Managed”. For more details, please refer to Introduction of MAC Address in Computer Network article."
},
{
"code": null,
"e": 27917,
"s": 27890,
"text": "49. Process of DHCP(DORA)?"
},
{
"code": null,
"e": 28236,
"s": 27917,
"text": "In DHCP, the client and the server exchange mainly 4 DHCP messages in order to make a connection. This process is known as DORA process (discovery, offer, request, and acknowledgment), but there are 8 DHCP messages in the process. For more details, please refer to Dynamic Host Configuration Protocol (DHCP) article."
},
{
"code": null,
"e": 28258,
"s": 28236,
"text": "50. What is ‘APIPA’?"
},
{
"code": null,
"e": 28741,
"s": 28258,
"text": "APIPA stands for Automatic Private IP Addressing (APIPA). It is a feature or characteristic in operating systems (eg. Windows) which enables computers to self-configure an IP address and subnet mask automatically when their DHCP(Dynamic Host Configuration Protocol) server isn’t reachable. The IP address range for APIPA is (169.254.0.1 to 169.254.255.254) having 65, 534 usable IP addresses, with the subnet mask of 255.255.0.0. For more details please read What is APIPA article."
},
{
"code": null,
"e": 28755,
"s": 28743,
"text": "anikakapoor"
},
{
"code": null,
"e": 28775,
"s": 28755,
"text": "interview-questions"
},
{
"code": null,
"e": 28793,
"s": 28775,
"text": "Computer Networks"
},
{
"code": null,
"e": 28811,
"s": 28793,
"text": "Computer Networks"
}
] |
Difference between var, let and const keywords in JavaScript | 15 Dec, 2021
In JavaScript, users can declare a variable using 3 keywords that are var, let, and const. In this article, we will see the differences between the var, let, and const keywords. We will discuss the scope and other required concepts about each keyword.
var keyword in JavaScript: The var is the oldest keyword to declare a variable in JavaScript.
Scope: Global scoped or function scoped. The scope of the var keyword is the global or function scope. It means variables defined outside the function can be accessed globally, and variables defined inside a particular function can be accessed within the function.
Example 1: Variable ‘a’ is declared globally. So, the scope of the variable ‘a’ is global, and it can be accessible everywhere in the program. The output shown is in the console.
Javascript
<script> var a = 10 function f(){ console.log(a) } f(); console.log(a);</script>
Output:
10
10
Example 2: The variable ‘a’ is declared inside the function. If the user tries to access it outside the function, it will display the error. Users can declare the 2 variables with the same name using the var keyword. Also, the user can reassign the value into the var variable. The output shown in the console.
Javascript
<script> function f() { // It can be accessible any // where within this function var a = 10; console.log(a) } f(); // A cannot be accessible // outside of function console.log(a);</script>
Output:
10
ReferenceError: a is not defined
Example 3: User can re-declare variable using var and user can update var variable. The output is shown in the console.
Javascript
<script> var a = 10 // User can re-declare // variable using var var a = 8 // User can update var variable a = 7</script>
Output:
7
Example 4: If users use the var variable before the declaration, it initializes with the undefined value. The output is shown in the console.
Javascript
<script> console.log(a); var a = 10;<script>
Output:
undefined
let keyword in JavaScript: The let keyword is an improved version of the var keyword.
Scope: block scoped: The scope of a let variable is only block scoped. It can’t be accessible outside the particular block ({block}). Let’s see the below example.
Example 1: The output is shown in the console.
Javascript
<script> let a = 10; function f() { let b = 9 console.log(b); console.log(a); } f();</script>
Output:
9
10
Example 2: The code returns an error because we are accessing the let variable outside the function block. The output is shown in the console.
Javascript
<script> let a = 10; function f() { if (true) { let b = 9 // It prints 9 console.log(b); } // It gives error as it // defined in if block console.log(b); } f() // It prints 10 console.log(a)</script>
Output:
9
ReferenceError: b is not defined
Example 3: Users cannot re-declare the variable defined with the let keyword but can update it.
Javascript
<script> let a = 10 // It is not allowed let a = 10 // It is allowed a = 10</script>
Output:
Uncaught SyntaxError: Identifier 'a' has already been declared
Example 4: Users can declare the variable with the same name in different blocks using the let keyword.
Javascript
<script> let a = 10 if (true) { let a=9 console.log(a) // It prints 9 } console.log(a) // It prints 10</script>
Output:
9
10
Example 5: If users use the let variable before the declaration, it does not initialize with undefined just like a var variable and return an error.
Javascript
<script> console.log(a); let a = 10;</script>
Output:
Uncaught ReferenceError: Cannot access 'a' before initialization
const keyword in JavaScript: The const keyword has all the properties that are the same as the let keyword, except the user cannot update it.
Scope: block scoped: When users declare a const variable, they need to initialize it, otherwise, it returns an error. The user cannot update the const variable once it is declared.
Example 1: We are changing the value of the const variable so that it returns an error. The output is shown in the console.
Javascript
<script> const a = 10; function f() { a = 9 console.log(a) } f();</script>
Output:
a=9
TypeError:Assignment to constant variable.
Example 2: Users cannot change the properties of the const object, but they can change the value of properties of the const object.
Javascript
<script> const a = { prop1: 10, prop2: 9 } // It is allowed a.prop1 = 3 // It is not allowed a = { b: 10, prop2: 9 }</script>
Output:
Uncaught SyntaxError:Unexpected identifier
Differences between var, let, and const
Note: Sometimes, users face the problem while working with the var variable as they change the value of it in the particular block. So, users should use the let and const keyword to declare a variable in JavaScript.
gabaa406
javascript-basics
JavaScript-Questions
Picked
Difference Between
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference Between Method Overloading and Method Overriding in Java
Difference between Process and Thread
Difference between Clustered and Non-clustered index
Differences between IPv4 and IPv6
Differences between Procedural and Object Oriented Programming
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Dec, 2021"
},
{
"code": null,
"e": 304,
"s": 52,
"text": "In JavaScript, users can declare a variable using 3 keywords that are var, let, and const. In this article, we will see the differences between the var, let, and const keywords. We will discuss the scope and other required concepts about each keyword."
},
{
"code": null,
"e": 399,
"s": 304,
"text": "var keyword in JavaScript: The var is the oldest keyword to declare a variable in JavaScript. "
},
{
"code": null,
"e": 665,
"s": 399,
"text": "Scope: Global scoped or function scoped. The scope of the var keyword is the global or function scope. It means variables defined outside the function can be accessed globally, and variables defined inside a particular function can be accessed within the function. "
},
{
"code": null,
"e": 844,
"s": 665,
"text": "Example 1: Variable ‘a’ is declared globally. So, the scope of the variable ‘a’ is global, and it can be accessible everywhere in the program. The output shown is in the console."
},
{
"code": null,
"e": 855,
"s": 844,
"text": "Javascript"
},
{
"code": "<script> var a = 10 function f(){ console.log(a) } f(); console.log(a);</script>",
"e": 970,
"s": 855,
"text": null
},
{
"code": null,
"e": 979,
"s": 970,
"text": "Output: "
},
{
"code": null,
"e": 985,
"s": 979,
"text": "10\n10"
},
{
"code": null,
"e": 1296,
"s": 985,
"text": "Example 2: The variable ‘a’ is declared inside the function. If the user tries to access it outside the function, it will display the error. Users can declare the 2 variables with the same name using the var keyword. Also, the user can reassign the value into the var variable. The output shown in the console."
},
{
"code": null,
"e": 1307,
"s": 1296,
"text": "Javascript"
},
{
"code": "<script> function f() { // It can be accessible any // where within this function var a = 10; console.log(a) } f(); // A cannot be accessible // outside of function console.log(a);</script>",
"e": 1545,
"s": 1307,
"text": null
},
{
"code": null,
"e": 1553,
"s": 1545,
"text": "Output:"
},
{
"code": null,
"e": 1589,
"s": 1553,
"text": "10\nReferenceError: a is not defined"
},
{
"code": null,
"e": 1709,
"s": 1589,
"text": "Example 3: User can re-declare variable using var and user can update var variable. The output is shown in the console."
},
{
"code": null,
"e": 1720,
"s": 1709,
"text": "Javascript"
},
{
"code": "<script> var a = 10 // User can re-declare // variable using var var a = 8 // User can update var variable a = 7</script>",
"e": 1865,
"s": 1720,
"text": null
},
{
"code": null,
"e": 1873,
"s": 1865,
"text": "Output:"
},
{
"code": null,
"e": 1875,
"s": 1873,
"text": "7"
},
{
"code": null,
"e": 2017,
"s": 1875,
"text": "Example 4: If users use the var variable before the declaration, it initializes with the undefined value. The output is shown in the console."
},
{
"code": null,
"e": 2028,
"s": 2017,
"text": "Javascript"
},
{
"code": "<script> console.log(a); var a = 10;<script>",
"e": 2079,
"s": 2028,
"text": null
},
{
"code": null,
"e": 2087,
"s": 2079,
"text": "Output:"
},
{
"code": null,
"e": 2097,
"s": 2087,
"text": "undefined"
},
{
"code": null,
"e": 2184,
"s": 2097,
"text": "let keyword in JavaScript: The let keyword is an improved version of the var keyword. "
},
{
"code": null,
"e": 2347,
"s": 2184,
"text": "Scope: block scoped: The scope of a let variable is only block scoped. It can’t be accessible outside the particular block ({block}). Let’s see the below example."
},
{
"code": null,
"e": 2394,
"s": 2347,
"text": "Example 1: The output is shown in the console."
},
{
"code": null,
"e": 2405,
"s": 2394,
"text": "Javascript"
},
{
"code": "<script> let a = 10; function f() { let b = 9 console.log(b); console.log(a); } f();</script>",
"e": 2532,
"s": 2405,
"text": null
},
{
"code": null,
"e": 2540,
"s": 2532,
"text": "Output:"
},
{
"code": null,
"e": 2545,
"s": 2540,
"text": "9\n10"
},
{
"code": null,
"e": 2688,
"s": 2545,
"text": "Example 2: The code returns an error because we are accessing the let variable outside the function block. The output is shown in the console."
},
{
"code": null,
"e": 2699,
"s": 2688,
"text": "Javascript"
},
{
"code": "<script> let a = 10; function f() { if (true) { let b = 9 // It prints 9 console.log(b); } // It gives error as it // defined in if block console.log(b); } f() // It prints 10 console.log(a)</script>",
"e": 2988,
"s": 2699,
"text": null
},
{
"code": null,
"e": 2996,
"s": 2988,
"text": "Output:"
},
{
"code": null,
"e": 3031,
"s": 2996,
"text": "9\nReferenceError: b is not defined"
},
{
"code": null,
"e": 3127,
"s": 3031,
"text": "Example 3: Users cannot re-declare the variable defined with the let keyword but can update it."
},
{
"code": null,
"e": 3138,
"s": 3127,
"text": "Javascript"
},
{
"code": "<script> let a = 10 // It is not allowed let a = 10 // It is allowed a = 10</script>",
"e": 3241,
"s": 3138,
"text": null
},
{
"code": null,
"e": 3249,
"s": 3241,
"text": "Output:"
},
{
"code": null,
"e": 3312,
"s": 3249,
"text": "Uncaught SyntaxError: Identifier 'a' has already been declared"
},
{
"code": null,
"e": 3416,
"s": 3312,
"text": "Example 4: Users can declare the variable with the same name in different blocks using the let keyword."
},
{
"code": null,
"e": 3427,
"s": 3416,
"text": "Javascript"
},
{
"code": "<script> let a = 10 if (true) { let a=9 console.log(a) // It prints 9 } console.log(a) // It prints 10</script>",
"e": 3549,
"s": 3427,
"text": null
},
{
"code": null,
"e": 3557,
"s": 3549,
"text": "Output:"
},
{
"code": null,
"e": 3563,
"s": 3557,
"text": "9 \n10"
},
{
"code": null,
"e": 3712,
"s": 3563,
"text": "Example 5: If users use the let variable before the declaration, it does not initialize with undefined just like a var variable and return an error."
},
{
"code": null,
"e": 3723,
"s": 3712,
"text": "Javascript"
},
{
"code": "<script> console.log(a); let a = 10;</script>",
"e": 3775,
"s": 3723,
"text": null
},
{
"code": null,
"e": 3783,
"s": 3775,
"text": "Output:"
},
{
"code": null,
"e": 3848,
"s": 3783,
"text": "Uncaught ReferenceError: Cannot access 'a' before initialization"
},
{
"code": null,
"e": 3990,
"s": 3848,
"text": "const keyword in JavaScript: The const keyword has all the properties that are the same as the let keyword, except the user cannot update it."
},
{
"code": null,
"e": 4172,
"s": 3990,
"text": "Scope: block scoped: When users declare a const variable, they need to initialize it, otherwise, it returns an error. The user cannot update the const variable once it is declared. "
},
{
"code": null,
"e": 4296,
"s": 4172,
"text": "Example 1: We are changing the value of the const variable so that it returns an error. The output is shown in the console."
},
{
"code": null,
"e": 4307,
"s": 4296,
"text": "Javascript"
},
{
"code": "<script> const a = 10; function f() { a = 9 console.log(a) } f();</script>",
"e": 4408,
"s": 4307,
"text": null
},
{
"code": null,
"e": 4416,
"s": 4408,
"text": "Output:"
},
{
"code": null,
"e": 4463,
"s": 4416,
"text": "a=9\nTypeError:Assignment to constant variable."
},
{
"code": null,
"e": 4595,
"s": 4463,
"text": "Example 2: Users cannot change the properties of the const object, but they can change the value of properties of the const object."
},
{
"code": null,
"e": 4606,
"s": 4595,
"text": "Javascript"
},
{
"code": "<script> const a = { prop1: 10, prop2: 9 } // It is allowed a.prop1 = 3 // It is not allowed a = { b: 10, prop2: 9 }</script>",
"e": 4787,
"s": 4606,
"text": null
},
{
"code": null,
"e": 4795,
"s": 4787,
"text": "Output:"
},
{
"code": null,
"e": 4838,
"s": 4795,
"text": "Uncaught SyntaxError:Unexpected identifier"
},
{
"code": null,
"e": 4878,
"s": 4838,
"text": "Differences between var, let, and const"
},
{
"code": null,
"e": 5095,
"s": 4878,
"text": "Note: Sometimes, users face the problem while working with the var variable as they change the value of it in the particular block. So, users should use the let and const keyword to declare a variable in JavaScript. "
},
{
"code": null,
"e": 5104,
"s": 5095,
"text": "gabaa406"
},
{
"code": null,
"e": 5122,
"s": 5104,
"text": "javascript-basics"
},
{
"code": null,
"e": 5143,
"s": 5122,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 5150,
"s": 5143,
"text": "Picked"
},
{
"code": null,
"e": 5169,
"s": 5150,
"text": "Difference Between"
},
{
"code": null,
"e": 5180,
"s": 5169,
"text": "JavaScript"
},
{
"code": null,
"e": 5197,
"s": 5180,
"text": "Web Technologies"
},
{
"code": null,
"e": 5295,
"s": 5197,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5363,
"s": 5295,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 5401,
"s": 5363,
"text": "Difference between Process and Thread"
},
{
"code": null,
"e": 5454,
"s": 5401,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 5488,
"s": 5454,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 5551,
"s": 5488,
"text": "Differences between Procedural and Object Oriented Programming"
},
{
"code": null,
"e": 5623,
"s": 5551,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 5663,
"s": 5623,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 5716,
"s": 5663,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 5758,
"s": 5716,
"text": "Roadmap to Learn JavaScript For Beginners"
}
] |
p5.js | height variable | 16 Apr, 2019
The height variable in p5.js is a system variable which stores the height of the drawing canvas. It sets the second parameter of createCanvas() function.
Syntax:
height
Below programs illustrate the height variable in p5.js:
Example 1: This example uses height variable to display the height of canvas.
function setup() { // Create Canvas of size 380*80 createCanvas(380, 80);} function draw() { // Set the background color background(220); // Set the text size textSize(16); // Set the text alignment textAlign(CENTER); // Set the text color fill(color('Green')); // Display result text("Height of Canvas is : " + height, 180, 50);}
Output:
Example 2: This example uses height variable to display the height of window.
function setup() { // set height to window height height = windowHeight; //create Canvas of size 380*80 createCanvas(380, height);} function draw() { background(220); textSize(16); textAlign(CENTER); fill(color('Green')); text("Height of Canvas is : "+height, 180, height/2); //use of height variable}
Output:
Reference: https://p5js.org/reference/#/p5/height
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Apr, 2019"
},
{
"code": null,
"e": 182,
"s": 28,
"text": "The height variable in p5.js is a system variable which stores the height of the drawing canvas. It sets the second parameter of createCanvas() function."
},
{
"code": null,
"e": 190,
"s": 182,
"text": "Syntax:"
},
{
"code": null,
"e": 197,
"s": 190,
"text": "height"
},
{
"code": null,
"e": 253,
"s": 197,
"text": "Below programs illustrate the height variable in p5.js:"
},
{
"code": null,
"e": 331,
"s": 253,
"text": "Example 1: This example uses height variable to display the height of canvas."
},
{
"code": "function setup() { // Create Canvas of size 380*80 createCanvas(380, 80);} function draw() { // Set the background color background(220); // Set the text size textSize(16); // Set the text alignment textAlign(CENTER); // Set the text color fill(color('Green')); // Display result text(\"Height of Canvas is : \" + height, 180, 50);} ",
"e": 746,
"s": 331,
"text": null
},
{
"code": null,
"e": 754,
"s": 746,
"text": "Output:"
},
{
"code": null,
"e": 832,
"s": 754,
"text": "Example 2: This example uses height variable to display the height of window."
},
{
"code": "function setup() { // set height to window height height = windowHeight; //create Canvas of size 380*80 createCanvas(380, height);} function draw() { background(220); textSize(16); textAlign(CENTER); fill(color('Green')); text(\"Height of Canvas is : \"+height, 180, height/2); //use of height variable}",
"e": 1144,
"s": 832,
"text": null
},
{
"code": null,
"e": 1152,
"s": 1144,
"text": "Output:"
},
{
"code": null,
"e": 1202,
"s": 1152,
"text": "Reference: https://p5js.org/reference/#/p5/height"
},
{
"code": null,
"e": 1219,
"s": 1202,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 1230,
"s": 1219,
"text": "JavaScript"
},
{
"code": null,
"e": 1247,
"s": 1230,
"text": "Web Technologies"
},
{
"code": null,
"e": 1345,
"s": 1247,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1406,
"s": 1345,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1478,
"s": 1406,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1518,
"s": 1478,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1571,
"s": 1518,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 1612,
"s": 1571,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1645,
"s": 1612,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1707,
"s": 1645,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1768,
"s": 1707,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1818,
"s": 1768,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Tilt of Binary Tree | 30 Jun, 2021
Given a binary tree, return the tilt of the whole tree. The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null nodes are assigned tilt to be zero. Therefore, tilt of the whole tree is defined as the sum of all nodes’ tilt.Examples:
Input :
1
/ \
2 3
Output : 1
Explanation:
Tilt of node 2 : 0
Tilt of node 3 : 0
Tilt of node 1 : |2-3| = 1
Tilt of binary tree : 0 + 0 + 1 = 1
Input :
4
/ \
2 9
/ \ \
3 5 7
Output : 15
Explanation:
Tilt of node 3 : 0
Tilt of node 5 : 0
Tilt of node 7 : 0
Tilt of node 2 : |3-5| = 2
Tilt of node 9 : |0-7| = 7
Tilt of node 4 : |(3+5+2)-(9+7)| = 6
Tilt of binary tree : 0 + 0 + 0 + 2 + 7 + 6 = 15
The idea is to recursively traverse tree. While traversing, we keep track of two things, sum of subtree rooted under current node, tilt of current node. Sum is needed to compute tilt of parent.
C++
Java
Python3
C#
Javascript
// CPP Program to find Tilt of Binary Tree#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer toleft child and a pointer to right child */struct Node { int val; struct Node *left, *right;}; /* Recursive function to calculate Tilt of whole tree */int traverse(Node* root, int* tilt){ if (!root) return 0; // Compute tilts of left and right subtrees // and find sums of left and right subtrees int left = traverse(root->left, tilt); int right = traverse(root->right, tilt); // Add current tilt to overall *tilt += abs(left - right); // Returns sum of nodes under current tree return left + right + root->val;} /* Driver function to print Tilt of whole tree */int Tilt(Node* root){ int tilt = 0; traverse(root, &tilt); return tilt;} /* Helper function that allocates anew node with the given data andNULL left and right pointers. */Node* newNode(int data){ Node* temp = new Node; temp->val = data; temp->left = temp->right = NULL; return temp;} // Driver codeint main(){ /* Let us construct a Binary Tree 4 / \ 2 9 / \ \ 3 5 7 */ Node* root = NULL; root = newNode(4); root->left = newNode(2); root->right = newNode(9); root->left->left = newNode(3); root->left->right = newNode(8); root->right->right = newNode(7); cout << "The Tilt of whole tree is " << Tilt(root); return 0;}
// Java Program to find Tilt of Binary Treeimport java.util.*;class GfG { /* A binary tree node has data, pointer toleft child and a pointer to right child */static class Node { int val; Node left, right;} /* Recursive function to calculate Tilt ofwhole tree */static class T{ int tilt = 0;}static int traverse(Node root, T t ){ if (root == null) return 0; // Compute tilts of left and right subtrees // and find sums of left and right subtrees int left = traverse(root.left, t); int right = traverse(root.right, t); // Add current tilt to overall t.tilt += Math.abs(left - right); // Returns sum of nodes under current tree return left + right + root.val;} /* Driver function to print Tilt of whole tree */static int Tilt(Node root){ T t = new T(); traverse(root, t); return t.tilt;} /* Helper function that allocates anew node with the given data andNULL left and right pointers. */static Node newNode(int data){ Node temp = new Node(); temp.val = data; temp.left = null; temp.right = null; return temp;} // Driver codepublic static void main(String[] args){ /* Let us construct a Binary Tree 4 / \ 2 9 / \ \ 3 5 7 */ Node root = null; root = newNode(4); root.left = newNode(2); root.right = newNode(9); root.left.left = newNode(3); root.left.right = newNode(8); root.right.right = newNode(7); System.out.println("The Tilt of whole tree is " + Tilt(root));}}
# Python3 Program to find Tilt of# Binary Tree # class that allocates a new node# with the given data and# None left and right pointers.class newNode: def __init__(self, data): self.val = data self.left = self.right = None # Recursive function to calculate# Tilt of whole treedef traverse(root, tilt): if (not root): return 0 # Compute tilts of left and right subtrees # and find sums of left and right subtrees left = traverse(root.left, tilt) right = traverse(root.right, tilt) # Add current tilt to overall tilt[0] += abs(left - right) # Returns sum of nodes under # current tree return left + right + root.val # Driver function to print Tilt# of whole treedef Tilt(root): tilt = [0] traverse(root, tilt) return tilt[0] # Driver codeif __name__ == '__main__': # Let us construct a Binary Tree # 4 # / \ # 2 9 # / \ \ # 3 5 7 root = None root = newNode(4) root.left = newNode(2) root.right = newNode(9) root.left.left = newNode(3) root.left.right = newNode(8) root.right.right = newNode(7) print("The Tilt of whole tree is", Tilt(root)) # This code is contributed by PranchalK
// C# Program to find Tilt of Binary Treeusing System; class GfG{ /* A binary tree node has data, pointer toleft child and a pointer to right child */public class Node{ public int val; public Node left, right;} /* Recursive function to calculate Tilt ofwhole tree */public class T{ public int tilt = 0;}static int traverse(Node root, T t ){ if (root == null) return 0; // Compute tilts of left and right subtrees // and find sums of left and right subtrees int left = traverse(root.left, t); int right = traverse(root.right, t); // Add current tilt to overall t.tilt += Math.Abs(left - right); // Returns sum of nodes under current tree return left + right + root.val;} /* Driver function to print Tilt of whole tree */static int Tilt(Node root){ T t = new T(); traverse(root, t); return t.tilt;} /* Helper function that allocates anew node with the given data andNULL left and right pointers. */static Node newNode(int data){ Node temp = new Node(); temp.val = data; temp.left = null; temp.right = null; return temp;} // Driver codepublic static void Main(String[] args){ /* Let us construct a Binary Tree 4 / \ 2 9 / \ \ 3 5 7 */ Node root = null; root = newNode(4); root.left = newNode(2); root.right = newNode(9); root.left.left = newNode(3); root.left.right = newNode(8); root.right.right = newNode(7); Console.WriteLine("The Tilt of whole tree is " + Tilt(root));}} // This code contributed by Rajput-Ji
<script> // JavaScript Program to find Tilt of Binary Tree /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node { constructor(data) { this.left = null; this.right = null; this.val = data; } } /* Recursive function to calculate Tilt of whole tree */ let tilt = 0; function traverse(root) { if (root == null) return 0; // Compute tilts of left and right subtrees // and find sums of left and right subtrees let left = traverse(root.left, tilt); let right = traverse(root.right, tilt); // Add current tilt to overall tilt += Math.abs(left - right); // Returns sum of nodes under current tree return left + right + root.val; } /* Driver function to print Tilt of whole tree */ function Tilt(root) { traverse(root); return tilt; } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ function newNode(data) { let temp = new Node(data); return temp; } /* Let us construct a Binary Tree 4 / \ 2 9 / \ \ 3 5 7 */ let root = null; root = newNode(4); root.left = newNode(2); root.right = newNode(9); root.left.left = newNode(3); root.left.right = newNode(8); root.right.right = newNode(7); document.write("The Tilt of whole tree is " + Tilt(root)); </script>
Output:
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
The Tilt of whole tree is 15
Complexity Analysis:
Time complexity: O(n), where n is the number of nodes in binary tree.
Auxiliary Space: O(n) as in worst case, depth of binary tree will be n.
Python Programming Tutorial | Count number of vowels using sets in given string | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPython Programming Tutorial | Count number of vowels using sets in given string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:07•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=LO7R3SNU6Vk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
prerna saini
PranchalKatiyar
Rajput-Ji
mukesh07
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Introduction to Tree Data Structure
What is Data Structure: Types, Classifications and Applications
Diagonal Traversal of Binary Tree
Top 50 Tree Coding Problems for Interviews
Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Iterative Preorder Traversal
Lowest Common Ancestor in a Binary Search Tree.
Boundary Traversal of binary tree
Handshaking Lemma and Interesting Tree Properties | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 394,
"s": 54,
"text": "Given a binary tree, return the tilt of the whole tree. The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null nodes are assigned tilt to be zero. Therefore, tilt of the whole tree is defined as the sum of all nodes’ tilt.Examples: "
},
{
"code": null,
"e": 821,
"s": 394,
"text": "Input :\n 1\n / \\\n 2 3\nOutput : 1\nExplanation: \nTilt of node 2 : 0\nTilt of node 3 : 0\nTilt of node 1 : |2-3| = 1\nTilt of binary tree : 0 + 0 + 1 = 1\n\nInput :\n 4\n / \\\n 2 9\n / \\ \\\n3 5 7\nOutput : 15\nExplanation: \nTilt of node 3 : 0\nTilt of node 5 : 0\nTilt of node 7 : 0\nTilt of node 2 : |3-5| = 2\nTilt of node 9 : |0-7| = 7\nTilt of node 4 : |(3+5+2)-(9+7)| = 6\nTilt of binary tree : 0 + 0 + 0 + 2 + 7 + 6 = 15"
},
{
"code": null,
"e": 1019,
"s": 823,
"text": "The idea is to recursively traverse tree. While traversing, we keep track of two things, sum of subtree rooted under current node, tilt of current node. Sum is needed to compute tilt of parent. "
},
{
"code": null,
"e": 1023,
"s": 1019,
"text": "C++"
},
{
"code": null,
"e": 1028,
"s": 1023,
"text": "Java"
},
{
"code": null,
"e": 1036,
"s": 1028,
"text": "Python3"
},
{
"code": null,
"e": 1039,
"s": 1036,
"text": "C#"
},
{
"code": null,
"e": 1050,
"s": 1039,
"text": "Javascript"
},
{
"code": "// CPP Program to find Tilt of Binary Tree#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer toleft child and a pointer to right child */struct Node { int val; struct Node *left, *right;}; /* Recursive function to calculate Tilt of whole tree */int traverse(Node* root, int* tilt){ if (!root) return 0; // Compute tilts of left and right subtrees // and find sums of left and right subtrees int left = traverse(root->left, tilt); int right = traverse(root->right, tilt); // Add current tilt to overall *tilt += abs(left - right); // Returns sum of nodes under current tree return left + right + root->val;} /* Driver function to print Tilt of whole tree */int Tilt(Node* root){ int tilt = 0; traverse(root, &tilt); return tilt;} /* Helper function that allocates anew node with the given data andNULL left and right pointers. */Node* newNode(int data){ Node* temp = new Node; temp->val = data; temp->left = temp->right = NULL; return temp;} // Driver codeint main(){ /* Let us construct a Binary Tree 4 / \\ 2 9 / \\ \\ 3 5 7 */ Node* root = NULL; root = newNode(4); root->left = newNode(2); root->right = newNode(9); root->left->left = newNode(3); root->left->right = newNode(8); root->right->right = newNode(7); cout << \"The Tilt of whole tree is \" << Tilt(root); return 0;}",
"e": 2487,
"s": 1050,
"text": null
},
{
"code": "// Java Program to find Tilt of Binary Treeimport java.util.*;class GfG { /* A binary tree node has data, pointer toleft child and a pointer to right child */static class Node { int val; Node left, right;} /* Recursive function to calculate Tilt ofwhole tree */static class T{ int tilt = 0;}static int traverse(Node root, T t ){ if (root == null) return 0; // Compute tilts of left and right subtrees // and find sums of left and right subtrees int left = traverse(root.left, t); int right = traverse(root.right, t); // Add current tilt to overall t.tilt += Math.abs(left - right); // Returns sum of nodes under current tree return left + right + root.val;} /* Driver function to print Tilt of whole tree */static int Tilt(Node root){ T t = new T(); traverse(root, t); return t.tilt;} /* Helper function that allocates anew node with the given data andNULL left and right pointers. */static Node newNode(int data){ Node temp = new Node(); temp.val = data; temp.left = null; temp.right = null; return temp;} // Driver codepublic static void main(String[] args){ /* Let us construct a Binary Tree 4 / \\ 2 9 / \\ \\ 3 5 7 */ Node root = null; root = newNode(4); root.left = newNode(2); root.right = newNode(9); root.left.left = newNode(3); root.left.right = newNode(8); root.right.right = newNode(7); System.out.println(\"The Tilt of whole tree is \" + Tilt(root));}}",
"e": 3965,
"s": 2487,
"text": null
},
{
"code": "# Python3 Program to find Tilt of# Binary Tree # class that allocates a new node# with the given data and# None left and right pointers.class newNode: def __init__(self, data): self.val = data self.left = self.right = None # Recursive function to calculate# Tilt of whole treedef traverse(root, tilt): if (not root): return 0 # Compute tilts of left and right subtrees # and find sums of left and right subtrees left = traverse(root.left, tilt) right = traverse(root.right, tilt) # Add current tilt to overall tilt[0] += abs(left - right) # Returns sum of nodes under # current tree return left + right + root.val # Driver function to print Tilt# of whole treedef Tilt(root): tilt = [0] traverse(root, tilt) return tilt[0] # Driver codeif __name__ == '__main__': # Let us construct a Binary Tree # 4 # / \\ # 2 9 # / \\ \\ # 3 5 7 root = None root = newNode(4) root.left = newNode(2) root.right = newNode(9) root.left.left = newNode(3) root.left.right = newNode(8) root.right.right = newNode(7) print(\"The Tilt of whole tree is\", Tilt(root)) # This code is contributed by PranchalK",
"e": 5187,
"s": 3965,
"text": null
},
{
"code": "// C# Program to find Tilt of Binary Treeusing System; class GfG{ /* A binary tree node has data, pointer toleft child and a pointer to right child */public class Node{ public int val; public Node left, right;} /* Recursive function to calculate Tilt ofwhole tree */public class T{ public int tilt = 0;}static int traverse(Node root, T t ){ if (root == null) return 0; // Compute tilts of left and right subtrees // and find sums of left and right subtrees int left = traverse(root.left, t); int right = traverse(root.right, t); // Add current tilt to overall t.tilt += Math.Abs(left - right); // Returns sum of nodes under current tree return left + right + root.val;} /* Driver function to print Tilt of whole tree */static int Tilt(Node root){ T t = new T(); traverse(root, t); return t.tilt;} /* Helper function that allocates anew node with the given data andNULL left and right pointers. */static Node newNode(int data){ Node temp = new Node(); temp.val = data; temp.left = null; temp.right = null; return temp;} // Driver codepublic static void Main(String[] args){ /* Let us construct a Binary Tree 4 / \\ 2 9 / \\ \\ 3 5 7 */ Node root = null; root = newNode(4); root.left = newNode(2); root.right = newNode(9); root.left.left = newNode(3); root.left.right = newNode(8); root.right.right = newNode(7); Console.WriteLine(\"The Tilt of whole tree is \" + Tilt(root));}} // This code contributed by Rajput-Ji",
"e": 6714,
"s": 5187,
"text": null
},
{
"code": "<script> // JavaScript Program to find Tilt of Binary Tree /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node { constructor(data) { this.left = null; this.right = null; this.val = data; } } /* Recursive function to calculate Tilt of whole tree */ let tilt = 0; function traverse(root) { if (root == null) return 0; // Compute tilts of left and right subtrees // and find sums of left and right subtrees let left = traverse(root.left, tilt); let right = traverse(root.right, tilt); // Add current tilt to overall tilt += Math.abs(left - right); // Returns sum of nodes under current tree return left + right + root.val; } /* Driver function to print Tilt of whole tree */ function Tilt(root) { traverse(root); return tilt; } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ function newNode(data) { let temp = new Node(data); return temp; } /* Let us construct a Binary Tree 4 / \\ 2 9 / \\ \\ 3 5 7 */ let root = null; root = newNode(4); root.left = newNode(2); root.right = newNode(9); root.left.left = newNode(3); root.left.right = newNode(8); root.right.right = newNode(7); document.write(\"The Tilt of whole tree is \" + Tilt(root)); </script>",
"e": 8243,
"s": 6714,
"text": null
},
{
"code": null,
"e": 8253,
"s": 8243,
"text": "Output: "
},
{
"code": null,
"e": 8262,
"s": 8253,
"text": "Chapters"
},
{
"code": null,
"e": 8289,
"s": 8262,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 8339,
"s": 8289,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 8362,
"s": 8339,
"text": "captions off, selected"
},
{
"code": null,
"e": 8370,
"s": 8362,
"text": "English"
},
{
"code": null,
"e": 8394,
"s": 8370,
"text": "This is a modal window."
},
{
"code": null,
"e": 8463,
"s": 8394,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 8485,
"s": 8463,
"text": "End of dialog window."
},
{
"code": null,
"e": 8514,
"s": 8485,
"text": "The Tilt of whole tree is 15"
},
{
"code": null,
"e": 8537,
"s": 8514,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 8607,
"s": 8537,
"text": "Time complexity: O(n), where n is the number of nodes in binary tree."
},
{
"code": null,
"e": 8679,
"s": 8607,
"text": "Auxiliary Space: O(n) as in worst case, depth of binary tree will be n."
},
{
"code": null,
"e": 9657,
"s": 8681,
"text": "Python Programming Tutorial | Count number of vowels using sets in given string | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPython Programming Tutorial | Count number of vowels using sets in given string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:07•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=LO7R3SNU6Vk\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 9672,
"s": 9659,
"text": "prerna saini"
},
{
"code": null,
"e": 9688,
"s": 9672,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 9698,
"s": 9688,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 9707,
"s": 9698,
"text": "mukesh07"
},
{
"code": null,
"e": 9712,
"s": 9707,
"text": "Tree"
},
{
"code": null,
"e": 9717,
"s": 9712,
"text": "Tree"
},
{
"code": null,
"e": 9815,
"s": 9717,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9847,
"s": 9815,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 9883,
"s": 9847,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 9947,
"s": 9883,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 9981,
"s": 9947,
"text": "Diagonal Traversal of Binary Tree"
},
{
"code": null,
"e": 10024,
"s": 9981,
"text": "Top 50 Tree Coding Problems for Interviews"
},
{
"code": null,
"e": 10094,
"s": 10024,
"text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)"
},
{
"code": null,
"e": 10123,
"s": 10094,
"text": "Iterative Preorder Traversal"
},
{
"code": null,
"e": 10171,
"s": 10123,
"text": "Lowest Common Ancestor in a Binary Search Tree."
},
{
"code": null,
"e": 10205,
"s": 10171,
"text": "Boundary Traversal of binary tree"
}
] |
Python | Spinner widget in kivy | 06 Feb, 2020
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.
Kivy Tutorial – Learn Kivy with Examples.
To work with spinner you must have to import:
from kivy.uix.spinner import Spinner
Spinner is a widget that provides a quick way to select one value from a set. In the default state, a spinner shows its currently selected value. Touching the spinner displays a dropdown menu with all the other available values from which the user can select a new one.Like a combo box, a spinner object can have multiple values and one of the values can be selected.A callback can be attached to the spinner object to receive notifications on selection of a value from the spinner object.
Basic Approach :
1) import kivy
2) import kivyApp
3) import Label
4) import Spinner
5) import Floatlayout
6) Set minimum version(optional)
7) create App class:
1) Create the spinner
2) Attach the labels to spinners
3) Attach a callback also
8) return Layout/widget/Class(according to requirement)
9) Run an instance of the class
Implementation of a simple spinner:
# Sample spinner app in kivy to change the# kivy default settings we use this module configfrom kivy.config import Config # 0 being off 1 being on as in true / false# you can use 0 or 1 && True or FalseConfig.set('graphics', 'resizable', True) # Program to Show how to create a switch# import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # The Label widget is for rendering text. from kivy.uix.label import Label # Spinner is a widget that provides a# quick way to select one value from a set.# like a dropdown listfrom kivy.uix.spinner import Spinner # module consist the floatlayout # to work with FloatLayout first # you have to import it from kivy.uix.floatlayout import FloatLayout # Make an App by deriving from the App classclass SpinnerExample(App): # define build def build(self): # creating floatlayout layout = FloatLayout() # creating the spinner # configure spinner object and add to layout self.spinnerObject = Spinner(text ="Python", values =("Python", "Java", "C++", "C", "C#", "PHP"), background_color =(0.784, 0.443, 0.216, 1)) self.spinnerObject.size_hint = (0.3, 0.2) self.spinnerObject.pos_hint ={'x': .35, 'y':.75} layout.add_widget(self.spinnerObject) # return the layout return layout; # Run the appif __name__ == '__main__': SpinnerExample().run()
Output:
Image 1:
Image 2:
Now if we have to tell user every time which element in a list is selected, we will display a label just beside the spinner which tells about the selected label. Also, we will print the value, and text of spinner.
Below is the Implementation:
# Sample spinner app in kivy to change the# kivy default settings we use this module configfrom kivy.config import Config # 0 being off 1 being on as in true / false# you can use 0 or 1 && True or FalseConfig.set('graphics', 'resizable', True) # Program to Show how to create a switch# import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # The Label widget is for rendering text. from kivy.uix.label import Label # Spinner is a widget that provides a# quick way to select one value from a set.# like a dropdown listfrom kivy.uix.spinner import Spinner # module consist the floatlayout # to work with FloatLayout first # you have to import it from kivy.uix.floatlayout import FloatLayout # Make an App by deriving from the App classclass SpinnerExample(App): # define build def build(self): # creating floatlayout layout = FloatLayout() # creating the spinner # configure spinner object and add to layout self.spinnerObject = Spinner(text ="Python", values =("Python", "Java", "C++", "C", "C#", "PHP"), background_color =(0.784, 0.443, 0.216, 1)) self.spinnerObject.size_hint = (0.3, 0.2) self.spinnerObject.pos_hint ={'x': .35, 'y':.75} layout.add_widget(self.spinnerObject) self.spinnerObject.bind(text = self.on_spinner_select) # It changes the label info as well # add a label displaying the selection from the spinner self.spinnerSelection = Label(text ="Selected value in spinner is: %s" %self.spinnerObject.text) layout.add_widget(self.spinnerSelection) self.spinnerSelection.pos_hint ={'x': .1, 'y':.3} return layout; # call back for the selection in spinner object def on_spinner_select(self, spinner, text): self.spinnerSelection.text = "Selected value in spinner is: %s" %self.spinnerObject.text) print('The spinner', spinner, 'have text', text) # Run the appif __name__ == '__main__': SpinnerExample().run()
Output:
Image 1:
Image 2:
Below is the output in video to get better understanding:
Media error: Format(s) not supported or source(s) not found
Python-gui
Python-kivy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Iterate over a list in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Feb, 2020"
},
{
"code": null,
"e": 264,
"s": 28,
"text": "Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications."
},
{
"code": null,
"e": 307,
"s": 264,
"text": " Kivy Tutorial – Learn Kivy with Examples."
},
{
"code": null,
"e": 353,
"s": 307,
"text": "To work with spinner you must have to import:"
},
{
"code": null,
"e": 390,
"s": 353,
"text": "from kivy.uix.spinner import Spinner"
},
{
"code": null,
"e": 880,
"s": 390,
"text": "Spinner is a widget that provides a quick way to select one value from a set. In the default state, a spinner shows its currently selected value. Touching the spinner displays a dropdown menu with all the other available values from which the user can select a new one.Like a combo box, a spinner object can have multiple values and one of the values can be selected.A callback can be attached to the spinner object to receive notifications on selection of a value from the spinner object."
},
{
"code": null,
"e": 1235,
"s": 880,
"text": "Basic Approach :\n\n1) import kivy\n2) import kivyApp\n3) import Label\n4) import Spinner\n5) import Floatlayout\n6) Set minimum version(optional)\n7) create App class:\n 1) Create the spinner\n 2) Attach the labels to spinners\n 3) Attach a callback also \n8) return Layout/widget/Class(according to requirement)\n9) Run an instance of the class"
},
{
"code": null,
"e": 1271,
"s": 1235,
"text": "Implementation of a simple spinner:"
},
{
"code": "# Sample spinner app in kivy to change the# kivy default settings we use this module configfrom kivy.config import Config # 0 being off 1 being on as in true / false# you can use 0 or 1 && True or FalseConfig.set('graphics', 'resizable', True) # Program to Show how to create a switch# import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # The Label widget is for rendering text. from kivy.uix.label import Label # Spinner is a widget that provides a# quick way to select one value from a set.# like a dropdown listfrom kivy.uix.spinner import Spinner # module consist the floatlayout # to work with FloatLayout first # you have to import it from kivy.uix.floatlayout import FloatLayout # Make an App by deriving from the App classclass SpinnerExample(App): # define build def build(self): # creating floatlayout layout = FloatLayout() # creating the spinner # configure spinner object and add to layout self.spinnerObject = Spinner(text =\"Python\", values =(\"Python\", \"Java\", \"C++\", \"C\", \"C#\", \"PHP\"), background_color =(0.784, 0.443, 0.216, 1)) self.spinnerObject.size_hint = (0.3, 0.2) self.spinnerObject.pos_hint ={'x': .35, 'y':.75} layout.add_widget(self.spinnerObject) # return the layout return layout; # Run the appif __name__ == '__main__': SpinnerExample().run() ",
"e": 2928,
"s": 1271,
"text": null
},
{
"code": null,
"e": 2936,
"s": 2928,
"text": "Output:"
},
{
"code": null,
"e": 2945,
"s": 2936,
"text": "Image 1:"
},
{
"code": null,
"e": 2954,
"s": 2945,
"text": "Image 2:"
},
{
"code": null,
"e": 3168,
"s": 2954,
"text": "Now if we have to tell user every time which element in a list is selected, we will display a label just beside the spinner which tells about the selected label. Also, we will print the value, and text of spinner."
},
{
"code": null,
"e": 3197,
"s": 3168,
"text": "Below is the Implementation:"
},
{
"code": "# Sample spinner app in kivy to change the# kivy default settings we use this module configfrom kivy.config import Config # 0 being off 1 being on as in true / false# you can use 0 or 1 && True or FalseConfig.set('graphics', 'resizable', True) # Program to Show how to create a switch# import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # The Label widget is for rendering text. from kivy.uix.label import Label # Spinner is a widget that provides a# quick way to select one value from a set.# like a dropdown listfrom kivy.uix.spinner import Spinner # module consist the floatlayout # to work with FloatLayout first # you have to import it from kivy.uix.floatlayout import FloatLayout # Make an App by deriving from the App classclass SpinnerExample(App): # define build def build(self): # creating floatlayout layout = FloatLayout() # creating the spinner # configure spinner object and add to layout self.spinnerObject = Spinner(text =\"Python\", values =(\"Python\", \"Java\", \"C++\", \"C\", \"C#\", \"PHP\"), background_color =(0.784, 0.443, 0.216, 1)) self.spinnerObject.size_hint = (0.3, 0.2) self.spinnerObject.pos_hint ={'x': .35, 'y':.75} layout.add_widget(self.spinnerObject) self.spinnerObject.bind(text = self.on_spinner_select) # It changes the label info as well # add a label displaying the selection from the spinner self.spinnerSelection = Label(text =\"Selected value in spinner is: %s\" %self.spinnerObject.text) layout.add_widget(self.spinnerSelection) self.spinnerSelection.pos_hint ={'x': .1, 'y':.3} return layout; # call back for the selection in spinner object def on_spinner_select(self, spinner, text): self.spinnerSelection.text = \"Selected value in spinner is: %s\" %self.spinnerObject.text) print('The spinner', spinner, 'have text', text) # Run the appif __name__ == '__main__': SpinnerExample().run() ",
"e": 5575,
"s": 3197,
"text": null
},
{
"code": null,
"e": 5583,
"s": 5575,
"text": "Output:"
},
{
"code": null,
"e": 5592,
"s": 5583,
"text": "Image 1:"
},
{
"code": null,
"e": 5601,
"s": 5592,
"text": "Image 2:"
},
{
"code": null,
"e": 5659,
"s": 5601,
"text": "Below is the output in video to get better understanding:"
},
{
"code": null,
"e": 5719,
"s": 5659,
"text": "Media error: Format(s) not supported or source(s) not found"
},
{
"code": null,
"e": 5730,
"s": 5719,
"text": "Python-gui"
},
{
"code": null,
"e": 5742,
"s": 5730,
"text": "Python-kivy"
},
{
"code": null,
"e": 5749,
"s": 5742,
"text": "Python"
},
{
"code": null,
"e": 5847,
"s": 5749,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5875,
"s": 5847,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 5925,
"s": 5875,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 5947,
"s": 5925,
"text": "Python map() function"
},
{
"code": null,
"e": 5991,
"s": 5947,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 6033,
"s": 5991,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 6055,
"s": 6033,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 6090,
"s": 6055,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 6116,
"s": 6090,
"text": "Python String | replace()"
},
{
"code": null,
"e": 6148,
"s": 6116,
"text": "How to Install PIP on Windows ?"
}
] |
Secrets | Python module to Generate secure random numbers | 30 May, 2018
The secrets module is used for generating random numbers for managing important data such as passwords, account authentication, security tokens, and related secrets, that are cryptographically strong. This module is responsible for providing access to the most secure source of randomness. This module is present in Python 3.6 and above.
Random Numbers: class secrets.SystemRandom
This class uses the os.urandom() function for the generation of random numbers from sources provided by the operating system.
secrets.choice(sequence): This function returns a randomly-chosen element from a non-empty sequence to manage a basic level of security.Example 1 : Generate a ten-character alphanumeric password.import secretsimport string alphabet = string.ascii_letters + string.digitspassword = ''.join(secrets.choice(alphabet) for i in range(10)) print(password)Output :'tmX47l1uo4'
Example 2 : Generate a ten-character alphanumeric password with at least one lowercase character, at least one uppercase character, and at least three digits.import secretsimport string alphabet = string.ascii_letters + string.digitswhile True: password = ''.join(secrets.choice(alphabet) for i in range(10)) if (any(c.islower() for c in password) and any(c.isupper() for c in password) and sum(c.isdigit() for c in password) >= 3): print(password) breakOutput :Tx8LppU05Q
secrets.randbelow(n): This function returns a random integer in the range [0, n).import secrets passwd = secrets.randbelow(20)print(passwd)Output :2
secrets.randbits(k): This function returns an int with k random bits.import secrets passwd = secrets.randbits(7)print(passwd)Output :61
secrets.choice(sequence): This function returns a randomly-chosen element from a non-empty sequence to manage a basic level of security.Example 1 : Generate a ten-character alphanumeric password.import secretsimport string alphabet = string.ascii_letters + string.digitspassword = ''.join(secrets.choice(alphabet) for i in range(10)) print(password)Output :'tmX47l1uo4'
Example 2 : Generate a ten-character alphanumeric password with at least one lowercase character, at least one uppercase character, and at least three digits.import secretsimport string alphabet = string.ascii_letters + string.digitswhile True: password = ''.join(secrets.choice(alphabet) for i in range(10)) if (any(c.islower() for c in password) and any(c.isupper() for c in password) and sum(c.isdigit() for c in password) >= 3): print(password) breakOutput :Tx8LppU05Q
import secretsimport string alphabet = string.ascii_letters + string.digitspassword = ''.join(secrets.choice(alphabet) for i in range(10)) print(password)
Output :
'tmX47l1uo4'
Example 2 : Generate a ten-character alphanumeric password with at least one lowercase character, at least one uppercase character, and at least three digits.
import secretsimport string alphabet = string.ascii_letters + string.digitswhile True: password = ''.join(secrets.choice(alphabet) for i in range(10)) if (any(c.islower() for c in password) and any(c.isupper() for c in password) and sum(c.isdigit() for c in password) >= 3): print(password) break
Output :
Tx8LppU05Q
secrets.randbelow(n): This function returns a random integer in the range [0, n).import secrets passwd = secrets.randbelow(20)print(passwd)Output :2
import secrets passwd = secrets.randbelow(20)print(passwd)
Output :
2
secrets.randbits(k): This function returns an int with k random bits.import secrets passwd = secrets.randbits(7)print(passwd)Output :61
import secrets passwd = secrets.randbits(7)print(passwd)
Output :
61
Generating tokens
This module provides several functions for generating secure tokens for applications such as password resets, hard-to-guess URLs etc.
secrets.token_bytes([nbytes=None]) : This function is responsible for generating a random byte string containing nbytes number of bytes. If no value is provided, a reasonable default is used.import secrets token1 = secrets.token_bytes()token2 = secrets.token_bytes(10) print(token1)print(token2)Output :b"\x86?\x85\xcf\x8ek8ud\x8a\x92\x8b>R\xc7\x89_\xc4x\xce'u]\x95\x0c\x05*?HG8\xfb"
b'Dx\xe8\x7f\xc05\xdf\xe0\xf6\xe1'
secrets.token_hex([nbytes=None]) : This function is responsible for generating a random text string in hexadecimal containing nbytes random bytes. If no value is provided, a reasonable default is used.import secrets token1 = secrets.token_hex(16)token2 = secrets.token_hex(9) print(token1)print(token2)Output :5d894a501c88fbe735c6ff496a6d3e51
78baed9057e597dce4
secrets.token_urlsafe([nbytes=None]) : This function is responsible for generating a random URL-safe text string containing nbytes random bytes. This is suitable for password recovery applications.Example : Generate a hard-to-guess temporary URL containing a security token.import secrets url = 'https://mydomain.com/reset=' + secrets.token_urlsafe()print(url)Output :https://mydomain.com/reset=GbOiFIvhMoqWsfaTQKbj8ydbo8G1lsMx1ECa6SXjb1s
How many bytes should tokens use?At least 32 bytes for tokens should be used to be secure against a brute-force attack.
secrets.token_bytes([nbytes=None]) : This function is responsible for generating a random byte string containing nbytes number of bytes. If no value is provided, a reasonable default is used.import secrets token1 = secrets.token_bytes()token2 = secrets.token_bytes(10) print(token1)print(token2)Output :b"\x86?\x85\xcf\x8ek8ud\x8a\x92\x8b>R\xc7\x89_\xc4x\xce'u]\x95\x0c\x05*?HG8\xfb"
b'Dx\xe8\x7f\xc05\xdf\xe0\xf6\xe1'
import secrets token1 = secrets.token_bytes()token2 = secrets.token_bytes(10) print(token1)print(token2)
Output :
b"\x86?\x85\xcf\x8ek8ud\x8a\x92\x8b>R\xc7\x89_\xc4x\xce'u]\x95\x0c\x05*?HG8\xfb"
b'Dx\xe8\x7f\xc05\xdf\xe0\xf6\xe1'
secrets.token_hex([nbytes=None]) : This function is responsible for generating a random text string in hexadecimal containing nbytes random bytes. If no value is provided, a reasonable default is used.import secrets token1 = secrets.token_hex(16)token2 = secrets.token_hex(9) print(token1)print(token2)Output :5d894a501c88fbe735c6ff496a6d3e51
78baed9057e597dce4
import secrets token1 = secrets.token_hex(16)token2 = secrets.token_hex(9) print(token1)print(token2)
Output :
5d894a501c88fbe735c6ff496a6d3e51
78baed9057e597dce4
secrets.token_urlsafe([nbytes=None]) : This function is responsible for generating a random URL-safe text string containing nbytes random bytes. This is suitable for password recovery applications.Example : Generate a hard-to-guess temporary URL containing a security token.import secrets url = 'https://mydomain.com/reset=' + secrets.token_urlsafe()print(url)Output :https://mydomain.com/reset=GbOiFIvhMoqWsfaTQKbj8ydbo8G1lsMx1ECa6SXjb1s
import secrets url = 'https://mydomain.com/reset=' + secrets.token_urlsafe()print(url)
Output :
https://mydomain.com/reset=GbOiFIvhMoqWsfaTQKbj8ydbo8G1lsMx1ECa6SXjb1s
How many bytes should tokens use?At least 32 bytes for tokens should be used to be secure against a brute-force attack.
Reference: Official Python DocumentationThis article is contributed by Aditi Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Python-Library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 May, 2018"
},
{
"code": null,
"e": 392,
"s": 54,
"text": "The secrets module is used for generating random numbers for managing important data such as passwords, account authentication, security tokens, and related secrets, that are cryptographically strong. This module is responsible for providing access to the most secure source of randomness. This module is present in Python 3.6 and above."
},
{
"code": null,
"e": 435,
"s": 392,
"text": "Random Numbers: class secrets.SystemRandom"
},
{
"code": null,
"e": 561,
"s": 435,
"text": "This class uses the os.urandom() function for the generation of random numbers from sources provided by the operating system."
},
{
"code": null,
"e": 1719,
"s": 561,
"text": "secrets.choice(sequence): This function returns a randomly-chosen element from a non-empty sequence to manage a basic level of security.Example 1 : Generate a ten-character alphanumeric password.import secretsimport string alphabet = string.ascii_letters + string.digitspassword = ''.join(secrets.choice(alphabet) for i in range(10)) print(password)Output :'tmX47l1uo4'\nExample 2 : Generate a ten-character alphanumeric password with at least one lowercase character, at least one uppercase character, and at least three digits.import secretsimport string alphabet = string.ascii_letters + string.digitswhile True: password = ''.join(secrets.choice(alphabet) for i in range(10)) if (any(c.islower() for c in password) and any(c.isupper() for c in password) and sum(c.isdigit() for c in password) >= 3): print(password) breakOutput :Tx8LppU05Q\nsecrets.randbelow(n): This function returns a random integer in the range [0, n).import secrets passwd = secrets.randbelow(20)print(passwd)Output :2\nsecrets.randbits(k): This function returns an int with k random bits.import secrets passwd = secrets.randbits(7)print(passwd)Output :61\n"
},
{
"code": null,
"e": 2590,
"s": 1719,
"text": "secrets.choice(sequence): This function returns a randomly-chosen element from a non-empty sequence to manage a basic level of security.Example 1 : Generate a ten-character alphanumeric password.import secretsimport string alphabet = string.ascii_letters + string.digitspassword = ''.join(secrets.choice(alphabet) for i in range(10)) print(password)Output :'tmX47l1uo4'\nExample 2 : Generate a ten-character alphanumeric password with at least one lowercase character, at least one uppercase character, and at least three digits.import secretsimport string alphabet = string.ascii_letters + string.digitswhile True: password = ''.join(secrets.choice(alphabet) for i in range(10)) if (any(c.islower() for c in password) and any(c.isupper() for c in password) and sum(c.isdigit() for c in password) >= 3): print(password) breakOutput :Tx8LppU05Q\n"
},
{
"code": "import secretsimport string alphabet = string.ascii_letters + string.digitspassword = ''.join(secrets.choice(alphabet) for i in range(10)) print(password)",
"e": 2747,
"s": 2590,
"text": null
},
{
"code": null,
"e": 2756,
"s": 2747,
"text": "Output :"
},
{
"code": null,
"e": 2770,
"s": 2756,
"text": "'tmX47l1uo4'\n"
},
{
"code": null,
"e": 2929,
"s": 2770,
"text": "Example 2 : Generate a ten-character alphanumeric password with at least one lowercase character, at least one uppercase character, and at least three digits."
},
{
"code": "import secretsimport string alphabet = string.ascii_letters + string.digitswhile True: password = ''.join(secrets.choice(alphabet) for i in range(10)) if (any(c.islower() for c in password) and any(c.isupper() for c in password) and sum(c.isdigit() for c in password) >= 3): print(password) break",
"e": 3251,
"s": 2929,
"text": null
},
{
"code": null,
"e": 3260,
"s": 3251,
"text": "Output :"
},
{
"code": null,
"e": 3272,
"s": 3260,
"text": "Tx8LppU05Q\n"
},
{
"code": null,
"e": 3423,
"s": 3272,
"text": "secrets.randbelow(n): This function returns a random integer in the range [0, n).import secrets passwd = secrets.randbelow(20)print(passwd)Output :2\n"
},
{
"code": "import secrets passwd = secrets.randbelow(20)print(passwd)",
"e": 3483,
"s": 3423,
"text": null
},
{
"code": null,
"e": 3492,
"s": 3483,
"text": "Output :"
},
{
"code": null,
"e": 3495,
"s": 3492,
"text": "2\n"
},
{
"code": null,
"e": 3633,
"s": 3495,
"text": "secrets.randbits(k): This function returns an int with k random bits.import secrets passwd = secrets.randbits(7)print(passwd)Output :61\n"
},
{
"code": "import secrets passwd = secrets.randbits(7)print(passwd)",
"e": 3691,
"s": 3633,
"text": null
},
{
"code": null,
"e": 3700,
"s": 3691,
"text": "Output :"
},
{
"code": null,
"e": 3704,
"s": 3700,
"text": "61\n"
},
{
"code": null,
"e": 3722,
"s": 3704,
"text": "Generating tokens"
},
{
"code": null,
"e": 3856,
"s": 3722,
"text": "This module provides several functions for generating secure tokens for applications such as password resets, hard-to-guess URLs etc."
},
{
"code": null,
"e": 5201,
"s": 3856,
"text": "secrets.token_bytes([nbytes=None]) : This function is responsible for generating a random byte string containing nbytes number of bytes. If no value is provided, a reasonable default is used.import secrets token1 = secrets.token_bytes()token2 = secrets.token_bytes(10) print(token1)print(token2)Output :b\"\\x86?\\x85\\xcf\\x8ek8ud\\x8a\\x92\\x8b>R\\xc7\\x89_\\xc4x\\xce'u]\\x95\\x0c\\x05*?HG8\\xfb\"\nb'Dx\\xe8\\x7f\\xc05\\xdf\\xe0\\xf6\\xe1'\nsecrets.token_hex([nbytes=None]) : This function is responsible for generating a random text string in hexadecimal containing nbytes random bytes. If no value is provided, a reasonable default is used.import secrets token1 = secrets.token_hex(16)token2 = secrets.token_hex(9) print(token1)print(token2)Output :5d894a501c88fbe735c6ff496a6d3e51\n78baed9057e597dce4\nsecrets.token_urlsafe([nbytes=None]) : This function is responsible for generating a random URL-safe text string containing nbytes random bytes. This is suitable for password recovery applications.Example : Generate a hard-to-guess temporary URL containing a security token.import secrets url = 'https://mydomain.com/reset=' + secrets.token_urlsafe()print(url)Output :https://mydomain.com/reset=GbOiFIvhMoqWsfaTQKbj8ydbo8G1lsMx1ECa6SXjb1s\nHow many bytes should tokens use?At least 32 bytes for tokens should be used to be secure against a brute-force attack."
},
{
"code": null,
"e": 5623,
"s": 5201,
"text": "secrets.token_bytes([nbytes=None]) : This function is responsible for generating a random byte string containing nbytes number of bytes. If no value is provided, a reasonable default is used.import secrets token1 = secrets.token_bytes()token2 = secrets.token_bytes(10) print(token1)print(token2)Output :b\"\\x86?\\x85\\xcf\\x8ek8ud\\x8a\\x92\\x8b>R\\xc7\\x89_\\xc4x\\xce'u]\\x95\\x0c\\x05*?HG8\\xfb\"\nb'Dx\\xe8\\x7f\\xc05\\xdf\\xe0\\xf6\\xe1'\n"
},
{
"code": "import secrets token1 = secrets.token_bytes()token2 = secrets.token_bytes(10) print(token1)print(token2)",
"e": 5730,
"s": 5623,
"text": null
},
{
"code": null,
"e": 5739,
"s": 5730,
"text": "Output :"
},
{
"code": null,
"e": 5856,
"s": 5739,
"text": "b\"\\x86?\\x85\\xcf\\x8ek8ud\\x8a\\x92\\x8b>R\\xc7\\x89_\\xc4x\\xce'u]\\x95\\x0c\\x05*?HG8\\xfb\"\nb'Dx\\xe8\\x7f\\xc05\\xdf\\xe0\\xf6\\xe1'\n"
},
{
"code": null,
"e": 6221,
"s": 5856,
"text": "secrets.token_hex([nbytes=None]) : This function is responsible for generating a random text string in hexadecimal containing nbytes random bytes. If no value is provided, a reasonable default is used.import secrets token1 = secrets.token_hex(16)token2 = secrets.token_hex(9) print(token1)print(token2)Output :5d894a501c88fbe735c6ff496a6d3e51\n78baed9057e597dce4\n"
},
{
"code": "import secrets token1 = secrets.token_hex(16)token2 = secrets.token_hex(9) print(token1)print(token2)",
"e": 6325,
"s": 6221,
"text": null
},
{
"code": null,
"e": 6334,
"s": 6325,
"text": "Output :"
},
{
"code": null,
"e": 6387,
"s": 6334,
"text": "5d894a501c88fbe735c6ff496a6d3e51\n78baed9057e597dce4\n"
},
{
"code": null,
"e": 6828,
"s": 6387,
"text": "secrets.token_urlsafe([nbytes=None]) : This function is responsible for generating a random URL-safe text string containing nbytes random bytes. This is suitable for password recovery applications.Example : Generate a hard-to-guess temporary URL containing a security token.import secrets url = 'https://mydomain.com/reset=' + secrets.token_urlsafe()print(url)Output :https://mydomain.com/reset=GbOiFIvhMoqWsfaTQKbj8ydbo8G1lsMx1ECa6SXjb1s\n"
},
{
"code": "import secrets url = 'https://mydomain.com/reset=' + secrets.token_urlsafe()print(url)",
"e": 6916,
"s": 6828,
"text": null
},
{
"code": null,
"e": 6925,
"s": 6916,
"text": "Output :"
},
{
"code": null,
"e": 6997,
"s": 6925,
"text": "https://mydomain.com/reset=GbOiFIvhMoqWsfaTQKbj8ydbo8G1lsMx1ECa6SXjb1s\n"
},
{
"code": null,
"e": 7117,
"s": 6997,
"text": "How many bytes should tokens use?At least 32 bytes for tokens should be used to be secure against a brute-force attack."
},
{
"code": null,
"e": 7456,
"s": 7117,
"text": "Reference: Official Python DocumentationThis article is contributed by Aditi Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 7581,
"s": 7456,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 7596,
"s": 7581,
"text": "Python-Library"
},
{
"code": null,
"e": 7603,
"s": 7596,
"text": "Python"
},
{
"code": null,
"e": 7701,
"s": 7603,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7733,
"s": 7701,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 7760,
"s": 7733,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 7781,
"s": 7760,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 7812,
"s": 7781,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 7868,
"s": 7812,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 7891,
"s": 7868,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 7933,
"s": 7891,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 7975,
"s": 7933,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 8014,
"s": 7975,
"text": "Python | datetime.timedelta() function"
}
] |
Kth largest element in a stream | Practice | GeeksforGeeks | Given an input stream arr[] of n integers. Find the Kth largest element for each element in the stream and if the Kth element doesn't exist, return -1.
Example 1:
Input:
k = 4, n = 6
arr[] = {1, 2, 3, 4, 5, 6}
Output:
-1 -1 -1 1 2 3
Explanation:
k = 4
For 1, the 4th largest element doesn't
exist so we print -1.
For 2, the 4th largest element doesn't
exist so we print -1.
For 3, the 4th largest element doesn't
exist so we print -1.
For 4, the 4th largest element is 1.
For 5, the 4th largest element is 2.
for 6, the 4th largest element is 3.
Example 2:
Input:
k = 1, n = 2
arr[] = {3, 4}
Output:
3 4
Explanation:
For the 1st and 2nd element the 1st largest
element is itself.
Your Task:
You don't need to read input or print anything. Your task is to complete the function kthLargest() which takes 2 Integers k, and n and also an array arr[] of size n as input and returns the kth largest element in the stream.
Expected Time Complexity: O(nlogk)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ k ≤ n ≤ 105
1 ≤ arr[i] ≤ 105
0
rayalravi20016 days ago
c++ solution
vector<int> res; int old=0; priority_queue<int,vector<int>,greater<int>> pq; for(int i=0; i<n; i++){ if(i<k-1){ res.push_back(-1); pq.push(arr[i]); } else{ pq.push(arr[i]); int top = pq.top(); (old>top)?res.push_back(old):res.push_back(top); if(old<top){ old = top; } pq.pop(); } } return res;
+1
bhaskarmaheshwari84 weeks ago
int prev=0; vector<int> v(n,-1); priority_queue<int,vector<int>,greater<int>> q; for(int i=0;i<n;i++) { q.push(arr[i]); if(i+1>=k) { if(q.top()>prev) { v[i]=q.top(); prev=q.top(); q.pop(); } else { v[i]=prev; q.pop(); } } } return v;
+1
badgujarsachin832 months ago
vector<int> kthLargest(int k, int arr[], int n) {
// code here
priority_queue<int,vector<int>,greater<int>> q;
vector<int > v;
for(int i=0;i<k;i++){
q.push(arr[i]);
if(i<k-1){
v.push_back(-1);
}
}
for(int i=k;i<n;i++){
v.push_back(q.top());
if(arr[i]>q.top()){
q.pop();
q.push(arr[i]);
}
}
v.push_back(q.top());
return v;
}
-1
saurabhsathe12343 months ago
Simple C++ Solution Using MinHeap : 0.7sec
vector<int> kthLargest(int k, int arr[], int n) {
// code here
priority_queue<int , vector<int>,greater<int>> pq;
vector<int> v;
for(int i=0;i<k;i++)
{
pq.push(arr[i]);
if(i<k-1)
v.push_back(-1);
}
for(int i=k ; i<n ; i++)
{
v.push_back(pq.top());
if(arr[i]> pq.top())
{
pq.pop();
pq.push(arr[i]);
}
}
v.push_back(pq.top());
return v;
}
+1
abhixhek053 months ago
vector<int> kthLargest(int k, int arr[], int n) {
// code here
priority_queue<int,vector<int>, greater<int>>q;
vector<int>ans;
for(int i=0;i<k-1;i++){
ans.push_back(-1);
q.push(arr[i]);
}
for(int i=k-1;i<n;i++){
q.push(arr[i]);
if(q.size()>k){
q.pop();
}
ans.push_back(q.top());
}
return ans;
}
-2
kumaarsahab4323 months ago
//Using Priority Queue
vector<int> kthLargest(int k, int arr[], int n) {
vector<int> ans ;
priority_queue<int, vector<int>, greater<int>> pq ;
for(int i=0 ; i<n ; i++)
{
pq.push(arr[i]) ;
if(pq.size()>k) pq.pop() ;
if(pq.size()==k)
ans.push_back(pq.top()) ;
else ans.push_back(-1) ;
}
return ans ;
}
-1
areeshaanjum7483 months ago
class Solution { static int[] kthLargest(int k, int[] arr, int n) { int[] ans = new int[n]; int i = 0; //i will point to ans array //We will add (-1) k-1 times bcoz upto that //kth element would not exist while(i < k-1){ ans[i] = -1; i++; } //Let us take the stream as 2, 1, 4, 3 //4th largest elem will be '1' PriorityQueue<Integer> minHeap = new PriorityQueue<>(k); int index = 0; while(index < k){ minHeap.add(arr[index]); index++; } ans[i] = minHeap.peek(); i++; //Now, the stream becomes 2, 1, 4, 3, 0 //this '0' will not change 4th largest elem //So we can say any elem less than the 4th largest elem //will not change the 4th largest elem //Atlast, our stream becomes 2, 1, 4, 3, 0, 5 //this '5' will definitely change the 4th largest elem //now our 4th largest elem will be '2' while(index<n){ if(arr[index] > minHeap.peek()){ minHeap.poll(); minHeap.add(arr[index]); } ans[i] = minHeap.peek(); index++; i++; } return ans; }};
-3
harshchittora20013 months ago
vector<int> kthLargest(int k, int arr[], int n) { // code here vector<int>x; priority_queue<int,vector<int>,greater<int>>min_heap; for(int i=0;i<n;i++) { min_heap.push(arr[i]); if(min_heap.size()>k) { min_heap.pop(); } if(min_heap.size()>=k) { x.push_back(min_heap.top()); } else if(min_heap.size()<=k) { x.push_back(-1); } } return x; }
-1
nitind3563 months ago
Simple C++ Code:-
vector<int> kthLargest(int k, int arr[], int n) {
vector<int>x;
priority_queue<int,vector<int>,greater<int>>min;
for(int i=0;i<n;i++)
{
min.push(arr[i]);
if(min.size()>k)
{
min.pop();
}
if(min.size()>=k)
{
x.push_back(min.top());
}
else if(min.size()<k)
{
x.push_back(-1);
}
}
return x;
}
-2
radheshyamnitj4 months ago
vector<int>ans; priority_queue<int,vector<int>,greater<int>> minheap;
for(int i=0;i<n;i++){
if(minheap.size()<k)
minheap.push(arr[i]);
if(minheap.size()<k)
ans.push_back(-1);
if(minheap.size()==k) {
ans.push_back(minheap.top());
if(minheap.top() < arr[i+1] && i<n-1)
minheap.pop();
}
}
return ans;
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 390,
"s": 238,
"text": "Given an input stream arr[] of n integers. Find the Kth largest element for each element in the stream and if the Kth element doesn't exist, return -1."
},
{
"code": null,
"e": 401,
"s": 390,
"text": "Example 1:"
},
{
"code": null,
"e": 784,
"s": 401,
"text": "Input:\nk = 4, n = 6\narr[] = {1, 2, 3, 4, 5, 6}\nOutput:\n-1 -1 -1 1 2 3\nExplanation:\nk = 4\nFor 1, the 4th largest element doesn't\nexist so we print -1.\nFor 2, the 4th largest element doesn't\nexist so we print -1.\nFor 3, the 4th largest element doesn't\nexist so we print -1.\nFor 4, the 4th largest element is 1.\nFor 5, the 4th largest element is 2.\nfor 6, the 4th largest element is 3."
},
{
"code": null,
"e": 795,
"s": 784,
"text": "Example 2:"
},
{
"code": null,
"e": 921,
"s": 795,
"text": "Input:\nk = 1, n = 2\narr[] = {3, 4}\nOutput:\n3 4 \nExplanation: \nFor the 1st and 2nd element the 1st largest \nelement is itself."
},
{
"code": null,
"e": 1159,
"s": 923,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function kthLargest() which takes 2 Integers k, and n and also an array arr[] of size n as input and returns the kth largest element in the stream."
},
{
"code": null,
"e": 1227,
"s": 1161,
"text": "Expected Time Complexity: O(nlogk)\nExpected Auxiliary Space: O(n)"
},
{
"code": null,
"e": 1275,
"s": 1229,
"text": "Constraints:\n1 ≤ k ≤ n ≤ 105\n1 ≤ arr[i] ≤ 105"
},
{
"code": null,
"e": 1277,
"s": 1275,
"text": "0"
},
{
"code": null,
"e": 1301,
"s": 1277,
"text": "rayalravi20016 days ago"
},
{
"code": null,
"e": 1315,
"s": 1301,
"text": "c++ solution"
},
{
"code": null,
"e": 1812,
"s": 1317,
"text": " vector<int> res; int old=0; priority_queue<int,vector<int>,greater<int>> pq; for(int i=0; i<n; i++){ if(i<k-1){ res.push_back(-1); pq.push(arr[i]); } else{ pq.push(arr[i]); int top = pq.top(); (old>top)?res.push_back(old):res.push_back(top); if(old<top){ old = top; } pq.pop(); } } return res;"
},
{
"code": null,
"e": 1815,
"s": 1812,
"text": "+1"
},
{
"code": null,
"e": 1845,
"s": 1815,
"text": "bhaskarmaheshwari84 weeks ago"
},
{
"code": null,
"e": 2374,
"s": 1845,
"text": "int prev=0; vector<int> v(n,-1); priority_queue<int,vector<int>,greater<int>> q; for(int i=0;i<n;i++) { q.push(arr[i]); if(i+1>=k) { if(q.top()>prev) { v[i]=q.top(); prev=q.top(); q.pop(); } else { v[i]=prev; q.pop(); } } } return v;"
},
{
"code": null,
"e": 2377,
"s": 2374,
"text": "+1"
},
{
"code": null,
"e": 2406,
"s": 2377,
"text": "badgujarsachin832 months ago"
},
{
"code": null,
"e": 2926,
"s": 2406,
"text": "vector<int> kthLargest(int k, int arr[], int n) {\n // code here\n priority_queue<int,vector<int>,greater<int>> q;\n vector<int > v;\n for(int i=0;i<k;i++){\n q.push(arr[i]);\n if(i<k-1){\n v.push_back(-1);\n }\n }\n for(int i=k;i<n;i++){\n v.push_back(q.top());\n if(arr[i]>q.top()){\n q.pop();\n q.push(arr[i]);\n }\n }\n v.push_back(q.top());\n return v;\n }"
},
{
"code": null,
"e": 2929,
"s": 2926,
"text": "-1"
},
{
"code": null,
"e": 2958,
"s": 2929,
"text": "saurabhsathe12343 months ago"
},
{
"code": null,
"e": 3001,
"s": 2958,
"text": "Simple C++ Solution Using MinHeap : 0.7sec"
},
{
"code": null,
"e": 3576,
"s": 3001,
"text": "vector<int> kthLargest(int k, int arr[], int n) {\n \n // code here\n priority_queue<int , vector<int>,greater<int>> pq;\n vector<int> v;\n for(int i=0;i<k;i++)\n {\n pq.push(arr[i]);\n if(i<k-1)\n v.push_back(-1);\n }\n for(int i=k ; i<n ; i++)\n {\n v.push_back(pq.top());\n if(arr[i]> pq.top())\n {\n pq.pop();\n pq.push(arr[i]);\n \n }\n }\n v.push_back(pq.top());\n return v;\n }"
},
{
"code": null,
"e": 3579,
"s": 3576,
"text": "+1"
},
{
"code": null,
"e": 3602,
"s": 3579,
"text": "abhixhek053 months ago"
},
{
"code": null,
"e": 4094,
"s": 3602,
"text": " vector<int> kthLargest(int k, int arr[], int n) {\n // code here\n priority_queue<int,vector<int>, greater<int>>q;\n vector<int>ans;\n for(int i=0;i<k-1;i++){\n ans.push_back(-1);\n q.push(arr[i]);\n \n }\n for(int i=k-1;i<n;i++){\n q.push(arr[i]);\n \n if(q.size()>k){\n q.pop();\n }\n ans.push_back(q.top()); \n }\n return ans;\n }"
},
{
"code": null,
"e": 4097,
"s": 4094,
"text": "-2"
},
{
"code": null,
"e": 4124,
"s": 4097,
"text": "kumaarsahab4323 months ago"
},
{
"code": null,
"e": 4549,
"s": 4124,
"text": "//Using Priority Queue\nvector<int> kthLargest(int k, int arr[], int n) {\n vector<int> ans ;\n priority_queue<int, vector<int>, greater<int>> pq ;\n for(int i=0 ; i<n ; i++)\n {\n pq.push(arr[i]) ;\n if(pq.size()>k) pq.pop() ;\n if(pq.size()==k)\n ans.push_back(pq.top()) ;\n else ans.push_back(-1) ;\n }\n \n return ans ;\n }"
},
{
"code": null,
"e": 4552,
"s": 4549,
"text": "-1"
},
{
"code": null,
"e": 4580,
"s": 4552,
"text": "areeshaanjum7483 months ago"
},
{
"code": null,
"e": 5855,
"s": 4580,
"text": "class Solution { static int[] kthLargest(int k, int[] arr, int n) { int[] ans = new int[n]; int i = 0; //i will point to ans array //We will add (-1) k-1 times bcoz upto that //kth element would not exist while(i < k-1){ ans[i] = -1; i++; } //Let us take the stream as 2, 1, 4, 3 //4th largest elem will be '1' PriorityQueue<Integer> minHeap = new PriorityQueue<>(k); int index = 0; while(index < k){ minHeap.add(arr[index]); index++; } ans[i] = minHeap.peek(); i++; //Now, the stream becomes 2, 1, 4, 3, 0 //this '0' will not change 4th largest elem //So we can say any elem less than the 4th largest elem //will not change the 4th largest elem //Atlast, our stream becomes 2, 1, 4, 3, 0, 5 //this '5' will definitely change the 4th largest elem //now our 4th largest elem will be '2' while(index<n){ if(arr[index] > minHeap.peek()){ minHeap.poll(); minHeap.add(arr[index]); } ans[i] = minHeap.peek(); index++; i++; } return ans; }};"
},
{
"code": null,
"e": 5858,
"s": 5855,
"text": "-3"
},
{
"code": null,
"e": 5888,
"s": 5858,
"text": "harshchittora20013 months ago"
},
{
"code": null,
"e": 6361,
"s": 5888,
"text": " vector<int> kthLargest(int k, int arr[], int n) { // code here vector<int>x; priority_queue<int,vector<int>,greater<int>>min_heap; for(int i=0;i<n;i++) { min_heap.push(arr[i]); if(min_heap.size()>k) { min_heap.pop(); } if(min_heap.size()>=k) { x.push_back(min_heap.top()); } else if(min_heap.size()<=k) { x.push_back(-1); } } return x; }"
},
{
"code": null,
"e": 6364,
"s": 6361,
"text": "-1"
},
{
"code": null,
"e": 6386,
"s": 6364,
"text": "nitind3563 months ago"
},
{
"code": null,
"e": 6850,
"s": 6386,
"text": "Simple C++ Code:-\n\nvector<int> kthLargest(int k, int arr[], int n) {\n vector<int>x;\n priority_queue<int,vector<int>,greater<int>>min;\n for(int i=0;i<n;i++)\n {\n min.push(arr[i]);\n if(min.size()>k)\n {\n min.pop();\n }\n if(min.size()>=k)\n {\n x.push_back(min.top());\n }\n else if(min.size()<k)\n {\n x.push_back(-1);\n }\n }\n return x;\n}"
},
{
"code": null,
"e": 6853,
"s": 6850,
"text": "-2"
},
{
"code": null,
"e": 6880,
"s": 6853,
"text": "radheshyamnitj4 months ago"
},
{
"code": null,
"e": 7411,
"s": 6880,
"text": " vector<int>ans; priority_queue<int,vector<int>,greater<int>> minheap;\n \n for(int i=0;i<n;i++){\n \n if(minheap.size()<k)\n minheap.push(arr[i]);\n \n if(minheap.size()<k)\n ans.push_back(-1);\n \n if(minheap.size()==k) {\n ans.push_back(minheap.top());\n \n if(minheap.top() < arr[i+1] && i<n-1)\n minheap.pop();\n } \n }\n return ans;"
},
{
"code": null,
"e": 7557,
"s": 7411,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 7593,
"s": 7557,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7603,
"s": 7593,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7613,
"s": 7603,
"text": "\nContest\n"
},
{
"code": null,
"e": 7676,
"s": 7613,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7824,
"s": 7676,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 8032,
"s": 7824,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 8138,
"s": 8032,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Count number of elements in an array with MongoDB? | To count number of elements in an array, use the aggregate framework. Let us first create a collection with documents −
>db.countNumberOfElementsDemo.insertOne({"UserMessage":["Hi","Hello","Bye","Awesome"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cef8ec2ef71edecf6a1f6a1")
}
Display all documents from a collection with the help of find() method −
> db.countNumberOfElementsDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cef8ec2ef71edecf6a1f6a1"),
"UserMessage" : [
"Hi",
"Hello",
"Bye",
"Awesome"
]
}
Following is the query to count number of elements in an array −
> db.countNumberOfElementsDemo.aggregate({$project: { NumberOfElements: { $size:"$UserMessage" }}})
This will produce the following output −
{ "_id" : ObjectId("5cef8ec2ef71edecf6a1f6a1"), "NumberOfElements" : 4 } | [
{
"code": null,
"e": 1182,
"s": 1062,
"text": "To count number of elements in an array, use the aggregate framework. Let us first create a collection with documents −"
},
{
"code": null,
"e": 1356,
"s": 1182,
"text": ">db.countNumberOfElementsDemo.insertOne({\"UserMessage\":[\"Hi\",\"Hello\",\"Bye\",\"Awesome\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cef8ec2ef71edecf6a1f6a1\")\n}"
},
{
"code": null,
"e": 1429,
"s": 1356,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1477,
"s": 1429,
"text": "> db.countNumberOfElementsDemo.find().pretty();"
},
{
"code": null,
"e": 1518,
"s": 1477,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1653,
"s": 1518,
"text": "{\n \"_id\" : ObjectId(\"5cef8ec2ef71edecf6a1f6a1\"),\n \"UserMessage\" : [\n \"Hi\",\n \"Hello\",\n \"Bye\",\n \"Awesome\"\n ]\n}"
},
{
"code": null,
"e": 1718,
"s": 1653,
"text": "Following is the query to count number of elements in an array −"
},
{
"code": null,
"e": 1818,
"s": 1718,
"text": "> db.countNumberOfElementsDemo.aggregate({$project: { NumberOfElements: { $size:\"$UserMessage\" }}})"
},
{
"code": null,
"e": 1859,
"s": 1818,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1932,
"s": 1859,
"text": "{ \"_id\" : ObjectId(\"5cef8ec2ef71edecf6a1f6a1\"), \"NumberOfElements\" : 4 }"
}
] |
ExoPlayer in Android with Example - GeeksforGeeks | 15 Dec, 2021
ExoPlayerView is one of the most used UI components in many apps such as YouTube, Netflix, and many video streaming platforms. ExoPlayerView is used for audio as well as video streaming in Android apps. Many Google apps use ExoPlayerView for streaming audios and videos. ExoPlayer is a media player library that provides a way to play audio and video with lots of customization in it. It is an alternative that is used to play videos and audios in Android along with MediaPlayer. ExoPlayer is a library that is the best alternative source for playing audio and videos on Android. This library will also help you to customize your media player according to our requirements.
ExoPlayer provides the support for the playlist and with this, you can clip or merge your media.
With the help of ExoPlayer, you can directly fetch media files such as audios and videos directly from the internet and play them inside the ExoPlayer.
It provides smooth encryption and streaming of video and audio files.
ExoPlayer provides you the ability to customize your media player according to your requirements.
ExoPlayer
MediaPlayer
We will be creating a simple video player app in which we will be fetching a video from a URL and play that video inside our ExoPlayer. Note that we are using JAVA for implementing ExoPlayer in Android.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add dependency to the build.gradle(Module:app)
Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.
// dependency for exoplayer
implementation ‘com.google.android.exoplayer:exoplayer:r2.4.0’
// for core support in exoplayer.
implementation ‘com.google.android.exoplayer:exoplayer-core:r2.4.0’
// for adding dash support in our exoplayer.
implementation ‘com.google.android.exoplayer:exoplayer-dash:r2.4.0’
// for adding hls support in exoplayer.
implementation ‘com.google.android.exoplayer:exoplayer-hls:r2.4.0’
// for smooth streaming of video in our exoplayer.
implementation ‘com.google.android.exoplayer:exoplayer-smoothstreaming:r2.4.0’
// for generating default ui of exoplayer
implementation ‘com.google.android.exoplayer:exoplayer-ui:r2.4.0’
After adding this dependency sync the project.
Step 3: Add internet permission in your Manifest file
Navigate to the app > manifest folder and write down the following permissions to it.
<!–Internet permission and network access permission–>
<uses-permission android:name=”android.permission.INTERNET”/>
<uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE”/>
Step 4: Working with the activity_main.xml
Now we will start implementing our ExoPlayerView in our XML file. Navigate to the app > res > layout > activity_main.xml. Inside that file add the below code.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--Widget for exoplayer view--> <com.google.android.exoplayer2.ui.SimpleExoPlayerView android:id="@+id/idExoPlayerVIew" android:layout_width="match_parent" android:layout_height="500dp" /> </RelativeLayout>
Step 5: Working with the MainActivity.java file
Navigate to the app > java > your apps package name > MainActivity.java file. Inside that file add the below code. Comments are added inside the code to understand the code in more detail.
Java
import android.net.Uri;import android.os.Bundle;import android.util.Log; import androidx.appcompat.app.AppCompatActivity; import com.google.android.exoplayer2.ExoPlayerFactory;import com.google.android.exoplayer2.SimpleExoPlayer;import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;import com.google.android.exoplayer2.extractor.ExtractorsFactory;import com.google.android.exoplayer2.source.ExtractorMediaSource;import com.google.android.exoplayer2.source.MediaSource;import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;import com.google.android.exoplayer2.trackselection.TrackSelector;import com.google.android.exoplayer2.ui.SimpleExoPlayerView;import com.google.android.exoplayer2.upstream.BandwidthMeter;import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory; public class MainActivity extends AppCompatActivity { // creating a variable for exoplayerview. SimpleExoPlayerView exoPlayerView; // creating a variable for exoplayer SimpleExoPlayer exoPlayer; // url of video which we are loading. String videoURL = "https://media.geeksforgeeks.org/wp-content/uploads/20201217163353/Screenrecorder-2020-12-17-16-32-03-350.mp4"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); exoPlayerView = findViewById(R.id.idExoPlayerVIew); try { // bandwisthmeter is used for // getting default bandwidth BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter(); // track selector is used to navigate between // video using a default seekbar. TrackSelector trackSelector = new DefaultTrackSelector(new AdaptiveTrackSelection.Factory(bandwidthMeter)); // we are adding our track selector to exoplayer. exoPlayer = ExoPlayerFactory.newSimpleInstance(this, trackSelector); // we are parsing a video url // and parsing its video uri. Uri videouri = Uri.parse(videoURL); // we are creating a variable for datasource factory // and setting its user agent as 'exoplayer_view' DefaultHttpDataSourceFactory dataSourceFactory = new DefaultHttpDataSourceFactory("exoplayer_video"); // we are creating a variable for extractor factory // and setting it to default extractor factory. ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory(); // we are creating a media source with above variables // and passing our event handler as null, MediaSource mediaSource = new ExtractorMediaSource(videouri, dataSourceFactory, extractorsFactory, null, null); // inside our exoplayer view // we are setting our player exoPlayerView.setPlayer(exoPlayer); // we are preparing our exoplayer // with media source. exoPlayer.prepare(mediaSource); // we are setting our exoplayer // when it is ready. exoPlayer.setPlayWhenReady(true); } catch (Exception e) { // below line is used for // handling our errors. Log.e("TAG", "Error : " + e.toString()); } }}
Note: We have used this video in this project.
Check out the project: https://github.com/ChaitanyaMunje/QRCodeGenerator/tree/ExoPlayer
kalrap615
android
Android-View
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create and Add Data to SQLite Database in Android?
Broadcast Receiver in Android With Example
Resource Raw Folder in Android Studio
Android RecyclerView in Kotlin
CardView in Android With Example
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Stream In Java | [
{
"code": null,
"e": 26315,
"s": 26287,
"text": "\n15 Dec, 2021"
},
{
"code": null,
"e": 26990,
"s": 26315,
"text": "ExoPlayerView is one of the most used UI components in many apps such as YouTube, Netflix, and many video streaming platforms. ExoPlayerView is used for audio as well as video streaming in Android apps. Many Google apps use ExoPlayerView for streaming audios and videos. ExoPlayer is a media player library that provides a way to play audio and video with lots of customization in it. It is an alternative that is used to play videos and audios in Android along with MediaPlayer. ExoPlayer is a library that is the best alternative source for playing audio and videos on Android. This library will also help you to customize your media player according to our requirements. "
},
{
"code": null,
"e": 27087,
"s": 26990,
"text": "ExoPlayer provides the support for the playlist and with this, you can clip or merge your media."
},
{
"code": null,
"e": 27239,
"s": 27087,
"text": "With the help of ExoPlayer, you can directly fetch media files such as audios and videos directly from the internet and play them inside the ExoPlayer."
},
{
"code": null,
"e": 27309,
"s": 27239,
"text": "It provides smooth encryption and streaming of video and audio files."
},
{
"code": null,
"e": 27407,
"s": 27309,
"text": "ExoPlayer provides you the ability to customize your media player according to your requirements."
},
{
"code": null,
"e": 27417,
"s": 27407,
"text": "ExoPlayer"
},
{
"code": null,
"e": 27429,
"s": 27417,
"text": "MediaPlayer"
},
{
"code": null,
"e": 27633,
"s": 27429,
"text": "We will be creating a simple video player app in which we will be fetching a video from a URL and play that video inside our ExoPlayer. Note that we are using JAVA for implementing ExoPlayer in Android. "
},
{
"code": null,
"e": 27662,
"s": 27633,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 27824,
"s": 27662,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 27879,
"s": 27824,
"text": "Step 2: Add dependency to the build.gradle(Module:app)"
},
{
"code": null,
"e": 27996,
"s": 27879,
"text": "Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. "
},
{
"code": null,
"e": 28024,
"s": 27996,
"text": "// dependency for exoplayer"
},
{
"code": null,
"e": 28087,
"s": 28024,
"text": "implementation ‘com.google.android.exoplayer:exoplayer:r2.4.0’"
},
{
"code": null,
"e": 28121,
"s": 28087,
"text": "// for core support in exoplayer."
},
{
"code": null,
"e": 28189,
"s": 28121,
"text": "implementation ‘com.google.android.exoplayer:exoplayer-core:r2.4.0’"
},
{
"code": null,
"e": 28234,
"s": 28189,
"text": "// for adding dash support in our exoplayer."
},
{
"code": null,
"e": 28302,
"s": 28234,
"text": "implementation ‘com.google.android.exoplayer:exoplayer-dash:r2.4.0’"
},
{
"code": null,
"e": 28342,
"s": 28302,
"text": "// for adding hls support in exoplayer."
},
{
"code": null,
"e": 28409,
"s": 28342,
"text": "implementation ‘com.google.android.exoplayer:exoplayer-hls:r2.4.0’"
},
{
"code": null,
"e": 28460,
"s": 28409,
"text": "// for smooth streaming of video in our exoplayer."
},
{
"code": null,
"e": 28539,
"s": 28460,
"text": "implementation ‘com.google.android.exoplayer:exoplayer-smoothstreaming:r2.4.0’"
},
{
"code": null,
"e": 28581,
"s": 28539,
"text": "// for generating default ui of exoplayer"
},
{
"code": null,
"e": 28647,
"s": 28581,
"text": "implementation ‘com.google.android.exoplayer:exoplayer-ui:r2.4.0’"
},
{
"code": null,
"e": 28694,
"s": 28647,
"text": "After adding this dependency sync the project."
},
{
"code": null,
"e": 28748,
"s": 28694,
"text": "Step 3: Add internet permission in your Manifest file"
},
{
"code": null,
"e": 28835,
"s": 28748,
"text": "Navigate to the app > manifest folder and write down the following permissions to it. "
},
{
"code": null,
"e": 28890,
"s": 28835,
"text": "<!–Internet permission and network access permission–>"
},
{
"code": null,
"e": 28952,
"s": 28890,
"text": "<uses-permission android:name=”android.permission.INTERNET”/>"
},
{
"code": null,
"e": 29026,
"s": 28952,
"text": "<uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE”/>"
},
{
"code": null,
"e": 29069,
"s": 29026,
"text": "Step 4: Working with the activity_main.xml"
},
{
"code": null,
"e": 29228,
"s": 29069,
"text": "Now we will start implementing our ExoPlayerView in our XML file. Navigate to the app > res > layout > activity_main.xml. Inside that file add the below code."
},
{
"code": null,
"e": 29232,
"s": 29228,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--Widget for exoplayer view--> <com.google.android.exoplayer2.ui.SimpleExoPlayerView android:id=\"@+id/idExoPlayerVIew\" android:layout_width=\"match_parent\" android:layout_height=\"500dp\" /> </RelativeLayout>",
"e": 29754,
"s": 29232,
"text": null
},
{
"code": null,
"e": 29802,
"s": 29754,
"text": "Step 5: Working with the MainActivity.java file"
},
{
"code": null,
"e": 29991,
"s": 29802,
"text": "Navigate to the app > java > your apps package name > MainActivity.java file. Inside that file add the below code. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 29996,
"s": 29991,
"text": "Java"
},
{
"code": "import android.net.Uri;import android.os.Bundle;import android.util.Log; import androidx.appcompat.app.AppCompatActivity; import com.google.android.exoplayer2.ExoPlayerFactory;import com.google.android.exoplayer2.SimpleExoPlayer;import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;import com.google.android.exoplayer2.extractor.ExtractorsFactory;import com.google.android.exoplayer2.source.ExtractorMediaSource;import com.google.android.exoplayer2.source.MediaSource;import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;import com.google.android.exoplayer2.trackselection.TrackSelector;import com.google.android.exoplayer2.ui.SimpleExoPlayerView;import com.google.android.exoplayer2.upstream.BandwidthMeter;import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory; public class MainActivity extends AppCompatActivity { // creating a variable for exoplayerview. SimpleExoPlayerView exoPlayerView; // creating a variable for exoplayer SimpleExoPlayer exoPlayer; // url of video which we are loading. String videoURL = \"https://media.geeksforgeeks.org/wp-content/uploads/20201217163353/Screenrecorder-2020-12-17-16-32-03-350.mp4\"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); exoPlayerView = findViewById(R.id.idExoPlayerVIew); try { // bandwisthmeter is used for // getting default bandwidth BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter(); // track selector is used to navigate between // video using a default seekbar. TrackSelector trackSelector = new DefaultTrackSelector(new AdaptiveTrackSelection.Factory(bandwidthMeter)); // we are adding our track selector to exoplayer. exoPlayer = ExoPlayerFactory.newSimpleInstance(this, trackSelector); // we are parsing a video url // and parsing its video uri. Uri videouri = Uri.parse(videoURL); // we are creating a variable for datasource factory // and setting its user agent as 'exoplayer_view' DefaultHttpDataSourceFactory dataSourceFactory = new DefaultHttpDataSourceFactory(\"exoplayer_video\"); // we are creating a variable for extractor factory // and setting it to default extractor factory. ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory(); // we are creating a media source with above variables // and passing our event handler as null, MediaSource mediaSource = new ExtractorMediaSource(videouri, dataSourceFactory, extractorsFactory, null, null); // inside our exoplayer view // we are setting our player exoPlayerView.setPlayer(exoPlayer); // we are preparing our exoplayer // with media source. exoPlayer.prepare(mediaSource); // we are setting our exoplayer // when it is ready. exoPlayer.setPlayWhenReady(true); } catch (Exception e) { // below line is used for // handling our errors. Log.e(\"TAG\", \"Error : \" + e.toString()); } }}",
"e": 33615,
"s": 29996,
"text": null
},
{
"code": null,
"e": 33662,
"s": 33615,
"text": "Note: We have used this video in this project."
},
{
"code": null,
"e": 33750,
"s": 33662,
"text": "Check out the project: https://github.com/ChaitanyaMunje/QRCodeGenerator/tree/ExoPlayer"
},
{
"code": null,
"e": 33760,
"s": 33750,
"text": "kalrap615"
},
{
"code": null,
"e": 33768,
"s": 33760,
"text": "android"
},
{
"code": null,
"e": 33781,
"s": 33768,
"text": "Android-View"
},
{
"code": null,
"e": 33805,
"s": 33781,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 33813,
"s": 33805,
"text": "Android"
},
{
"code": null,
"e": 33818,
"s": 33813,
"text": "Java"
},
{
"code": null,
"e": 33837,
"s": 33818,
"text": "Technical Scripter"
},
{
"code": null,
"e": 33842,
"s": 33837,
"text": "Java"
},
{
"code": null,
"e": 33850,
"s": 33842,
"text": "Android"
},
{
"code": null,
"e": 33948,
"s": 33850,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34006,
"s": 33948,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 34049,
"s": 34006,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 34087,
"s": 34049,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 34118,
"s": 34087,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 34151,
"s": 34118,
"text": "CardView in Android With Example"
},
{
"code": null,
"e": 34166,
"s": 34151,
"text": "Arrays in Java"
},
{
"code": null,
"e": 34210,
"s": 34166,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 34232,
"s": 34210,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 34283,
"s": 34232,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
Best Time to Buy and Sell Stock with Cooldown in C++ | Suppose we have an array for which the ith element is the price of a given stock on the day i. We have to design an algorithm to find the maximum profit. We may complete as many transactions as we want (So, buy one and sell one share of the stock multiple times). But we have to follow these rules −
We may not engage in multiple transactions at the same time (So, we must sell the stock before you buy again).
After we sell our stock, we cannot buy stock on next day. (So cool down 1 day)
If the input is like [1,2,3,0,2], then the output will be 3, the sequence is like [buy, sell, cooldown, buy, sell]
To solve this, we will follow these steps −
endWithSell := 0, endWithBuy := -ve infinity, prevBuy := 0 and prevSell := 0
for i := 0 to size of the given arrayprevBuy := endWithBuyendWithBuy := max of endWithBuy and prevSell – Arr[i]prevSell := endWithSellendWithSell := max of endWithSell and prevBuy + Arr[i]
prevBuy := endWithBuy
endWithBuy := max of endWithBuy and prevSell – Arr[i]
prevSell := endWithSell
endWithSell := max of endWithSell and prevBuy + Arr[i]
return endWithSell
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int maxProfit(vector<int>& p) {
int endWithSell = 0;
int endWithBuy = INT_MIN;
int prevBuy =0, prevSell = 0;
for(int i =0;i<p.size();i++){
prevBuy = endWithBuy;
endWithBuy = max(endWithBuy,prevSell - p[i]);
prevSell = endWithSell;
endWithSell = max(endWithSell, prevBuy + p[i]);
}
return endWithSell;
}
};
main(){
Solution ob;
vector<int> v = {1,2,3,0,2};
cout << (ob.maxProfit(v));
}
[1,2,3,0,2]
3 | [
{
"code": null,
"e": 1362,
"s": 1062,
"text": "Suppose we have an array for which the ith element is the price of a given stock on the day i. We have to design an algorithm to find the maximum profit. We may complete as many transactions as we want (So, buy one and sell one share of the stock multiple times). But we have to follow these rules −"
},
{
"code": null,
"e": 1473,
"s": 1362,
"text": "We may not engage in multiple transactions at the same time (So, we must sell the stock before you buy again)."
},
{
"code": null,
"e": 1552,
"s": 1473,
"text": "After we sell our stock, we cannot buy stock on next day. (So cool down 1 day)"
},
{
"code": null,
"e": 1667,
"s": 1552,
"text": "If the input is like [1,2,3,0,2], then the output will be 3, the sequence is like [buy, sell, cooldown, buy, sell]"
},
{
"code": null,
"e": 1711,
"s": 1667,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1788,
"s": 1711,
"text": "endWithSell := 0, endWithBuy := -ve infinity, prevBuy := 0 and prevSell := 0"
},
{
"code": null,
"e": 1977,
"s": 1788,
"text": "for i := 0 to size of the given arrayprevBuy := endWithBuyendWithBuy := max of endWithBuy and prevSell – Arr[i]prevSell := endWithSellendWithSell := max of endWithSell and prevBuy + Arr[i]"
},
{
"code": null,
"e": 1999,
"s": 1977,
"text": "prevBuy := endWithBuy"
},
{
"code": null,
"e": 2053,
"s": 1999,
"text": "endWithBuy := max of endWithBuy and prevSell – Arr[i]"
},
{
"code": null,
"e": 2077,
"s": 2053,
"text": "prevSell := endWithSell"
},
{
"code": null,
"e": 2132,
"s": 2077,
"text": "endWithSell := max of endWithSell and prevBuy + Arr[i]"
},
{
"code": null,
"e": 2151,
"s": 2132,
"text": "return endWithSell"
},
{
"code": null,
"e": 2221,
"s": 2151,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2232,
"s": 2221,
"text": " Live Demo"
},
{
"code": null,
"e": 2778,
"s": 2232,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int maxProfit(vector<int>& p) {\n int endWithSell = 0;\n int endWithBuy = INT_MIN;\n int prevBuy =0, prevSell = 0;\n for(int i =0;i<p.size();i++){\n prevBuy = endWithBuy;\n endWithBuy = max(endWithBuy,prevSell - p[i]);\n prevSell = endWithSell;\n endWithSell = max(endWithSell, prevBuy + p[i]);\n }\n return endWithSell;\n }\n};\nmain(){\n Solution ob;\n vector<int> v = {1,2,3,0,2};\n cout << (ob.maxProfit(v));\n}"
},
{
"code": null,
"e": 2790,
"s": 2778,
"text": "[1,2,3,0,2]"
},
{
"code": null,
"e": 2792,
"s": 2790,
"text": "3"
}
] |
Convert a Singly Linked List to an array | 24 Mar, 2022
Given a singly linked list and the task is to convert it into an array.Examples:
Input: List = 1 -> 2 -> 3 -> 4 -> 5 -> NULL Output: 1 2 3 4 5Input: List = 10 -> 20 -> 30 -> 40 -> 50 -> NULL Output: 10 20 30 40 50
Approach: An approach to creating a linked list from the given array has been discussed in this article. Here, an approach to convert the given linked list to an array will be discussed.
Find the length of the given linked list say len.
Create an array of size len.
Traverse the given linked list and store the elements in the array one at a time.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <iostream>using namespace std; // Singly Linked List structurestruct node { int data; node* next;}; // Function to add a new node// to the Linked Listnode* add(int data){ node* newnode = new node; newnode->data = data; newnode->next = NULL; return newnode;} // Function to print the array contentsvoid printArr(int a[], int n){ for (int i = 0; i < n; i++) cout << a[i] << " ";} // Function to return the length// of the Linked Listint findlength(node* head){ node* curr = head; int cnt = 0; while (curr != NULL) { cnt++; curr = curr->next; } return cnt;} // Function to convert the// Linked List to an arrayvoid convertArr(node* head){ // Find the length of the // given linked list int len = findlength(head); // Create an array of the // required length int arr[len]; int index = 0; node* curr = head; // Traverse the Linked List and add the // elements to the array one by one while (curr != NULL) { arr[index++] = curr->data; curr = curr->next; } // Print the created array printArr(arr, len);} // Driver codeint main(){ node* head = NULL; head = add(1); head->next = add(2); head->next->next = add(3); head->next->next->next = add(4); head->next->next->next->next = add(5); convertArr(head); return 0;}
// Java implementation of the approachclass GFG{ // Singly Linked List structurestatic class node{ int data; node next;} // Function to add a new node// to the Linked Liststatic node add(int data){ node newnode = new node(); newnode.data = data; newnode.next = null; return newnode;} // Function to print the array contentsstatic void printArr(int a[], int n){ for (int i = 0; i < n; i++) System.out.print(a[i]+" ");} // Function to return the length// of the Linked Liststatic int findlength(node head){ node curr = head; int cnt = 0; while (curr != null) { cnt++; curr = curr.next; } return cnt;} // Function to convert the// Linked List to an arraystatic void convertArr(node head){ // Find the length of the // given linked list int len = findlength(head); // Create an array of the // required length int []arr = new int[len]; int index = 0; node curr = head; // Traverse the Linked List and add the // elements to the array one by one while (curr != null) { arr[index++] = curr.data; curr = curr.next; } // Print the created array printArr(arr, len);} // Driver codepublic static void main(String []args){ node head = new node(); head = add(1); head.next = add(2); head.next.next = add(3); head.next.next.next = add(4); head.next.next.next.next = add(5); convertArr(head);}} // This code is contributed by Rajput-Ji
# Python3 implementation of the approach # Structure of a Nodeclass node: def __init__(self, data): self.data = data self.next = None # Function to add a new node# to the Linked Listdef add(data): newnode = node(0) newnode.data = data newnode.next = None return newnode # Function to print the array contentsdef printArr(a, n): i = 0 while(i < n): print (a[i], end = " ") i = i + 1 # Function to return the length# of the Linked Listdef findlength( head): curr = head cnt = 0 while (curr != None): cnt = cnt + 1 curr = curr.next return cnt # Function to convert the# Linked List to an arraydef convertArr(head): # Find the length of the # given linked list len1 = findlength(head) # Create an array of the # required length arr = [] index = 0 curr = head # Traverse the Linked List and add the # elements to the array one by one while (curr != None): arr.append( curr.data) curr = curr.next # Print the created array printArr(arr, len1) # Driver codehead = node(0)head = add(1)head.next = add(2)head.next.next = add(3)head.next.next.next = add(4)head.next.next.next.next = add(5)convertArr(head) # This code is contributed by Arnab kundu
// C# implementation of the approachusing System; class GFG{ // Singly Linked List structurepublic class node{ public int data; public node next;} // Function to add a new node// to the Linked Liststatic node add(int data){ node newnode = new node(); newnode.data = data; newnode.next = null; return newnode;} // Function to print the array contentsstatic void printArr(int []a, int n){ for (int i = 0; i < n; i++) Console.Write(a[i] + " ");} // Function to return the length// of the Linked Liststatic int findlength(node head){ node curr = head; int cnt = 0; while (curr != null) { cnt++; curr = curr.next; } return cnt;} // Function to convert the// Linked List to an arraystatic void convertArr(node head){ // Find the length of the // given linked list int len = findlength(head); // Create an array of the // required length int []arr = new int[len]; int index = 0; node curr = head; // Traverse the Linked List and add the // elements to the array one by one while (curr != null) { arr[index++] = curr.data; curr = curr.next; } // Print the created array printArr(arr, len);} // Driver codepublic static void Main(String []args){ node head = new node(); head = add(1); head.next = add(2); head.next.next = add(3); head.next.next.next = add(4); head.next.next.next.next = add(5); convertArr(head);}} // This code is contributed by 29AjayKumar
<script> // JavaScript implementation of the approach // Singly Linked List structureclass node { constructor() { this.data = 0; this.next = null; } } // Function to add a new node// to the Linked Listfunction add( data){ var newnode = new node(); newnode.data = data; newnode.next = null; return newnode;} // Function to print the array contentsfunction printArr( a, n){ for (let i = 0; i < n; i++) document.write(a[i]+" ");} // Function to return the length// of the Linked Listfunction findlength( head){ var curr = head; let cnt = 0; while (curr != null) { cnt++; curr = curr.next; } return cnt;} // Function to convert the// Linked List to an arrayfunction convertArr( head){ // Find the length of the // given linked list let len = findlength(head); // Create an array of the // required length let arr = new Array(len); let index = 0; var curr = head; // Traverse the Linked List and add the // elements to the array one by one while (curr != null) { arr[index++] = curr.data; curr = curr.next; } // Print the created array printArr(arr, len);} // Driver Code var head = new node();head = add(1);head.next = add(2);head.next.next = add(3);head.next.next.next = add(4);head.next.next.next.next = add(5); convertArr(head); </script>
1 2 3 4 5
Time Complexity: O(N)Auxiliary Space: O(N)
Rajput-Ji
29AjayKumar
andrew1234
jana_sayantan
pankajsharmagfg
surinderdawra388
Algorithms
Arrays
Linked List
Technical Scripter
Linked List
Arrays
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Hashing | A Complete Tutorial
Find if there is a path between two vertices in an undirected graph
How to Start Learning DSA?
Complete Roadmap To Learn DSA From Scratch
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Arrays in Java
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Largest Sum Contiguous Subarray
Arrays in C/C++ | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Mar, 2022"
},
{
"code": null,
"e": 135,
"s": 52,
"text": "Given a singly linked list and the task is to convert it into an array.Examples: "
},
{
"code": null,
"e": 270,
"s": 135,
"text": "Input: List = 1 -> 2 -> 3 -> 4 -> 5 -> NULL Output: 1 2 3 4 5Input: List = 10 -> 20 -> 30 -> 40 -> 50 -> NULL Output: 10 20 30 40 50 "
},
{
"code": null,
"e": 461,
"s": 272,
"text": "Approach: An approach to creating a linked list from the given array has been discussed in this article. Here, an approach to convert the given linked list to an array will be discussed. "
},
{
"code": null,
"e": 511,
"s": 461,
"text": "Find the length of the given linked list say len."
},
{
"code": null,
"e": 540,
"s": 511,
"text": "Create an array of size len."
},
{
"code": null,
"e": 622,
"s": 540,
"text": "Traverse the given linked list and store the elements in the array one at a time."
},
{
"code": null,
"e": 675,
"s": 622,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 679,
"s": 675,
"text": "C++"
},
{
"code": null,
"e": 684,
"s": 679,
"text": "Java"
},
{
"code": null,
"e": 692,
"s": 684,
"text": "Python3"
},
{
"code": null,
"e": 695,
"s": 692,
"text": "C#"
},
{
"code": null,
"e": 706,
"s": 695,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <iostream>using namespace std; // Singly Linked List structurestruct node { int data; node* next;}; // Function to add a new node// to the Linked Listnode* add(int data){ node* newnode = new node; newnode->data = data; newnode->next = NULL; return newnode;} // Function to print the array contentsvoid printArr(int a[], int n){ for (int i = 0; i < n; i++) cout << a[i] << \" \";} // Function to return the length// of the Linked Listint findlength(node* head){ node* curr = head; int cnt = 0; while (curr != NULL) { cnt++; curr = curr->next; } return cnt;} // Function to convert the// Linked List to an arrayvoid convertArr(node* head){ // Find the length of the // given linked list int len = findlength(head); // Create an array of the // required length int arr[len]; int index = 0; node* curr = head; // Traverse the Linked List and add the // elements to the array one by one while (curr != NULL) { arr[index++] = curr->data; curr = curr->next; } // Print the created array printArr(arr, len);} // Driver codeint main(){ node* head = NULL; head = add(1); head->next = add(2); head->next->next = add(3); head->next->next->next = add(4); head->next->next->next->next = add(5); convertArr(head); return 0;}",
"e": 2104,
"s": 706,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Singly Linked List structurestatic class node{ int data; node next;} // Function to add a new node// to the Linked Liststatic node add(int data){ node newnode = new node(); newnode.data = data; newnode.next = null; return newnode;} // Function to print the array contentsstatic void printArr(int a[], int n){ for (int i = 0; i < n; i++) System.out.print(a[i]+\" \");} // Function to return the length// of the Linked Liststatic int findlength(node head){ node curr = head; int cnt = 0; while (curr != null) { cnt++; curr = curr.next; } return cnt;} // Function to convert the// Linked List to an arraystatic void convertArr(node head){ // Find the length of the // given linked list int len = findlength(head); // Create an array of the // required length int []arr = new int[len]; int index = 0; node curr = head; // Traverse the Linked List and add the // elements to the array one by one while (curr != null) { arr[index++] = curr.data; curr = curr.next; } // Print the created array printArr(arr, len);} // Driver codepublic static void main(String []args){ node head = new node(); head = add(1); head.next = add(2); head.next.next = add(3); head.next.next.next = add(4); head.next.next.next.next = add(5); convertArr(head);}} // This code is contributed by Rajput-Ji",
"e": 3572,
"s": 2104,
"text": null
},
{
"code": "# Python3 implementation of the approach # Structure of a Nodeclass node: def __init__(self, data): self.data = data self.next = None # Function to add a new node# to the Linked Listdef add(data): newnode = node(0) newnode.data = data newnode.next = None return newnode # Function to print the array contentsdef printArr(a, n): i = 0 while(i < n): print (a[i], end = \" \") i = i + 1 # Function to return the length# of the Linked Listdef findlength( head): curr = head cnt = 0 while (curr != None): cnt = cnt + 1 curr = curr.next return cnt # Function to convert the# Linked List to an arraydef convertArr(head): # Find the length of the # given linked list len1 = findlength(head) # Create an array of the # required length arr = [] index = 0 curr = head # Traverse the Linked List and add the # elements to the array one by one while (curr != None): arr.append( curr.data) curr = curr.next # Print the created array printArr(arr, len1) # Driver codehead = node(0)head = add(1)head.next = add(2)head.next.next = add(3)head.next.next.next = add(4)head.next.next.next.next = add(5)convertArr(head) # This code is contributed by Arnab kundu",
"e": 4860,
"s": 3572,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Singly Linked List structurepublic class node{ public int data; public node next;} // Function to add a new node// to the Linked Liststatic node add(int data){ node newnode = new node(); newnode.data = data; newnode.next = null; return newnode;} // Function to print the array contentsstatic void printArr(int []a, int n){ for (int i = 0; i < n; i++) Console.Write(a[i] + \" \");} // Function to return the length// of the Linked Liststatic int findlength(node head){ node curr = head; int cnt = 0; while (curr != null) { cnt++; curr = curr.next; } return cnt;} // Function to convert the// Linked List to an arraystatic void convertArr(node head){ // Find the length of the // given linked list int len = findlength(head); // Create an array of the // required length int []arr = new int[len]; int index = 0; node curr = head; // Traverse the Linked List and add the // elements to the array one by one while (curr != null) { arr[index++] = curr.data; curr = curr.next; } // Print the created array printArr(arr, len);} // Driver codepublic static void Main(String []args){ node head = new node(); head = add(1); head.next = add(2); head.next.next = add(3); head.next.next.next = add(4); head.next.next.next.next = add(5); convertArr(head);}} // This code is contributed by 29AjayKumar",
"e": 6375,
"s": 4860,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Singly Linked List structureclass node { constructor() { this.data = 0; this.next = null; } } // Function to add a new node// to the Linked Listfunction add( data){ var newnode = new node(); newnode.data = data; newnode.next = null; return newnode;} // Function to print the array contentsfunction printArr( a, n){ for (let i = 0; i < n; i++) document.write(a[i]+\" \");} // Function to return the length// of the Linked Listfunction findlength( head){ var curr = head; let cnt = 0; while (curr != null) { cnt++; curr = curr.next; } return cnt;} // Function to convert the// Linked List to an arrayfunction convertArr( head){ // Find the length of the // given linked list let len = findlength(head); // Create an array of the // required length let arr = new Array(len); let index = 0; var curr = head; // Traverse the Linked List and add the // elements to the array one by one while (curr != null) { arr[index++] = curr.data; curr = curr.next; } // Print the created array printArr(arr, len);} // Driver Code var head = new node();head = add(1);head.next = add(2);head.next.next = add(3);head.next.next.next = add(4);head.next.next.next.next = add(5); convertArr(head); </script>",
"e": 7804,
"s": 6375,
"text": null
},
{
"code": null,
"e": 7814,
"s": 7804,
"text": "1 2 3 4 5"
},
{
"code": null,
"e": 7859,
"s": 7816,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 7869,
"s": 7859,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 7881,
"s": 7869,
"text": "29AjayKumar"
},
{
"code": null,
"e": 7892,
"s": 7881,
"text": "andrew1234"
},
{
"code": null,
"e": 7906,
"s": 7892,
"text": "jana_sayantan"
},
{
"code": null,
"e": 7922,
"s": 7906,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 7939,
"s": 7922,
"text": "surinderdawra388"
},
{
"code": null,
"e": 7950,
"s": 7939,
"text": "Algorithms"
},
{
"code": null,
"e": 7957,
"s": 7950,
"text": "Arrays"
},
{
"code": null,
"e": 7969,
"s": 7957,
"text": "Linked List"
},
{
"code": null,
"e": 7988,
"s": 7969,
"text": "Technical Scripter"
},
{
"code": null,
"e": 8000,
"s": 7988,
"text": "Linked List"
},
{
"code": null,
"e": 8007,
"s": 8000,
"text": "Arrays"
},
{
"code": null,
"e": 8018,
"s": 8007,
"text": "Algorithms"
},
{
"code": null,
"e": 8116,
"s": 8018,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8154,
"s": 8116,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 8222,
"s": 8154,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 8249,
"s": 8222,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 8292,
"s": 8249,
"text": "Complete Roadmap To Learn DSA From Scratch"
},
{
"code": null,
"e": 8359,
"s": 8292,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 8374,
"s": 8359,
"text": "Arrays in Java"
},
{
"code": null,
"e": 8420,
"s": 8374,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 8488,
"s": 8420,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 8520,
"s": 8488,
"text": "Largest Sum Contiguous Subarray"
}
] |
Python | Vkeyboard (virtual keyboard) in kivy | 05 Sep, 2019
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.
VKeyboard is an onscreen keyboard for Kivy. Its operation is intended to be transparent to the user. Using the widget directly is NOT recommended. Read the section Request keyboard first.
Modes in Vkeyboard:
This virtual keyboard has a docked and free mode:
Docked mode: (VKeyboard.docked = True) Generally used when only one person is using the computer, like a tablet or personal computer etc.
Free mode: (VKeyboard.docked = False) Mostly for multitouch surfaces. This mode allows multiple virtual keyboards to be used on the screen.
If the docked mode changes, you need to manually call VKeyboard.setup_mode() otherwise, the change will have no impact.
During that call, the VKeyboard, implemented on top of a Scatter, will change the behavior of the scatter and position the keyboard near the target (if target and docked mode are set).
Basic Approach:
1) import kivy
2) import kivyApp
3) import vkeyboard
4) set kivy version (optional)
5) Create the Vkeyboard class
6) Create the App class
7) return the vkeyboard class
8) Run the App
# Implementation of the Approach:
# import kivy module import kivy # this restricts the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require("1.9.1") # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # VKeyboard is an onscreen keyboard# for Kivy. Its operation is intended# to be transparent to the user. from kivy.uix.vkeyboard import VKeyboard # Create the vkeyboardclass Test(VKeyboard): player = VKeyboard() # Create the App classclass VkeyboardApp(App): def build(self): return Test() # run the Appif __name__ == '__main__': VkeyboardApp().run()
Output:
Python-gui
Python-kivy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Sep, 2019"
},
{
"code": null,
"e": 288,
"s": 52,
"text": "Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications."
},
{
"code": null,
"e": 476,
"s": 288,
"text": "VKeyboard is an onscreen keyboard for Kivy. Its operation is intended to be transparent to the user. Using the widget directly is NOT recommended. Read the section Request keyboard first."
},
{
"code": null,
"e": 496,
"s": 476,
"text": "Modes in Vkeyboard:"
},
{
"code": null,
"e": 546,
"s": 496,
"text": "This virtual keyboard has a docked and free mode:"
},
{
"code": null,
"e": 684,
"s": 546,
"text": "Docked mode: (VKeyboard.docked = True) Generally used when only one person is using the computer, like a tablet or personal computer etc."
},
{
"code": null,
"e": 824,
"s": 684,
"text": "Free mode: (VKeyboard.docked = False) Mostly for multitouch surfaces. This mode allows multiple virtual keyboards to be used on the screen."
},
{
"code": null,
"e": 944,
"s": 824,
"text": "If the docked mode changes, you need to manually call VKeyboard.setup_mode() otherwise, the change will have no impact."
},
{
"code": null,
"e": 1129,
"s": 944,
"text": "During that call, the VKeyboard, implemented on top of a Scatter, will change the behavior of the scatter and position the keyboard near the target (if target and docked mode are set)."
},
{
"code": null,
"e": 1329,
"s": 1129,
"text": "Basic Approach:\n1) import kivy\n2) import kivyApp\n3) import vkeyboard\n4) set kivy version (optional)\n5) Create the Vkeyboard class\n6) Create the App class\n7) return the vkeyboard class\n8) Run the App\n"
},
{
"code": null,
"e": 1363,
"s": 1329,
"text": "# Implementation of the Approach:"
},
{
"code": "# import kivy module import kivy # this restricts the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require(\"1.9.1\") # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # VKeyboard is an onscreen keyboard# for Kivy. Its operation is intended# to be transparent to the user. from kivy.uix.vkeyboard import VKeyboard # Create the vkeyboardclass Test(VKeyboard): player = VKeyboard() # Create the App classclass VkeyboardApp(App): def build(self): return Test() # run the Appif __name__ == '__main__': VkeyboardApp().run()",
"e": 2045,
"s": 1363,
"text": null
},
{
"code": null,
"e": 2053,
"s": 2045,
"text": "Output:"
},
{
"code": null,
"e": 2064,
"s": 2053,
"text": "Python-gui"
},
{
"code": null,
"e": 2076,
"s": 2064,
"text": "Python-kivy"
},
{
"code": null,
"e": 2083,
"s": 2076,
"text": "Python"
}
] |
Python | Split the Even and Odd elements into two different lists | 19 Apr, 2020
In this program, a list is accepted with the mixture of odd and even elements and based on whether the element is even or odd, it is split into two different lists.
Examples:
Input : [8, 12, 15, 9, 3, 11, 26, 23]
Output : Even lists: [8, 12, 26]
Odd lists: [15, 9, 3, 11, 23]
Input : [2, 5, 13, 17, 51, 62, 73, 84, 95]
Output : Even lists: [2, 62, 84]
Odd lists: [5, 13, 17, 51, 73, 95]
# Python code to split into even and odd lists# Function to splitdef Split(mix): ev_li = [] od_li = [] for i in mix: if (i % 2 == 0): ev_li.append(i) else: od_li.append(i) print("Even lists:", ev_li) print("Odd lists:", od_li) # Driver Codemix = [2, 5, 13, 17, 51, 62, 73, 84, 95]Split(mix)
Output:
Even lists: [2, 62, 84]
Odd lists: [5, 13, 17, 51, 73, 95]
Alternate Shorter Solution :
def Split(mix): ev_li = [ele for ele in li_in if ele%2 ==0] od_li = [ele for ele in li_in if ele%2 !=0] print("Even lists:", ev_li) print("Odd lists:", od_li) # Driver Codemix = [2, 5, 13, 17, 51, 62, 73, 84, 95]Split(mix)
Output:
Even lists: [2, 62, 84]
Odd lists: [5, 13, 17, 51, 73, 95]
shubham_singh
zwwingfan
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Apr, 2020"
},
{
"code": null,
"e": 193,
"s": 28,
"text": "In this program, a list is accepted with the mixture of odd and even elements and based on whether the element is even or odd, it is split into two different lists."
},
{
"code": null,
"e": 203,
"s": 193,
"text": "Examples:"
},
{
"code": null,
"e": 436,
"s": 203,
"text": "Input : [8, 12, 15, 9, 3, 11, 26, 23]\nOutput : Even lists: [8, 12, 26]\n Odd lists: [15, 9, 3, 11, 23]\n\n\nInput : [2, 5, 13, 17, 51, 62, 73, 84, 95]\nOutput : Even lists: [2, 62, 84]\n Odd lists: [5, 13, 17, 51, 73, 95]\n"
},
{
"code": "# Python code to split into even and odd lists# Function to splitdef Split(mix): ev_li = [] od_li = [] for i in mix: if (i % 2 == 0): ev_li.append(i) else: od_li.append(i) print(\"Even lists:\", ev_li) print(\"Odd lists:\", od_li) # Driver Codemix = [2, 5, 13, 17, 51, 62, 73, 84, 95]Split(mix)",
"e": 779,
"s": 436,
"text": null
},
{
"code": null,
"e": 787,
"s": 779,
"text": "Output:"
},
{
"code": null,
"e": 847,
"s": 787,
"text": "Even lists: [2, 62, 84]\nOdd lists: [5, 13, 17, 51, 73, 95]\n"
},
{
"code": null,
"e": 876,
"s": 847,
"text": "Alternate Shorter Solution :"
},
{
"code": "def Split(mix): ev_li = [ele for ele in li_in if ele%2 ==0] od_li = [ele for ele in li_in if ele%2 !=0] print(\"Even lists:\", ev_li) print(\"Odd lists:\", od_li) # Driver Codemix = [2, 5, 13, 17, 51, 62, 73, 84, 95]Split(mix)",
"e": 1112,
"s": 876,
"text": null
},
{
"code": null,
"e": 1120,
"s": 1112,
"text": "Output:"
},
{
"code": null,
"e": 1180,
"s": 1120,
"text": "Even lists: [2, 62, 84]\nOdd lists: [5, 13, 17, 51, 73, 95]\n"
},
{
"code": null,
"e": 1194,
"s": 1180,
"text": "shubham_singh"
},
{
"code": null,
"e": 1204,
"s": 1194,
"text": "zwwingfan"
},
{
"code": null,
"e": 1225,
"s": 1204,
"text": "Python list-programs"
},
{
"code": null,
"e": 1237,
"s": 1225,
"text": "python-list"
},
{
"code": null,
"e": 1244,
"s": 1237,
"text": "Python"
},
{
"code": null,
"e": 1256,
"s": 1244,
"text": "python-list"
}
] |
Setting up Google Cloud SQL with Flask | 16 Jan, 2022
Setting up a database can be very tricky, yet some pretty simple and scalable solutions are available and one such solution is Google Cloud SQL. Cloud SQL is a fully-managed database service that makes it easy to set up, maintain, and administer your relational PostgreSQL and MySQL databases in the cloud. Setting it up can be both tricky and simple, confused? I am here to clear the confusion.
First of all, you need a Google Cloud Platform (GCP) account. If you don’t want one, then create an account by going to this link here. You will also get $300 free credits for one year when you signup. You also need to set up your billing account to be able to use some of the GCP services which include Cloud SQL. Don’t worry you won’t get charged for this tutorial if you have free credits.
Now, you need to enable Cloud SQL Admin API from the marketplace. You can do that by click on this link here.Now, let’s jump into our GCP dashboard and then search for Cloud SQL. Your CLoud SQL page should look something like this.
Now, click on CREATE INSTANCE and then for this tutorial we would be selecting the MySQL option. Now, you should be greeted with the following page.
Now, fill up the details. It is always advised to generate the password because it creates a random string and note the password because you can not retrieve it if you forget it and also change the region to your nearest one geographically and then click on create. That’s all. Now, the next page should look something like this.
Now, you first need to create a database. To do that simply, click on the Databases option on the navigation bar at the left and then click on Create database and then provide the name of your database. For this tutorial, our database name will be testing. After you have done that, you should see your database listed there. That all for the setup part. Now let’s actually see how can connect to this database from your flask app.
Obviously, you will be needing Python. In this tutorial, we are currently on the latest python version that is 3.8You also need to install flask, flask-sqlalchemy and mysqlclient. To install those, simply run the following command in your terminal.
pip3 install Flask Flask-SQLAlchemy mysqlclient
Note: If you are on a Linux machine, then your need to have libmysqlclient-dev installed before you install mysqlclient. To install it simply run sudo apt-get install libmysqlclient-dev in your terminal.
With all your pre-requisites done, let’s actually jump right into the code. For simplicity purposes, I will be writing all the code in a single file but as you know, if you are planning on building a mid-size application even, then you need to have separate files for routes, models, etc.Here, the entire code will be written inside a single file called app.py. I have added explanations for every line in my code in the form of inline comments.
Python3
# importsfrom flask import Flask, request, make_responsefrom flask_sqlalchemy import SQLAlchemy # initializing Flask appapp = Flask(__name__) # Google Cloud SQL (change this accordingly)PASSWORD ="your database password"PUBLIC_IP_ADDRESS ="public ip of database"DBNAME ="database name"PROJECT_ID ="gcp project id"INSTANCE_NAME ="instance name" # configurationapp.config["SECRET_KEY"] = "yoursecretkey"app.config["SQLALCHEMY_DATABASE_URI"]= f"mysql + mysqldb://root:{PASSWORD}@{PUBLIC_IP_ADDRESS}/{DBNAME}?unix_socket =/cloudsql/{PROJECT_ID}:{INSTANCE_NAME}"app.config["SQLALCHEMY_TRACK_MODIFICATIONS"]= True db = SQLAlchemy(app) # User ORM for SQLAlchemyclass Users(db.Model): id = db.Column(db.Integer, primary_key = True, nullable = False) name = db.Column(db.String(50), nullable = False) email = db.Column(db.String(50), nullable = False, unique = True) @app.route('/add', methods =['POST'])def add(): # getting name and email name = request.form.get('name') email = request.form.get('email') # checking if user already exists user = Users.query.filter_by(email = email).first() if not user: try: # creating Users object user = Users( name = name, email = email ) # adding the fields to users table db.session.add(user) db.session.commit() # response responseObject = { 'status' : 'success', 'message': 'Successfully registered.' } return make_response(responseObject, 200) except: responseObject = { 'status' : 'fail', 'message': 'Some error occured !!' } return make_response(responseObject, 400) else: # if user already exists then send status as fail responseObject = { 'status' : 'fail', 'message': 'User already exists !!' } return make_response(responseObject, 403) @app.route('/view')def view(): # fetches all the users users = Users.query.all() # response list consisting user details response = list() for user in users: response.append({ "name" : user.name, "email": user.email }) return make_response({ 'status' : 'success', 'message': response }, 200) if __name__ == "__main__": # serving the app directly app.run()
You need to change the following placeholders in the code
PASSWORD: the password you set for your database while creating the instance
PUBLIC_IP_ADDRESS: your GCP instances public IP (can be found in the overview page)
DBNAME: name of the database that you created later on (for this tutorial it was ‘testing’)
PROJECT_ID: your GCP project ID
INSTANCE_NAME: you Cloud SQL instance name
Your code is ready but it still can’t access your database. This is where most people get it wrong. They keep on checking the documentations and their codebase but they find no mistake and they get completely frustrated and give up, but I hope you are not the one to give up, right? So, let us see what is left to be done.
The reason why your database isn’t accessible by your code is that GCP by default blocks all incoming connections from unknown sources (for security purposes). So, what you need to do right now, is to add your systems public IP address to the Authorised Network. To do that, first, go to your Cloud SQL instance page and click on the edit button. You should see a page like this
Here, click on the Add network button under public IP. There, you need to enter your Public IP address. If you don’t know your Public IP then go to this link. After you have entered your Public IP, you are good to go.Now, your app should be able to connect to your database from your system. Now, open up your terminal inside your project directory and type python inside it. This should open up the python interpreter. Now, simply type the following lines in it to create your table from the ORM.
Python3
from app import dbdb.create_all()
That’s all. Now you are ready to test out your app. Go ahead and using any API request tool to check if it works or not. You can use the famous Postman to test it out.The ability to host your database on an external service is very crucial for student developers, otherwise, it is impossible to showcase your projects.
ruhelaa48
akshaysingh98088
sweetyty
saurabh1990aror
mysql
Python Flask
Python
SQL
Web Technologies
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
SQL | DDL, DQL, DML, DCL and TCL Commands
SQL | Join (Inner, Left, Right and Full Joins)
SQL | WITH clause
How to find Nth highest salary from a table
CTE in SQL | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Jan, 2022"
},
{
"code": null,
"e": 424,
"s": 28,
"text": "Setting up a database can be very tricky, yet some pretty simple and scalable solutions are available and one such solution is Google Cloud SQL. Cloud SQL is a fully-managed database service that makes it easy to set up, maintain, and administer your relational PostgreSQL and MySQL databases in the cloud. Setting it up can be both tricky and simple, confused? I am here to clear the confusion."
},
{
"code": null,
"e": 817,
"s": 424,
"text": "First of all, you need a Google Cloud Platform (GCP) account. If you don’t want one, then create an account by going to this link here. You will also get $300 free credits for one year when you signup. You also need to set up your billing account to be able to use some of the GCP services which include Cloud SQL. Don’t worry you won’t get charged for this tutorial if you have free credits."
},
{
"code": null,
"e": 1049,
"s": 817,
"text": "Now, you need to enable Cloud SQL Admin API from the marketplace. You can do that by click on this link here.Now, let’s jump into our GCP dashboard and then search for Cloud SQL. Your CLoud SQL page should look something like this."
},
{
"code": null,
"e": 1198,
"s": 1049,
"text": "Now, click on CREATE INSTANCE and then for this tutorial we would be selecting the MySQL option. Now, you should be greeted with the following page."
},
{
"code": null,
"e": 1528,
"s": 1198,
"text": "Now, fill up the details. It is always advised to generate the password because it creates a random string and note the password because you can not retrieve it if you forget it and also change the region to your nearest one geographically and then click on create. That’s all. Now, the next page should look something like this."
},
{
"code": null,
"e": 1960,
"s": 1528,
"text": "Now, you first need to create a database. To do that simply, click on the Databases option on the navigation bar at the left and then click on Create database and then provide the name of your database. For this tutorial, our database name will be testing. After you have done that, you should see your database listed there. That all for the setup part. Now let’s actually see how can connect to this database from your flask app."
},
{
"code": null,
"e": 2209,
"s": 1960,
"text": "Obviously, you will be needing Python. In this tutorial, we are currently on the latest python version that is 3.8You also need to install flask, flask-sqlalchemy and mysqlclient. To install those, simply run the following command in your terminal."
},
{
"code": null,
"e": 2257,
"s": 2209,
"text": "pip3 install Flask Flask-SQLAlchemy mysqlclient"
},
{
"code": null,
"e": 2461,
"s": 2257,
"text": "Note: If you are on a Linux machine, then your need to have libmysqlclient-dev installed before you install mysqlclient. To install it simply run sudo apt-get install libmysqlclient-dev in your terminal."
},
{
"code": null,
"e": 2907,
"s": 2461,
"text": "With all your pre-requisites done, let’s actually jump right into the code. For simplicity purposes, I will be writing all the code in a single file but as you know, if you are planning on building a mid-size application even, then you need to have separate files for routes, models, etc.Here, the entire code will be written inside a single file called app.py. I have added explanations for every line in my code in the form of inline comments."
},
{
"code": null,
"e": 2915,
"s": 2907,
"text": "Python3"
},
{
"code": "# importsfrom flask import Flask, request, make_responsefrom flask_sqlalchemy import SQLAlchemy # initializing Flask appapp = Flask(__name__) # Google Cloud SQL (change this accordingly)PASSWORD =\"your database password\"PUBLIC_IP_ADDRESS =\"public ip of database\"DBNAME =\"database name\"PROJECT_ID =\"gcp project id\"INSTANCE_NAME =\"instance name\" # configurationapp.config[\"SECRET_KEY\"] = \"yoursecretkey\"app.config[\"SQLALCHEMY_DATABASE_URI\"]= f\"mysql + mysqldb://root:{PASSWORD}@{PUBLIC_IP_ADDRESS}/{DBNAME}?unix_socket =/cloudsql/{PROJECT_ID}:{INSTANCE_NAME}\"app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"]= True db = SQLAlchemy(app) # User ORM for SQLAlchemyclass Users(db.Model): id = db.Column(db.Integer, primary_key = True, nullable = False) name = db.Column(db.String(50), nullable = False) email = db.Column(db.String(50), nullable = False, unique = True) @app.route('/add', methods =['POST'])def add(): # getting name and email name = request.form.get('name') email = request.form.get('email') # checking if user already exists user = Users.query.filter_by(email = email).first() if not user: try: # creating Users object user = Users( name = name, email = email ) # adding the fields to users table db.session.add(user) db.session.commit() # response responseObject = { 'status' : 'success', 'message': 'Successfully registered.' } return make_response(responseObject, 200) except: responseObject = { 'status' : 'fail', 'message': 'Some error occured !!' } return make_response(responseObject, 400) else: # if user already exists then send status as fail responseObject = { 'status' : 'fail', 'message': 'User already exists !!' } return make_response(responseObject, 403) @app.route('/view')def view(): # fetches all the users users = Users.query.all() # response list consisting user details response = list() for user in users: response.append({ \"name\" : user.name, \"email\": user.email }) return make_response({ 'status' : 'success', 'message': response }, 200) if __name__ == \"__main__\": # serving the app directly app.run()",
"e": 5369,
"s": 2915,
"text": null
},
{
"code": null,
"e": 5428,
"s": 5369,
"text": "You need to change the following placeholders in the code "
},
{
"code": null,
"e": 5505,
"s": 5428,
"text": "PASSWORD: the password you set for your database while creating the instance"
},
{
"code": null,
"e": 5589,
"s": 5505,
"text": "PUBLIC_IP_ADDRESS: your GCP instances public IP (can be found in the overview page)"
},
{
"code": null,
"e": 5681,
"s": 5589,
"text": "DBNAME: name of the database that you created later on (for this tutorial it was ‘testing’)"
},
{
"code": null,
"e": 5713,
"s": 5681,
"text": "PROJECT_ID: your GCP project ID"
},
{
"code": null,
"e": 5756,
"s": 5713,
"text": "INSTANCE_NAME: you Cloud SQL instance name"
},
{
"code": null,
"e": 6079,
"s": 5756,
"text": "Your code is ready but it still can’t access your database. This is where most people get it wrong. They keep on checking the documentations and their codebase but they find no mistake and they get completely frustrated and give up, but I hope you are not the one to give up, right? So, let us see what is left to be done."
},
{
"code": null,
"e": 6458,
"s": 6079,
"text": "The reason why your database isn’t accessible by your code is that GCP by default blocks all incoming connections from unknown sources (for security purposes). So, what you need to do right now, is to add your systems public IP address to the Authorised Network. To do that, first, go to your Cloud SQL instance page and click on the edit button. You should see a page like this"
},
{
"code": null,
"e": 6956,
"s": 6458,
"text": "Here, click on the Add network button under public IP. There, you need to enter your Public IP address. If you don’t know your Public IP then go to this link. After you have entered your Public IP, you are good to go.Now, your app should be able to connect to your database from your system. Now, open up your terminal inside your project directory and type python inside it. This should open up the python interpreter. Now, simply type the following lines in it to create your table from the ORM."
},
{
"code": null,
"e": 6964,
"s": 6956,
"text": "Python3"
},
{
"code": "from app import dbdb.create_all()",
"e": 6998,
"s": 6964,
"text": null
},
{
"code": null,
"e": 7318,
"s": 6998,
"text": "That’s all. Now you are ready to test out your app. Go ahead and using any API request tool to check if it works or not. You can use the famous Postman to test it out.The ability to host your database on an external service is very crucial for student developers, otherwise, it is impossible to showcase your projects. "
},
{
"code": null,
"e": 7328,
"s": 7318,
"text": "ruhelaa48"
},
{
"code": null,
"e": 7345,
"s": 7328,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 7354,
"s": 7345,
"text": "sweetyty"
},
{
"code": null,
"e": 7370,
"s": 7354,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 7376,
"s": 7370,
"text": "mysql"
},
{
"code": null,
"e": 7389,
"s": 7376,
"text": "Python Flask"
},
{
"code": null,
"e": 7396,
"s": 7389,
"text": "Python"
},
{
"code": null,
"e": 7400,
"s": 7396,
"text": "SQL"
},
{
"code": null,
"e": 7417,
"s": 7400,
"text": "Web Technologies"
},
{
"code": null,
"e": 7421,
"s": 7417,
"text": "SQL"
},
{
"code": null,
"e": 7519,
"s": 7421,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7537,
"s": 7519,
"text": "Python Dictionary"
},
{
"code": null,
"e": 7579,
"s": 7537,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 7601,
"s": 7579,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 7627,
"s": 7601,
"text": "Python String | replace()"
},
{
"code": null,
"e": 7659,
"s": 7627,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 7701,
"s": 7659,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 7748,
"s": 7701,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 7766,
"s": 7748,
"text": "SQL | WITH clause"
},
{
"code": null,
"e": 7810,
"s": 7766,
"text": "How to find Nth highest salary from a table"
}
] |
Drop rows from the dataframe based on certain condition applied on a column | 05 Feb, 2019
Pandas provides a rich collection of functions to perform data analysis in Python. While performing data analysis, quite often we require to filter the data to remove unnecessary rows or columns.
We have already discussed earlier how to drop rows or columns based on their labels. However, in this post we are going to discuss several approaches on how to drop rows from the dataframe based on certain condition applied on a column. Retain all those rows for which the applied condition on the given column evaluates to True.
To download the CSV used in code, click here.
You are given the “nba.csv” dataset. Drop all the players from the dataset whose age is below 25 years.
Solution #1 : We will use vectorization to filter out such rows from the dataset which satisfy the applied condition.
# importing pandas as pdimport pandas as pd # Read the csv file and construct the # dataframedf = pd.read_csv('nba.csv') # Visualize the dataframeprint(df.head(15) # Print the shape of the dataframeprint(df.shape)
Output :
In this dataframe, currently, we are having 458 rows and 9 columns. Let’s use vectorization operation to filter out all those rows which satisfy the given condition.
# Filter all rows for which the player's# age is greater than or equal to 25df_filtered = df[df['Age'] >= 25] # Print the new dataframeprint(df_filtered.head(15) # Print the shape of the dataframeprint(df_filtered.shape)
Output :As we can see in the output, the returned dataframe only contains those players whose age is greater than or equal to 25 years. Solution #2 : We can use the DataFrame.drop() function to drop such rows which does not satisfy the given condition.
# importing pandas as pdimport pandas as pd # Read the csv file and construct the # dataframedf = pd.read_csv('nba.csv') # First filter out those rows which# does not contain any datadf = df.dropna(how = 'all') # Filter all rows for which the player's# age is greater than or equal to 25df.drop(df[df['Age'] < 25].index, inplace = True) # Print the modified dataframeprint(df.head(15)) # Print the shape of the dataframeprint(df.shape)
Output :As we can see in the output, we have successfully dropped all those rows which do not satisfy the given condition applied to the ‘Age’ column.
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Feb, 2019"
},
{
"code": null,
"e": 248,
"s": 52,
"text": "Pandas provides a rich collection of functions to perform data analysis in Python. While performing data analysis, quite often we require to filter the data to remove unnecessary rows or columns."
},
{
"code": null,
"e": 578,
"s": 248,
"text": "We have already discussed earlier how to drop rows or columns based on their labels. However, in this post we are going to discuss several approaches on how to drop rows from the dataframe based on certain condition applied on a column. Retain all those rows for which the applied condition on the given column evaluates to True."
},
{
"code": null,
"e": 624,
"s": 578,
"text": "To download the CSV used in code, click here."
},
{
"code": null,
"e": 728,
"s": 624,
"text": "You are given the “nba.csv” dataset. Drop all the players from the dataset whose age is below 25 years."
},
{
"code": null,
"e": 846,
"s": 728,
"text": "Solution #1 : We will use vectorization to filter out such rows from the dataset which satisfy the applied condition."
},
{
"code": "# importing pandas as pdimport pandas as pd # Read the csv file and construct the # dataframedf = pd.read_csv('nba.csv') # Visualize the dataframeprint(df.head(15) # Print the shape of the dataframeprint(df.shape)",
"e": 1063,
"s": 846,
"text": null
},
{
"code": null,
"e": 1072,
"s": 1063,
"text": "Output :"
},
{
"code": null,
"e": 1238,
"s": 1072,
"text": "In this dataframe, currently, we are having 458 rows and 9 columns. Let’s use vectorization operation to filter out all those rows which satisfy the given condition."
},
{
"code": "# Filter all rows for which the player's# age is greater than or equal to 25df_filtered = df[df['Age'] >= 25] # Print the new dataframeprint(df_filtered.head(15) # Print the shape of the dataframeprint(df_filtered.shape)",
"e": 1461,
"s": 1238,
"text": null
},
{
"code": null,
"e": 1714,
"s": 1461,
"text": "Output :As we can see in the output, the returned dataframe only contains those players whose age is greater than or equal to 25 years. Solution #2 : We can use the DataFrame.drop() function to drop such rows which does not satisfy the given condition."
},
{
"code": "# importing pandas as pdimport pandas as pd # Read the csv file and construct the # dataframedf = pd.read_csv('nba.csv') # First filter out those rows which# does not contain any datadf = df.dropna(how = 'all') # Filter all rows for which the player's# age is greater than or equal to 25df.drop(df[df['Age'] < 25].index, inplace = True) # Print the modified dataframeprint(df.head(15)) # Print the shape of the dataframeprint(df.shape)",
"e": 2155,
"s": 1714,
"text": null
},
{
"code": null,
"e": 2306,
"s": 2155,
"text": "Output :As we can see in the output, we have successfully dropped all those rows which do not satisfy the given condition applied to the ‘Age’ column."
},
{
"code": null,
"e": 2331,
"s": 2306,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 2355,
"s": 2331,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2369,
"s": 2355,
"text": "Python-pandas"
},
{
"code": null,
"e": 2376,
"s": 2369,
"text": "Python"
},
{
"code": null,
"e": 2474,
"s": 2376,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2492,
"s": 2474,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2534,
"s": 2492,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2556,
"s": 2534,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2591,
"s": 2556,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2617,
"s": 2591,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2649,
"s": 2617,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2678,
"s": 2649,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2705,
"s": 2678,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2735,
"s": 2705,
"text": "Iterate over a list in Python"
}
] |
Print Hello World Without using a Semicolon in Java | 23 Nov, 2021
Every statement in Java must end with a semicolon as per the basics. However, unlike other languages, almost all statements in Java can be treated as expressions. However, there are a few scenarios when we can write a running program without semicolons. If we place the statement inside an if/for statement with a blank pair of parentheses, we don’t have to end it with a semicolon. Also, calling a function that returns void will not work here as void functions are not expressions.
Methods:
Using if-else statementsUsing append() method of StringBuilder classUsing equals method of String class
Using if-else statements
Using append() method of StringBuilder class
Using equals method of String class
Method 1: Using if statement
Java
// Java program to Print Hello World Without Semicolon// Using if statement // Main classclass GFG { // Main driver method public static void main(String args[]) { // Using if statement to // print hello world if (System.out.printf("Hello World") == null) { } }}
Hello World
Method 2: Using append() method of StringBuilder class
Java
// Java Program to Print Hello World Without Semicolon// Using append() method of String class // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Using append() method to print statement if (System.out.append("Hello World") == null) { } }}
Hello World
Method 3: Using equals method of String class
Java
// Java Program to Print Hello World Without Semicolon// Using equals() method of String class // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Using equals() method to print statement if (System.out.append("Hello World").equals(null)) { } }}
Hello World
surindertarika1234
reetbatra25
java-basics
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Nov, 2021"
},
{
"code": null,
"e": 538,
"s": 54,
"text": "Every statement in Java must end with a semicolon as per the basics. However, unlike other languages, almost all statements in Java can be treated as expressions. However, there are a few scenarios when we can write a running program without semicolons. If we place the statement inside an if/for statement with a blank pair of parentheses, we don’t have to end it with a semicolon. Also, calling a function that returns void will not work here as void functions are not expressions."
},
{
"code": null,
"e": 548,
"s": 538,
"text": "Methods: "
},
{
"code": null,
"e": 653,
"s": 548,
"text": "Using if-else statementsUsing append() method of StringBuilder classUsing equals method of String class "
},
{
"code": null,
"e": 678,
"s": 653,
"text": "Using if-else statements"
},
{
"code": null,
"e": 723,
"s": 678,
"text": "Using append() method of StringBuilder class"
},
{
"code": null,
"e": 760,
"s": 723,
"text": "Using equals method of String class "
},
{
"code": null,
"e": 789,
"s": 760,
"text": "Method 1: Using if statement"
},
{
"code": null,
"e": 794,
"s": 789,
"text": "Java"
},
{
"code": "// Java program to Print Hello World Without Semicolon// Using if statement // Main classclass GFG { // Main driver method public static void main(String args[]) { // Using if statement to // print hello world if (System.out.printf(\"Hello World\") == null) { } }}",
"e": 1099,
"s": 794,
"text": null
},
{
"code": null,
"e": 1111,
"s": 1099,
"text": "Hello World"
},
{
"code": null,
"e": 1166,
"s": 1111,
"text": "Method 2: Using append() method of StringBuilder class"
},
{
"code": null,
"e": 1171,
"s": 1166,
"text": "Java"
},
{
"code": "// Java Program to Print Hello World Without Semicolon// Using append() method of String class // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Using append() method to print statement if (System.out.append(\"Hello World\") == null) { } }}",
"e": 1535,
"s": 1171,
"text": null
},
{
"code": null,
"e": 1547,
"s": 1535,
"text": "Hello World"
},
{
"code": null,
"e": 1593,
"s": 1547,
"text": "Method 3: Using equals method of String class"
},
{
"code": null,
"e": 1598,
"s": 1593,
"text": "Java"
},
{
"code": "// Java Program to Print Hello World Without Semicolon// Using equals() method of String class // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Using equals() method to print statement if (System.out.append(\"Hello World\").equals(null)) { } }}",
"e": 1966,
"s": 1598,
"text": null
},
{
"code": null,
"e": 1978,
"s": 1966,
"text": "Hello World"
},
{
"code": null,
"e": 1997,
"s": 1978,
"text": "surindertarika1234"
},
{
"code": null,
"e": 2009,
"s": 1997,
"text": "reetbatra25"
},
{
"code": null,
"e": 2021,
"s": 2009,
"text": "java-basics"
},
{
"code": null,
"e": 2026,
"s": 2021,
"text": "Java"
},
{
"code": null,
"e": 2031,
"s": 2026,
"text": "Java"
}
] |
How to Share Files On Local Network Using Apache File Server? | 30 Mar, 2021
Normally we share files between our computers and mobiles using Gmail, Whatsapp, Bluetooth, etc. But here we are going to discuss sharing files using Apache Server from your computer. Your system has to be connected to a LAN for Accessing the files from one computer to another connected on a LAN.
The local server is the same as our web server. As our Web Server serves our needs anywhere and anytime. But Local server operates when multiple clients are connected to the same LAN(Local Area Network). And if we connect a router and connect our mobiles to the Wi-Fi of that router then we can access the files which were shared by the Computer on that server.
Apache HTTP Server is a very powerful HTTP server. It is the replacement for NCSA Server. It is Free of cost and open Source.
ComputerWi-Fi Router(For Mobile Users)Local Area Network Connection(Acts as Local Server)
Computer
Wi-Fi Router(For Mobile Users)
Local Area Network Connection(Acts as Local Server)
You need to download Apache24 from Google and install it on your device. Download the file which is available in 32 bit and 64bit.Unzip the downloaded files where you would like to install the same.Now, open the command prompt and navigate to the location where you have unzipped the folder.Now Use the below command to open the specific folder for starting the server.
You need to download Apache24 from Google and install it on your device. Download the file which is available in 32 bit and 64bit.
Unzip the downloaded files where you would like to install the same.
Now, open the command prompt and navigate to the location where you have unzipped the folder.
Now Use the below command to open the specific folder for starting the server.
cd Apache24/bin/httpd
Now After entering this command you will get a dialogue box for Allowing Access. You have to give access to all Public and Private Networks.
Now You can access the files on the network. Just by typing the host’s IP Address.
Here we have just placed an HTML File, so it is showing the text “It Works” in the browser. You can even place your HTML projects or Your Files in a Folder and Access them.
Example:
If you type in the below statement in the command prompt:
- 192.168.102.67/Geeks
You will get all the files stored in Geeks Folder which is Located in Apache24/htdocs folder.
To access the files on another machine connected to the same network just type the host computer IP Address forwarded by the folder name.
192.168.102.67/Geeks.
So you can access the files.
How To
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
How to Install Git in VS Code?
Docker - COPY Instruction
Setting up the environment in Java
How to Run a Python Script using Docker?
Running Python script on GPU.
How to setup cron jobs in Ubuntu | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 Mar, 2021"
},
{
"code": null,
"e": 352,
"s": 54,
"text": "Normally we share files between our computers and mobiles using Gmail, Whatsapp, Bluetooth, etc. But here we are going to discuss sharing files using Apache Server from your computer. Your system has to be connected to a LAN for Accessing the files from one computer to another connected on a LAN."
},
{
"code": null,
"e": 714,
"s": 352,
"text": "The local server is the same as our web server. As our Web Server serves our needs anywhere and anytime. But Local server operates when multiple clients are connected to the same LAN(Local Area Network). And if we connect a router and connect our mobiles to the Wi-Fi of that router then we can access the files which were shared by the Computer on that server."
},
{
"code": null,
"e": 840,
"s": 714,
"text": "Apache HTTP Server is a very powerful HTTP server. It is the replacement for NCSA Server. It is Free of cost and open Source."
},
{
"code": null,
"e": 930,
"s": 840,
"text": "ComputerWi-Fi Router(For Mobile Users)Local Area Network Connection(Acts as Local Server)"
},
{
"code": null,
"e": 939,
"s": 930,
"text": "Computer"
},
{
"code": null,
"e": 970,
"s": 939,
"text": "Wi-Fi Router(For Mobile Users)"
},
{
"code": null,
"e": 1022,
"s": 970,
"text": "Local Area Network Connection(Acts as Local Server)"
},
{
"code": null,
"e": 1392,
"s": 1022,
"text": "You need to download Apache24 from Google and install it on your device. Download the file which is available in 32 bit and 64bit.Unzip the downloaded files where you would like to install the same.Now, open the command prompt and navigate to the location where you have unzipped the folder.Now Use the below command to open the specific folder for starting the server."
},
{
"code": null,
"e": 1523,
"s": 1392,
"text": "You need to download Apache24 from Google and install it on your device. Download the file which is available in 32 bit and 64bit."
},
{
"code": null,
"e": 1592,
"s": 1523,
"text": "Unzip the downloaded files where you would like to install the same."
},
{
"code": null,
"e": 1686,
"s": 1592,
"text": "Now, open the command prompt and navigate to the location where you have unzipped the folder."
},
{
"code": null,
"e": 1765,
"s": 1686,
"text": "Now Use the below command to open the specific folder for starting the server."
},
{
"code": null,
"e": 1787,
"s": 1765,
"text": "cd Apache24/bin/httpd"
},
{
"code": null,
"e": 1928,
"s": 1787,
"text": "Now After entering this command you will get a dialogue box for Allowing Access. You have to give access to all Public and Private Networks."
},
{
"code": null,
"e": 2011,
"s": 1928,
"text": "Now You can access the files on the network. Just by typing the host’s IP Address."
},
{
"code": null,
"e": 2184,
"s": 2011,
"text": "Here we have just placed an HTML File, so it is showing the text “It Works” in the browser. You can even place your HTML projects or Your Files in a Folder and Access them."
},
{
"code": null,
"e": 2193,
"s": 2184,
"text": "Example:"
},
{
"code": null,
"e": 2251,
"s": 2193,
"text": "If you type in the below statement in the command prompt:"
},
{
"code": null,
"e": 2274,
"s": 2251,
"text": "- 192.168.102.67/Geeks"
},
{
"code": null,
"e": 2368,
"s": 2274,
"text": "You will get all the files stored in Geeks Folder which is Located in Apache24/htdocs folder."
},
{
"code": null,
"e": 2506,
"s": 2368,
"text": "To access the files on another machine connected to the same network just type the host computer IP Address forwarded by the folder name."
},
{
"code": null,
"e": 2528,
"s": 2506,
"text": "192.168.102.67/Geeks."
},
{
"code": null,
"e": 2557,
"s": 2528,
"text": "So you can access the files."
},
{
"code": null,
"e": 2564,
"s": 2557,
"text": "How To"
},
{
"code": null,
"e": 2573,
"s": 2564,
"text": "TechTips"
},
{
"code": null,
"e": 2671,
"s": 2573,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2720,
"s": 2671,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 2762,
"s": 2720,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 2801,
"s": 2762,
"text": "How to Install and Use NVM on Windows?"
},
{
"code": null,
"e": 2855,
"s": 2801,
"text": "How to Install Python Packages for AWS Lambda Layers?"
},
{
"code": null,
"e": 2886,
"s": 2855,
"text": "How to Install Git in VS Code?"
},
{
"code": null,
"e": 2912,
"s": 2886,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 2947,
"s": 2912,
"text": "Setting up the environment in Java"
},
{
"code": null,
"e": 2988,
"s": 2947,
"text": "How to Run a Python Script using Docker?"
},
{
"code": null,
"e": 3018,
"s": 2988,
"text": "Running Python script on GPU."
}
] |
Java Program to Check If a Number is Neon Number or Not | 15 Oct, 2021
A neon number is a number where the sum of digits of the square of the number is equal to the number. The task is to check and print neon numbers in a range.
Illustration:
Case 1:
Input : 9
Output : Given number 9 is Neon number
Explanation : square of 9=9*9=81;
sum of digit of square : 8+1=9(which is equal to given number)
Case 2:
Input : 8
Output : Given number is not a Neon number
Explanation : square of 8=8*8=64
sum of digit of square : 6+4=10(which is not equal to given number)
Algorithm :
First, find the square of the given number.Find the sum of the digit of the square by using a loop. The condition checksum is equal to the given numberReturn trueElse return false.
First, find the square of the given number.
Find the sum of the digit of the square by using a loop.
The condition checksum is equal to the given numberReturn trueElse return false.
Return trueElse return false.
Return true
Else return false.
Pseudo code : Square =n*n;
while(square>0)
{
int r=square%10;
sum+=r;
square=square/10;
}
Example:
Java
// Java Program to Check If a Number is Neon number or not // Importing java input/output libraryimport java.io.*; class GFG { // Method to check whether number is neon or not // Boolean type public static boolean checkNeon(int n) { // squaring the number to be checked int square = n * n; // Initializing current sum to 0 int sum = 0; // If product is positive while (square > 0) { // Step 1: Find remainder int r = square % 10; // Add remainder to the current sum sum += r; // Drop last digit of the product // and store the number square = square / 10; } // Condition check // Sum of digits of number obtained is // equal to original number if (sum == n) // number is neon return true; else // number is not neon return false; } // Main driver method public static void main(String[] args) { // Custom input int n = 9; // Calling above function to check custom number or // if user entered number via Scanner class if (checkNeon(n)) // Print number considered is neon System.out.println("Given number " + n + " is Neon number"); else // Print number considered is not neon System.out.println("Given number " + n + " is not a Neon number"); }}
Given number 9 is Neon number
Time Complexity: O(l) where l is the number of the digit in the square of the given number
clintra
surinderdawra388
simmytarika5
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Oct, 2021"
},
{
"code": null,
"e": 210,
"s": 52,
"text": "A neon number is a number where the sum of digits of the square of the number is equal to the number. The task is to check and print neon numbers in a range."
},
{
"code": null,
"e": 224,
"s": 210,
"text": "Illustration:"
},
{
"code": null,
"e": 577,
"s": 224,
"text": "Case 1:\n\nInput : 9\nOutput : Given number 9 is Neon number\n\nExplanation : square of 9=9*9=81;\n sum of digit of square : 8+1=9(which is equal to given number)\n\n\nCase 2:\n\nInput : 8\nOutput : Given number is not a Neon number\n \nExplanation : square of 8=8*8=64\n sum of digit of square : 6+4=10(which is not equal to given number)"
},
{
"code": null,
"e": 589,
"s": 577,
"text": "Algorithm :"
},
{
"code": null,
"e": 770,
"s": 589,
"text": "First, find the square of the given number.Find the sum of the digit of the square by using a loop. The condition checksum is equal to the given numberReturn trueElse return false."
},
{
"code": null,
"e": 814,
"s": 770,
"text": "First, find the square of the given number."
},
{
"code": null,
"e": 872,
"s": 814,
"text": "Find the sum of the digit of the square by using a loop. "
},
{
"code": null,
"e": 953,
"s": 872,
"text": "The condition checksum is equal to the given numberReturn trueElse return false."
},
{
"code": null,
"e": 983,
"s": 953,
"text": "Return trueElse return false."
},
{
"code": null,
"e": 995,
"s": 983,
"text": "Return true"
},
{
"code": null,
"e": 1014,
"s": 995,
"text": "Else return false."
},
{
"code": null,
"e": 1188,
"s": 1014,
"text": "Pseudo code : Square =n*n;\n while(square>0)\n {\n int r=square%10;\n sum+=r;\n square=square/10;\n }"
},
{
"code": null,
"e": 1197,
"s": 1188,
"text": "Example:"
},
{
"code": null,
"e": 1202,
"s": 1197,
"text": "Java"
},
{
"code": "// Java Program to Check If a Number is Neon number or not // Importing java input/output libraryimport java.io.*; class GFG { // Method to check whether number is neon or not // Boolean type public static boolean checkNeon(int n) { // squaring the number to be checked int square = n * n; // Initializing current sum to 0 int sum = 0; // If product is positive while (square > 0) { // Step 1: Find remainder int r = square % 10; // Add remainder to the current sum sum += r; // Drop last digit of the product // and store the number square = square / 10; } // Condition check // Sum of digits of number obtained is // equal to original number if (sum == n) // number is neon return true; else // number is not neon return false; } // Main driver method public static void main(String[] args) { // Custom input int n = 9; // Calling above function to check custom number or // if user entered number via Scanner class if (checkNeon(n)) // Print number considered is neon System.out.println(\"Given number \" + n + \" is Neon number\"); else // Print number considered is not neon System.out.println(\"Given number \" + n + \" is not a Neon number\"); }}",
"e": 2739,
"s": 1202,
"text": null
},
{
"code": null,
"e": 2769,
"s": 2739,
"text": "Given number 9 is Neon number"
},
{
"code": null,
"e": 2860,
"s": 2769,
"text": "Time Complexity: O(l) where l is the number of the digit in the square of the given number"
},
{
"code": null,
"e": 2870,
"s": 2862,
"text": "clintra"
},
{
"code": null,
"e": 2887,
"s": 2870,
"text": "surinderdawra388"
},
{
"code": null,
"e": 2900,
"s": 2887,
"text": "simmytarika5"
},
{
"code": null,
"e": 2907,
"s": 2900,
"text": "Picked"
},
{
"code": null,
"e": 2931,
"s": 2907,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 2936,
"s": 2931,
"text": "Java"
},
{
"code": null,
"e": 2950,
"s": 2936,
"text": "Java Programs"
},
{
"code": null,
"e": 2969,
"s": 2950,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2974,
"s": 2969,
"text": "Java"
}
] |
Convert string to title case in JavaScript | 23 Apr, 2019
We convert a string to title case in such a way that every new word begins with a capital(uppercase) letter.This can be achieved by following ways-1) By using replace() function
<script>function sentenceCase (str) { if ((str===null) || (str==='')) return false; else str = str.toString(); return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});} document.write(sentenceCase('geeks for geeks'));</script>
OUTPUT
Geeks For Geeks
2) By using For loop to titlecase a string
<script>function titleCase(str) { str = str.toLowerCase().split(' '); for (var i = 0; i < str.length; i++) { str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1); } return str.join(' ');}document.write(titleCase("GEEKS FOR GEEKS"));</script>
OUTPUT
Geeks For Geeks
3) By using map() method
<script>function titleCase(str) { return str.toLowerCase().split(' ').map(function(word) { return (word.charAt(0).toUpperCase() + word.slice(1)); }).join(' ');}document.write(titleCase("converting string to titlecase"));</script>
OUTPUT
Converting String To Titlecase
javascript-string
Picked
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
JavaScript | Promises
How to filter object array based on attributes?
Lodash _.debounce() Method
JavaScript String includes() Method
JavaScript | fetch() Method
How to map, reduce and filter a Set element using JavaScript ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Apr, 2019"
},
{
"code": null,
"e": 206,
"s": 28,
"text": "We convert a string to title case in such a way that every new word begins with a capital(uppercase) letter.This can be achieved by following ways-1) By using replace() function"
},
{
"code": "<script>function sentenceCase (str) { if ((str===null) || (str==='')) return false; else str = str.toString(); return str.replace(/\\w\\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});} document.write(sentenceCase('geeks for geeks'));</script>",
"e": 507,
"s": 206,
"text": null
},
{
"code": null,
"e": 514,
"s": 507,
"text": "OUTPUT"
},
{
"code": null,
"e": 530,
"s": 514,
"text": "Geeks For Geeks"
},
{
"code": null,
"e": 573,
"s": 530,
"text": "2) By using For loop to titlecase a string"
},
{
"code": "<script>function titleCase(str) { str = str.toLowerCase().split(' '); for (var i = 0; i < str.length; i++) { str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1); } return str.join(' ');}document.write(titleCase(\"GEEKS FOR GEEKS\"));</script>",
"e": 828,
"s": 573,
"text": null
},
{
"code": null,
"e": 835,
"s": 828,
"text": "OUTPUT"
},
{
"code": null,
"e": 851,
"s": 835,
"text": "Geeks For Geeks"
},
{
"code": null,
"e": 876,
"s": 851,
"text": "3) By using map() method"
},
{
"code": "<script>function titleCase(str) { return str.toLowerCase().split(' ').map(function(word) { return (word.charAt(0).toUpperCase() + word.slice(1)); }).join(' ');}document.write(titleCase(\"converting string to titlecase\"));</script>",
"e": 1111,
"s": 876,
"text": null
},
{
"code": null,
"e": 1118,
"s": 1111,
"text": "OUTPUT"
},
{
"code": null,
"e": 1149,
"s": 1118,
"text": "Converting String To Titlecase"
},
{
"code": null,
"e": 1167,
"s": 1149,
"text": "javascript-string"
},
{
"code": null,
"e": 1174,
"s": 1167,
"text": "Picked"
},
{
"code": null,
"e": 1185,
"s": 1174,
"text": "JavaScript"
},
{
"code": null,
"e": 1283,
"s": 1185,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1344,
"s": 1283,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1384,
"s": 1344,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1426,
"s": 1384,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 1467,
"s": 1426,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1489,
"s": 1467,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 1537,
"s": 1489,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 1564,
"s": 1537,
"text": "Lodash _.debounce() Method"
},
{
"code": null,
"e": 1600,
"s": 1564,
"text": "JavaScript String includes() Method"
},
{
"code": null,
"e": 1628,
"s": 1600,
"text": "JavaScript | fetch() Method"
}
] |
wxPython - Event Handling | Unlike a console mode application, which is executed in a sequential manner, a GUI based application is event driven. Functions or methods are executed in response to user’s actions like clicking a button, selecting an item from collection or mouse click, etc., called events.
Data pertaining to an event which takes place during the application’s runtime is stored as object of a subclass derived from wx.Event. A display control (such as Button) is the source of event of a particular type and produces an object of Event class associated to it. For instance, click of a button emits a wx.CommandEvent. This event data is dispatched to event handler method in the program. wxPython has many predefined event binders. An Event binder encapsulates relationship between a specific widget (control), its associated event type and the event handler method.
For example, to call OnClick() method of the program on a button’s click event, the following statement is required −
self.b1.Bind(EVT_BUTTON, OnClick)
Bind() method is inherited by all display objects from wx.EvtHandler class. EVT_.BUTTON here is the binder, which associates button click event to OnClick() method.
In the following example, the MoveEvent, caused by dragging the top level window – a wx.Frame object in this case – is connected to OnMove() method using wx.EVT_MOVE binder. The code displays a window. If it is moved using mouse, its instantaneous coordinates are displayed on the console.
import wx
class Example(wx.Frame):
def __init__(self, *args, **kw):
super(Example, self).__init__(*args, **kw)
self.InitUI()
def InitUI(self):
self.Bind(wx.EVT_MOVE, self.OnMove)
self.SetSize((250, 180))
self.SetTitle('Move event')
self.Centre()
self.Show(True)
def OnMove(self, e):
x, y = e.GetPosition()
print "current window position x = ",x," y= ",y
ex = wx.App()
Example(None)
ex.MainLoop()
The above code produces the following output −
current window position x = 562 y = 309
current window position x = 562 y = 309
current window position x = 326 y = 304
current window position x = 384 y = 240
current window position x = 173 y = 408
current window position x = 226 y = 30
current window position x = 481 y = 80
Some of the subclasses inherited from wx.Event are listed in the following table −
wxKeyEvent
Occurs when a key is presses or released
wxPaintEvent
Is generated whenever contents of the window needs to be redrawn
wxMouseEvent
Contains data about any event due to mouse activity like mouse button pressed or dragged
wxScrollEvent
Associated with scrollable controls like wxScrollbar and wxSlider
wxCommandEvent
Contains event data originating from many widgets such as button, dialogs, clipboard, etc.
wxMenuEvent
Different menu-related events excluding menu command button click
wxColourPickerEvent
wxColourPickerCtrl generated events
wxDirFilePickerEvent
Events generated by FileDialog and DirDialog
Events in wxPython are of two types. Basic events and Command events. A basic event stays local to the window in which it originates. Most of the wxWidgets generate command events. A command event can be propagated to window or windows, which are above the source window in class hierarchy.
Following is a simple example of event propagation. The complete code is −
import wx
class MyPanel(wx.Panel):
def __init__(self, parent):
super(MyPanel, self).__init__(parent)
b = wx.Button(self, label = 'Btn', pos = (100,100))
b.Bind(wx.EVT_BUTTON, self.btnclk)
self.Bind(wx.EVT_BUTTON, self.OnButtonClicked)
def OnButtonClicked(self, e):
print 'Panel received click event. propagated to Frame class'
e.Skip()
def btnclk(self,e):
print "Button received click event. propagated to Panel class"
e.Skip()
class Example(wx.Frame):
def __init__(self,parent):
super(Example, self).__init__(parent)
self.InitUI()
def InitUI(self):
mpnl = MyPanel(self)
self.Bind(wx.EVT_BUTTON, self.OnButtonClicked)
self.SetTitle('Event propagation demo')
self.Centre()
self.Show(True)
def OnButtonClicked(self, e):
print 'click event received by frame class'
e.Skip()
ex = wx.App()
Example(None)
ex.MainLoop()
In the above code, there are two classes. MyPanel, a wx.Panel subclass and Example, a wx.Frame subclass which is the top level window for the program. A button is placed in the panel.
This Button object is bound to an event handler btnclk() which propagates it to parent class (MyPanel in this case). Button click generates a CommandEvent which can be propagated to its parent by Skip() method.
MyPanel class object also binds the received event to another handler OnButtonClicked(). This function in turn transmits to its parent, the Example class. The above code produces the following output −
Button received click event. Propagated to Panel class.
Panel received click event. Propagated to Frame class.
Click event received by frame class. | [
{
"code": null,
"e": 2293,
"s": 2016,
"text": "Unlike a console mode application, which is executed in a sequential manner, a GUI based application is event driven. Functions or methods are executed in response to user’s actions like clicking a button, selecting an item from collection or mouse click, etc., called events."
},
{
"code": null,
"e": 2870,
"s": 2293,
"text": "Data pertaining to an event which takes place during the application’s runtime is stored as object of a subclass derived from wx.Event. A display control (such as Button) is the source of event of a particular type and produces an object of Event class associated to it. For instance, click of a button emits a wx.CommandEvent. This event data is dispatched to event handler method in the program. wxPython has many predefined event binders. An Event binder encapsulates relationship between a specific widget (control), its associated event type and the event handler method."
},
{
"code": null,
"e": 2988,
"s": 2870,
"text": "For example, to call OnClick() method of the program on a button’s click event, the following statement is required −"
},
{
"code": null,
"e": 3023,
"s": 2988,
"text": "self.b1.Bind(EVT_BUTTON, OnClick)\n"
},
{
"code": null,
"e": 3188,
"s": 3023,
"text": "Bind() method is inherited by all display objects from wx.EvtHandler class. EVT_.BUTTON here is the binder, which associates button click event to OnClick() method."
},
{
"code": null,
"e": 3478,
"s": 3188,
"text": "In the following example, the MoveEvent, caused by dragging the top level window – a wx.Frame object in this case – is connected to OnMove() method using wx.EVT_MOVE binder. The code displays a window. If it is moved using mouse, its instantaneous coordinates are displayed on the console."
},
{
"code": null,
"e": 3999,
"s": 3478,
"text": "import wx\n \nclass Example(wx.Frame): \n \n def __init__(self, *args, **kw): \n super(Example, self).__init__(*args, **kw) \n self.InitUI() \n \n def InitUI(self): \n self.Bind(wx.EVT_MOVE, self.OnMove) \n self.SetSize((250, 180)) \n self.SetTitle('Move event') \n self.Centre() \n self.Show(True)\n\t\t \n def OnMove(self, e): \n x, y = e.GetPosition() \n print \"current window position x = \",x,\" y= \",y \n \nex = wx.App() \nExample(None) \nex.MainLoop() "
},
{
"code": null,
"e": 4046,
"s": 3999,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 4087,
"s": 4046,
"text": "current window position x = 562 y = 309"
},
{
"code": null,
"e": 4128,
"s": 4087,
"text": "current window position x = 562 y = 309"
},
{
"code": null,
"e": 4169,
"s": 4128,
"text": "current window position x = 326 y = 304"
},
{
"code": null,
"e": 4210,
"s": 4169,
"text": "current window position x = 384 y = 240"
},
{
"code": null,
"e": 4251,
"s": 4210,
"text": "current window position x = 173 y = 408"
},
{
"code": null,
"e": 4291,
"s": 4251,
"text": "current window position x = 226 y = 30"
},
{
"code": null,
"e": 4331,
"s": 4291,
"text": "current window position x = 481 y = 80"
},
{
"code": null,
"e": 4414,
"s": 4331,
"text": "Some of the subclasses inherited from wx.Event are listed in the following table −"
},
{
"code": null,
"e": 4425,
"s": 4414,
"text": "wxKeyEvent"
},
{
"code": null,
"e": 4466,
"s": 4425,
"text": "Occurs when a key is presses or released"
},
{
"code": null,
"e": 4479,
"s": 4466,
"text": "wxPaintEvent"
},
{
"code": null,
"e": 4544,
"s": 4479,
"text": "Is generated whenever contents of the window needs to be redrawn"
},
{
"code": null,
"e": 4557,
"s": 4544,
"text": "wxMouseEvent"
},
{
"code": null,
"e": 4646,
"s": 4557,
"text": "Contains data about any event due to mouse activity like mouse button pressed or dragged"
},
{
"code": null,
"e": 4660,
"s": 4646,
"text": "wxScrollEvent"
},
{
"code": null,
"e": 4726,
"s": 4660,
"text": "Associated with scrollable controls like wxScrollbar and wxSlider"
},
{
"code": null,
"e": 4741,
"s": 4726,
"text": "wxCommandEvent"
},
{
"code": null,
"e": 4832,
"s": 4741,
"text": "Contains event data originating from many widgets such as button, dialogs, clipboard, etc."
},
{
"code": null,
"e": 4844,
"s": 4832,
"text": "wxMenuEvent"
},
{
"code": null,
"e": 4910,
"s": 4844,
"text": "Different menu-related events excluding menu command button click"
},
{
"code": null,
"e": 4930,
"s": 4910,
"text": "wxColourPickerEvent"
},
{
"code": null,
"e": 4966,
"s": 4930,
"text": "wxColourPickerCtrl generated events"
},
{
"code": null,
"e": 4987,
"s": 4966,
"text": "wxDirFilePickerEvent"
},
{
"code": null,
"e": 5032,
"s": 4987,
"text": "Events generated by FileDialog and DirDialog"
},
{
"code": null,
"e": 5323,
"s": 5032,
"text": "Events in wxPython are of two types. Basic events and Command events. A basic event stays local to the window in which it originates. Most of the wxWidgets generate command events. A command event can be propagated to window or windows, which are above the source window in class hierarchy."
},
{
"code": null,
"e": 5398,
"s": 5323,
"text": "Following is a simple example of event propagation. The complete code is −"
},
{
"code": null,
"e": 6417,
"s": 5398,
"text": "import wx\n \nclass MyPanel(wx.Panel): \n \n def __init__(self, parent): \n super(MyPanel, self).__init__(parent)\n\t\t\n b = wx.Button(self, label = 'Btn', pos = (100,100)) \n b.Bind(wx.EVT_BUTTON, self.btnclk) \n self.Bind(wx.EVT_BUTTON, self.OnButtonClicked) \n\t\t\n def OnButtonClicked(self, e): \n \n print 'Panel received click event. propagated to Frame class' \n e.Skip() \n\t\t\n def btnclk(self,e): \n print \"Button received click event. propagated to Panel class\" \n e.Skip()\n\t\t\nclass Example(wx.Frame):\n\n def __init__(self,parent): \n super(Example, self).__init__(parent) \n \n self.InitUI() \n\n def InitUI(self):\n\t\n mpnl = MyPanel(self) \n self.Bind(wx.EVT_BUTTON, self.OnButtonClicked)\n\t\t\n self.SetTitle('Event propagation demo') \n self.Centre() \n self.Show(True)\n\t\t\n def OnButtonClicked(self, e): \n \n print 'click event received by frame class' \n e.Skip()\n\t\t\nex = wx.App() \nExample(None) \nex.MainLoop()"
},
{
"code": null,
"e": 6601,
"s": 6417,
"text": "In the above code, there are two classes. MyPanel, a wx.Panel subclass and Example, a wx.Frame subclass which is the top level window for the program. A button is placed in the panel."
},
{
"code": null,
"e": 6812,
"s": 6601,
"text": "This Button object is bound to an event handler btnclk() which propagates it to parent class (MyPanel in this case). Button click generates a CommandEvent which can be propagated to its parent by Skip() method."
},
{
"code": null,
"e": 7014,
"s": 6812,
"text": "MyPanel class object also binds the received event to another handler OnButtonClicked(). This function in turn transmits to its parent, the Example class. The above code produces the following output −"
}
] |
Difference between long int and long long int in C/C++ | 13 Jun, 2022
All variables use data type during declarations to restrict the type of data to be stored. Therefore, we can say that data types are used to tell the variables the type of data it can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared. Different data types require a different amount of memory.
Integer: The keyword used for integer data types is int. Integers typically require 4 bytes of memory space and range from -2147483648 to 2147483647.
Datatype Modifiers: As the name implies, datatype modifiers are used with the built-in data types to modify the length of data that a particular data type can hold.
Below is a list of ranges along with the memory requirements and format specifiers on the 32-bit GCC compiler.
S. No.
Data Type
Memory
(bytes)
Range
Long long takes the double memory as compared to long. But it can also be different on various systems. Its range depends on the type of application. The guaranteed minimum usable bit sizes for different data types:
char: 8
short:16
int: 16
long: 32
long long: 64
The decreasing order is: long long >=long>=int>=short>=char
Program 1:
In various competitive coding platforms, the constraints are between 107 to 1018. Below is the program to understand the concept:
C++
// C++ program to implement// the above approach#include <iostream>using namespace std; // Driver codeint main(){ // Value of p 10^5 int p = 100000; // Value of q 10^5 int q = 100000; int result = p * q; cout << result << endl; return 0;}
1410065408
As above, the output is not correct as int can’t store a 1010 value(out of its range). In this case, long long should be used.
Program 2:
Below is the C++ program to demonstrate how converting int to long long affects the output:
C++
// C++ program to implement// the above approach#include <iostream>using namespace std; // Driver codeint main(){ // Value of p 10^5 int p = 100000; // Value of q 10^5 int q = 100000; long long int result = p * q; cout << result << endl; return 0;}
1410065408
Explanation: The above program gives the same output even after converting int to long long int because at first, the result is declared as long long. But before assigning the value of multiplication of p and q, it is already overflowed. Now, to prevent the overflow condition, it is required to convert the int result to the long long int before assigning the result value so that the overflow condition does not occur.
Program 3:
Below is the C++ program to implement the above approach:
C++
// C++ program to implement// the above approach#include <iostream>using namespace std; // Driver codeint main(){ // Value of p 10^5 int p = 100000; // Value of q 10^5 int q = 100000; long long int result = (long long int)p * q; cout << result << endl; return 0;}
10000000000
Explanation: After this, it gives the correct output, which is 1010, which can be easily stored into a long long data type as the range is up to 1018.
nobleniraj
Data Types
Articles
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
Time complexities of different data structures
Difference Between Object And Class
SQL | DROP, TRUNCATE
Implementation of LinkedList in Javascript
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
std::sort() in C++ STL
Bitwise Operators in C/C++ | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 444,
"s": 52,
"text": "All variables use data type during declarations to restrict the type of data to be stored. Therefore, we can say that data types are used to tell the variables the type of data it can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared. Different data types require a different amount of memory."
},
{
"code": null,
"e": 594,
"s": 444,
"text": "Integer: The keyword used for integer data types is int. Integers typically require 4 bytes of memory space and range from -2147483648 to 2147483647."
},
{
"code": null,
"e": 760,
"s": 594,
"text": "Datatype Modifiers: As the name implies, datatype modifiers are used with the built-in data types to modify the length of data that a particular data type can hold. "
},
{
"code": null,
"e": 871,
"s": 760,
"text": "Below is a list of ranges along with the memory requirements and format specifiers on the 32-bit GCC compiler."
},
{
"code": null,
"e": 879,
"s": 871,
"text": "S. No. "
},
{
"code": null,
"e": 889,
"s": 879,
"text": "Data Type"
},
{
"code": null,
"e": 896,
"s": 889,
"text": "Memory"
},
{
"code": null,
"e": 904,
"s": 896,
"text": "(bytes)"
},
{
"code": null,
"e": 910,
"s": 904,
"text": "Range"
},
{
"code": null,
"e": 1127,
"s": 910,
"text": " Long long takes the double memory as compared to long. But it can also be different on various systems. Its range depends on the type of application. The guaranteed minimum usable bit sizes for different data types:"
},
{
"code": null,
"e": 1135,
"s": 1127,
"text": "char: 8"
},
{
"code": null,
"e": 1144,
"s": 1135,
"text": "short:16"
},
{
"code": null,
"e": 1152,
"s": 1144,
"text": "int: 16"
},
{
"code": null,
"e": 1161,
"s": 1152,
"text": "long: 32"
},
{
"code": null,
"e": 1175,
"s": 1161,
"text": "long long: 64"
},
{
"code": null,
"e": 1235,
"s": 1175,
"text": "The decreasing order is: long long >=long>=int>=short>=char"
},
{
"code": null,
"e": 1246,
"s": 1235,
"text": "Program 1:"
},
{
"code": null,
"e": 1376,
"s": 1246,
"text": "In various competitive coding platforms, the constraints are between 107 to 1018. Below is the program to understand the concept:"
},
{
"code": null,
"e": 1380,
"s": 1376,
"text": "C++"
},
{
"code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // Driver codeint main(){ // Value of p 10^5 int p = 100000; // Value of q 10^5 int q = 100000; int result = p * q; cout << result << endl; return 0;}",
"e": 1642,
"s": 1380,
"text": null
},
{
"code": null,
"e": 1653,
"s": 1642,
"text": "1410065408"
},
{
"code": null,
"e": 1780,
"s": 1653,
"text": "As above, the output is not correct as int can’t store a 1010 value(out of its range). In this case, long long should be used."
},
{
"code": null,
"e": 1791,
"s": 1780,
"text": "Program 2:"
},
{
"code": null,
"e": 1883,
"s": 1791,
"text": "Below is the C++ program to demonstrate how converting int to long long affects the output:"
},
{
"code": null,
"e": 1887,
"s": 1883,
"text": "C++"
},
{
"code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // Driver codeint main(){ // Value of p 10^5 int p = 100000; // Value of q 10^5 int q = 100000; long long int result = p * q; cout << result << endl; return 0;}",
"e": 2159,
"s": 1887,
"text": null
},
{
"code": null,
"e": 2170,
"s": 2159,
"text": "1410065408"
},
{
"code": null,
"e": 2591,
"s": 2170,
"text": "Explanation: The above program gives the same output even after converting int to long long int because at first, the result is declared as long long. But before assigning the value of multiplication of p and q, it is already overflowed. Now, to prevent the overflow condition, it is required to convert the int result to the long long int before assigning the result value so that the overflow condition does not occur."
},
{
"code": null,
"e": 2602,
"s": 2591,
"text": "Program 3:"
},
{
"code": null,
"e": 2660,
"s": 2602,
"text": "Below is the C++ program to implement the above approach:"
},
{
"code": null,
"e": 2664,
"s": 2660,
"text": "C++"
},
{
"code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // Driver codeint main(){ // Value of p 10^5 int p = 100000; // Value of q 10^5 int q = 100000; long long int result = (long long int)p * q; cout << result << endl; return 0;}",
"e": 2951,
"s": 2664,
"text": null
},
{
"code": null,
"e": 2963,
"s": 2951,
"text": "10000000000"
},
{
"code": null,
"e": 3114,
"s": 2963,
"text": "Explanation: After this, it gives the correct output, which is 1010, which can be easily stored into a long long data type as the range is up to 1018."
},
{
"code": null,
"e": 3125,
"s": 3114,
"text": "nobleniraj"
},
{
"code": null,
"e": 3136,
"s": 3125,
"text": "Data Types"
},
{
"code": null,
"e": 3145,
"s": 3136,
"text": "Articles"
},
{
"code": null,
"e": 3149,
"s": 3145,
"text": "C++"
},
{
"code": null,
"e": 3162,
"s": 3149,
"text": "C++ Programs"
},
{
"code": null,
"e": 3166,
"s": 3162,
"text": "CPP"
},
{
"code": null,
"e": 3264,
"s": 3166,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3290,
"s": 3264,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 3337,
"s": 3290,
"text": "Time complexities of different data structures"
},
{
"code": null,
"e": 3373,
"s": 3337,
"text": "Difference Between Object And Class"
},
{
"code": null,
"e": 3394,
"s": 3373,
"text": "SQL | DROP, TRUNCATE"
},
{
"code": null,
"e": 3437,
"s": 3394,
"text": "Implementation of LinkedList in Javascript"
},
{
"code": null,
"e": 3455,
"s": 3437,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 3498,
"s": 3455,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3544,
"s": 3498,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 3567,
"s": 3544,
"text": "std::sort() in C++ STL"
}
] |
Maximum Difference | Practice | GeeksforGeeks | Given array A[] of integers, the task is to complete the function findMaxDiff which finds the maximum absolute difference between nearest left and right smaller element of every element in array.If the element is the leftmost element, nearest smaller element on left side is considered as 0. Similarly if the element is the rightmost elements, smaller element on right side is considered as 0.
Examples:
Input : arr[] = {2, 1, 8}
Output : 1
Left smaller LS[] {0, 0, 1}
Right smaller RS[] {1, 0, 0}
Maximum Diff of abs(LS[i] - RS[i]) = 1
Input : arr[] = {2, 4, 8, 7, 7, 9, 3}
Output : 4
Left smaller LS[] = {0, 2, 4, 4, 4, 7, 2}
Right smaller RS[] = {0, 3, 7, 3, 3, 3, 0}
Maximum Diff of abs(LS[i] - RS[i]) = 7 - 3 = 4
Input : arr[] = {5, 1, 9, 2, 5, 1, 7}
Output : 1
Input:
The first line of input contains an integer T denoting the no of test cases. Then T test cases follow .Each test case contains an integer N denoting the size of the array A. In the next line are N space separated values of the array A.
Output:
For each test case output will be in a new line denoting the the maximum absolute difference between nearest left and right smaller element of every element in array.
Constraints:
1<=T<=100
1<=N<=100
1<=A[ ]<=100
Example(To be used only for expected output) :
Input:
2
3
2 1 8
7
2 4 8 7 7 9 3
Output
1
4
+1
sauravmehta8185 days ago
O(n) Solution
class Solution
{
int findMaxDiff(int arr[], int n)
{
int[] output1=leftsmall(arr);
int[] output2=rightsmall(arr);
int num=Integer.MIN_VALUE;
for(int i=0;i<arr.length;i++)
{
if(Math.abs(output1[i]-output2[i])>num)
num=Math.abs(output1[i]-output2[i]);
}
return num;
}
public int[] leftsmall(int[] arr)
{
Stack<Integer> stk=new Stack<>();
int[] output=new int[arr.length];
stk.push(arr[0]);
output[0]=0;
for(int i=1;i<arr.length;i++)
{
while(!stk.empty() && stk.peek()>=arr[i])
stk.pop();
output[i]=stk.empty()? 0:stk.peek();
stk.push(arr[i]);
}
return output;
}
public int[] rightsmall(int[] arr)
{
Stack<Integer> stk=new Stack<>();
int[] output=new int[arr.length];
stk.push(arr[arr.length-1]);
output[arr.length-1]=0;
for(int i=arr.length-2;i>=0;i--)
{
while(!stk.empty() && stk.peek()>=arr[i])
stk.pop();
output[i]=stk.empty()? 0:stk.peek();
stk.push(arr[i]);
}
return output;
}
}
0
bhavinbansal78652 weeks ago
int findMaxDiff(int a[], int n) { //Your code here int left[n]; left[0]=0; int k; bool flag; for(int i=1;i<n;i++) { k=i-1; flag=false; while(k>=0) { if(a[i]>a[k]) { left[i]=a[k]; flag=true; break; } k--; } if(flag==false) left[i]=0; } int right[n]; right[n-1]=0; for(int i=n-2;i>=0;i--) { k=i+1; flag=false; while(k<=(n-1)) { if(a[i]>a[k]) { right[i]=a[k]; flag=true; break; } k++; } if(flag==false) right[i]=0; } int res=0; for(int i=0;i<n;i++) { res=max(res,abs(left[i]-right[i])); } return res; }
0
rawn963 weeks ago
int findMaxDiff(int a[], int n)
{
stack<int> s;
int ls[n]={0},ans=0;
for(int i=0;i<n;i++){
while(!s.empty() && a[s.top()]>a[i]){
ans=max(ans,abs(ls[s.top()]-a[i]));
s.pop();
}
if(!s.empty())
ls[i]=a[s.top()]==a[i] ? ls[s.top()] : a[s.top()];
s.push(i);
}
while(!s.empty()){
ans=max(ans,ls[s.top()]);
s.pop();
}
return ans;
}
+1
ankitmaurya31 month ago
def nearestleftsmaller(a,n):
ans = []
stack = []
for i in range(n):
while(len(stack)!=0 and a[i]<=stack[-1]):
stack.pop()
if len(stack)==0:
ans.append(0)
else:
ans.append(stack[-1])
# ans.append(0 if len(stack)==0 else stack[-1])
stack.append(a[i])
return ans
def nearestrightsmaller(a,n):
ans = [0 for i in range(n)]
stack = []
for i in range(n-1,-1,-1):
while(len(stack)!=0 and a[i]<=stack[-1]):
stack.pop()
if len(stack)==0:
ans[i] = 0
else:
ans[i] = stack[-1]
# ans.append(0 if len(stack)==0 else stack[-1])
stack.append(a[i])
return ans
class Solution:
# Your task is to complete this function
# Function should return an integer denoting the required answer
def findMaxDiff(self, a, n):
nrs = nearestrightsmaller(a,n)
nls = nearestleftsmaller(a,n)
res = 0
for i in range(n):
res = max(res,abs(nls[i]-nrs[i]))
return res
0
anupamojha31131 month ago
//Your code here // Time Taken 0.01/1.29 int ans=0; for(int i=0;i<n;i++){ int r=0;int l=0; for(int j=i;j<n;j++){ if(arr[i]>arr[j]){ r=arr[j]; break; } } for(int j=i;j>=0;j--){ if(arr[i]>arr[j]){ l=arr[j]; break; } } ans=max(ans,abs(l-r)); } return ans;
0
21mx1261 month ago
//c++ program
vector<int> ls(n,0); vector<int> stk; stk.push_back(0); for(int i=0;i<n;i++){ if(A[i]>stk[stk.size()-1]){ ls[i]=stk[stk.size()-1]; stk.push_back(A[i]); }else{ while(A[i]<=stk[stk.size()-1]){ stk.erase(stk.begin()+stk.size()-1); } ls[i]=stk[stk.size()-1]; stk.push_back(A[i]); } } stk.clear(); stk.push_back(0); int res=INT_MIN; for(int i=n-1;i>=0;i--){ if(A[i]>stk[stk.size()-1]){ //cout << stk[stk.size()-1] << " "; res = (res > abs(ls[i]-stk[stk.size()-1]) ? res : abs(ls[i]-stk[stk.size()-1])); stk.push_back(A[i]); }else{ while(A[i]<=stk[stk.size()-1]){ stk.erase(stk.begin()+stk.size()-1); } //cout << stk[stk.size()-1] << " "; res = (res > abs(ls[i]-stk[stk.size()-1]) ? res : abs(ls[i]-stk[stk.size()-1])); stk.push_back(A[i]); } } return res;
0
21mx126
This comment was deleted.
0
onlybkm20021 month ago
int findMaxDiff(int A[], int n)
{
stack<int> st1;
stack<int> st2;
vector<int> ls(n,0);
vector<int> rs(n,0);
for(int i=n-1; i>=0; i--)
{
while(!st1.empty() && st1.top()>=A[i])
{
st1.pop();
}
if(i<n)
{
if(!st1.empty())
{
rs[i] = st1.top();
}
}
st1.push(A[i]);
}
for(int i=0; i<n; i++)
{
while(!st2.empty() && st2.top()>=A[i])
{
st2.pop();
}
if(i<n)
{
if(!st2.empty())
{
ls[i] = st2.top();
}
}
st2.push(A[i]);
}
vector<int> diff(n);
for(int i=0; i<n; i++)
{
diff[i] = abs(ls[i]-rs[i]);
}
int maxDiff = INT_MIN;
for(int i=0; i<n; i++)
{
maxDiff = max(maxDiff,diff[i]);
}
return maxDiff;
}
0
tooweaktooslow2 months ago
EASY JAVA SOLUTION
class Solution{ int findMaxDiff(int arr[], int n) { if(n==1)return 0; Integer[] ls=new Integer[n];//left smaller Integer[] rs=new Integer[n];//right smaller Stack<Integer>st=new Stack<>(); findls(ls,arr,st,n); st=new Stack<>(); findrs(rs,arr,st,n); // System.out.println(Arrays.toString(ls)); int max=Integer.MIN_VALUE; for(int i=0;i<n;i++) { int t=Math.abs(ls[i]-rs[i]); if(t>max)max=t; } return max; } public static void findls(Integer[]ans,int[]arr,Stack<Integer>st,int n) { ans[0]=0; st.push(arr[0]); for(int i=1;i<n;i++) { if(st.size()>0 && st.peek()<arr[i]) { ans[i]=st.peek(); st.push(arr[i]); } else{ if(st.size()==0) { ans[i]=0; st.push(arr[i]); } else{ while(st.size()>0 && st.peek()>=arr[i]) { st.pop(); } if(st.size()==0) { ans[i]=0; st.push(arr[i]); } else{ ans[i]=st.peek(); st.push(arr[i]); } } } } } public static void findrs(Integer[]ans,int[]arr,Stack<Integer>st,int n){ ans[n-1]=0; st.push(arr[n-1]); for(int i=n-2;i>=0;i--) { if(st.peek()<arr[i]) { ans[i]=st.peek(); st.push(arr[i]); } else{ while(st.size()>0 && st.peek()>=arr[i]) { st.pop(); } if(st.size()==0) { ans[i]=0; st.push(arr[i]); }else{ ans[i]=st.peek(); st.push(arr[i]); } } } }}
0
shubhankardey29sep2 months ago
class Solution
{
int findMaxDiff(int a[], int n)
{
// Your code here
int []r1 = nsl(a,n);
int []r2 = nsr(a,n);
int max = 0;
for(int i=0;i<n;i++)
{
int res = Math.abs(r1[i] - r2[i]);
max = Math.max(max,res);
}
return max;
}
int[] nsl(int []a,int n)
{
Stack<Integer> st = new Stack<>();
int []res = new int[n];
res[0] = 0;
st.push(a[0]);
int idx = 1;
for(int i=1;i<n;i++)
{
while(!st.isEmpty() && st.peek()>=a[i])
st.pop();
if(st.size()==0)
res[idx++] = 0;
else
res[idx++] = st.peek();
st.push(a[i]);
}
return res;
}
int[] nsr(int []a,int n)
{
Stack<Integer> st = new Stack<>();
int []res = new int[n];
res[n-1] = 0;
st.push(a[n-1]);
int idx = n-2;
for(int i=n-2;i>=0;i--)
{
while(!st.isEmpty() && st.peek()>=a[i])
st.pop();
if(st.size()==0)
res[idx--] = 0;
else
res[idx--] = st.peek();
st.push(a[i]);
}
return res;
}
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
On submission, your code is tested against multiple test cases consisting of all
possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the
correctness of code. On submission, your code is tested against multiple test cases
consisting of all possible corner cases and stress constraints. | [
{
"code": null,
"e": 632,
"s": 238,
"text": "Given array A[] of integers, the task is to complete the function findMaxDiff which finds the maximum absolute difference between nearest left and right smaller element of every element in array.If the element is the leftmost element, nearest smaller element on left side is considered as 0. Similarly if the element is the rightmost elements, smaller element on right side is considered as 0."
},
{
"code": null,
"e": 642,
"s": 632,
"text": "Examples:"
},
{
"code": null,
"e": 1014,
"s": 642,
"text": "Input : arr[] = {2, 1, 8}\nOutput : 1\nLeft smaller LS[] {0, 0, 1}\nRight smaller RS[] {1, 0, 0}\nMaximum Diff of abs(LS[i] - RS[i]) = 1 \n\nInput : arr[] = {2, 4, 8, 7, 7, 9, 3}\nOutput : 4\nLeft smaller LS[] = {0, 2, 4, 4, 4, 7, 2}\nRight smaller RS[] = {0, 3, 7, 3, 3, 3, 0}\nMaximum Diff of abs(LS[i] - RS[i]) = 7 - 3 = 4 \n\nInput : arr[] = {5, 1, 9, 2, 5, 1, 7}\nOutput : 1"
},
{
"code": null,
"e": 1572,
"s": 1014,
"text": "Input:\nThe first line of input contains an integer T denoting the no of test cases. Then T test cases follow .Each test case contains an integer N denoting the size of the array A. In the next line are N space separated values of the array A.\n\nOutput:\nFor each test case output will be in a new line denoting the the maximum absolute difference between nearest left and right smaller element of every element in array.\n\nConstraints:\n1<=T<=100\n1<=N<=100\n1<=A[ ]<=100\n\nExample(To be used only for expected output) :\nInput:\n2\n3\n2 1 8\n7\n2 4 8 7 7 9 3\nOutput\n1\n4"
},
{
"code": null,
"e": 1575,
"s": 1572,
"text": "+1"
},
{
"code": null,
"e": 1600,
"s": 1575,
"text": "sauravmehta8185 days ago"
},
{
"code": null,
"e": 1614,
"s": 1600,
"text": "O(n) Solution"
},
{
"code": null,
"e": 2815,
"s": 1616,
"text": "class Solution\n{\n int findMaxDiff(int arr[], int n)\n {\n int[] output1=leftsmall(arr);\n int[] output2=rightsmall(arr);\n int num=Integer.MIN_VALUE;\n for(int i=0;i<arr.length;i++)\n {\n if(Math.abs(output1[i]-output2[i])>num)\n num=Math.abs(output1[i]-output2[i]);\n }\n return num;\n }\n public int[] leftsmall(int[] arr)\n {\n Stack<Integer> stk=new Stack<>();\n int[] output=new int[arr.length];\n stk.push(arr[0]);\n output[0]=0;\n for(int i=1;i<arr.length;i++)\n {\n while(!stk.empty() && stk.peek()>=arr[i])\n stk.pop();\n output[i]=stk.empty()? 0:stk.peek();\n stk.push(arr[i]);\n }\n return output;\n }\n \n \n public int[] rightsmall(int[] arr)\n {\n Stack<Integer> stk=new Stack<>();\n int[] output=new int[arr.length];\n stk.push(arr[arr.length-1]);\n output[arr.length-1]=0;\n for(int i=arr.length-2;i>=0;i--)\n {\n while(!stk.empty() && stk.peek()>=arr[i])\n stk.pop();\n output[i]=stk.empty()? 0:stk.peek();\n stk.push(arr[i]);\n }\n return output;\n }\n}"
},
{
"code": null,
"e": 2817,
"s": 2815,
"text": "0"
},
{
"code": null,
"e": 2845,
"s": 2817,
"text": "bhavinbansal78652 weeks ago"
},
{
"code": null,
"e": 3768,
"s": 2845,
"text": "int findMaxDiff(int a[], int n) { //Your code here int left[n]; left[0]=0; int k; bool flag; for(int i=1;i<n;i++) { k=i-1; flag=false; while(k>=0) { if(a[i]>a[k]) { left[i]=a[k]; flag=true; break; } k--; } if(flag==false) left[i]=0; } int right[n]; right[n-1]=0; for(int i=n-2;i>=0;i--) { k=i+1; flag=false; while(k<=(n-1)) { if(a[i]>a[k]) { right[i]=a[k]; flag=true; break; } k++; } if(flag==false) right[i]=0; } int res=0; for(int i=0;i<n;i++) { res=max(res,abs(left[i]-right[i])); } return res; }"
},
{
"code": null,
"e": 3770,
"s": 3768,
"text": "0"
},
{
"code": null,
"e": 3788,
"s": 3770,
"text": "rawn963 weeks ago"
},
{
"code": null,
"e": 4298,
"s": 3788,
"text": "\tint findMaxDiff(int a[], int n)\n {\n stack<int> s;\n int ls[n]={0},ans=0;\n for(int i=0;i<n;i++){\n while(!s.empty() && a[s.top()]>a[i]){\n ans=max(ans,abs(ls[s.top()]-a[i]));\n s.pop();\n }\n if(!s.empty())\n ls[i]=a[s.top()]==a[i] ? ls[s.top()] : a[s.top()];\n s.push(i);\n }\n while(!s.empty()){\n ans=max(ans,ls[s.top()]);\n s.pop();\n }\n return ans;\n }"
},
{
"code": null,
"e": 4301,
"s": 4298,
"text": "+1"
},
{
"code": null,
"e": 4325,
"s": 4301,
"text": "ankitmaurya31 month ago"
},
{
"code": null,
"e": 5415,
"s": 4325,
"text": "def nearestleftsmaller(a,n):\n ans = []\n stack = []\n for i in range(n):\n while(len(stack)!=0 and a[i]<=stack[-1]):\n stack.pop()\n if len(stack)==0:\n ans.append(0)\n else:\n ans.append(stack[-1])\n# ans.append(0 if len(stack)==0 else stack[-1])\n stack.append(a[i])\n return ans\n \ndef nearestrightsmaller(a,n):\n ans = [0 for i in range(n)]\n stack = []\n for i in range(n-1,-1,-1):\n while(len(stack)!=0 and a[i]<=stack[-1]):\n stack.pop()\n if len(stack)==0:\n ans[i] = 0\n else:\n ans[i] = stack[-1]\n# ans.append(0 if len(stack)==0 else stack[-1])\n stack.append(a[i])\n return ans\n \n \nclass Solution:\n # Your task is to complete this function\n # Function should return an integer denoting the required answer\n def findMaxDiff(self, a, n):\n nrs = nearestrightsmaller(a,n)\n nls = nearestleftsmaller(a,n)\n res = 0\n for i in range(n):\n res = max(res,abs(nls[i]-nrs[i]))\n return res"
},
{
"code": null,
"e": 5417,
"s": 5415,
"text": "0"
},
{
"code": null,
"e": 5443,
"s": 5417,
"text": "anupamojha31131 month ago"
},
{
"code": null,
"e": 5815,
"s": 5443,
"text": " //Your code here // Time Taken 0.01/1.29 int ans=0; for(int i=0;i<n;i++){ int r=0;int l=0; for(int j=i;j<n;j++){ if(arr[i]>arr[j]){ r=arr[j]; break; } } for(int j=i;j>=0;j--){ if(arr[i]>arr[j]){ l=arr[j]; break; } } ans=max(ans,abs(l-r)); } return ans;"
},
{
"code": null,
"e": 5817,
"s": 5815,
"text": "0"
},
{
"code": null,
"e": 5836,
"s": 5817,
"text": "21mx1261 month ago"
},
{
"code": null,
"e": 5850,
"s": 5836,
"text": "//c++ program"
},
{
"code": null,
"e": 6954,
"s": 5852,
"text": "vector<int> ls(n,0); vector<int> stk; stk.push_back(0); for(int i=0;i<n;i++){ if(A[i]>stk[stk.size()-1]){ ls[i]=stk[stk.size()-1]; stk.push_back(A[i]); }else{ while(A[i]<=stk[stk.size()-1]){ stk.erase(stk.begin()+stk.size()-1); } ls[i]=stk[stk.size()-1]; stk.push_back(A[i]); } } stk.clear(); stk.push_back(0); int res=INT_MIN; for(int i=n-1;i>=0;i--){ if(A[i]>stk[stk.size()-1]){ //cout << stk[stk.size()-1] << \" \"; res = (res > abs(ls[i]-stk[stk.size()-1]) ? res : abs(ls[i]-stk[stk.size()-1])); stk.push_back(A[i]); }else{ while(A[i]<=stk[stk.size()-1]){ stk.erase(stk.begin()+stk.size()-1); } //cout << stk[stk.size()-1] << \" \"; res = (res > abs(ls[i]-stk[stk.size()-1]) ? res : abs(ls[i]-stk[stk.size()-1])); stk.push_back(A[i]); } } return res;"
},
{
"code": null,
"e": 6956,
"s": 6954,
"text": "0"
},
{
"code": null,
"e": 6964,
"s": 6956,
"text": "21mx126"
},
{
"code": null,
"e": 6990,
"s": 6964,
"text": "This comment was deleted."
},
{
"code": null,
"e": 6992,
"s": 6990,
"text": "0"
},
{
"code": null,
"e": 7015,
"s": 6992,
"text": "onlybkm20021 month ago"
},
{
"code": null,
"e": 8030,
"s": 7015,
"text": "int findMaxDiff(int A[], int n)\n {\n stack<int> st1;\n stack<int> st2;\n vector<int> ls(n,0);\n vector<int> rs(n,0);\n for(int i=n-1; i>=0; i--)\n {\n while(!st1.empty() && st1.top()>=A[i])\n {\n st1.pop();\n }\n if(i<n)\n {\n if(!st1.empty())\n {\n rs[i] = st1.top();\n }\n }\n st1.push(A[i]);\n }\n for(int i=0; i<n; i++)\n {\n while(!st2.empty() && st2.top()>=A[i])\n {\n st2.pop();\n }\n if(i<n)\n {\n if(!st2.empty())\n {\n ls[i] = st2.top();\n }\n }\n st2.push(A[i]);\n }\n vector<int> diff(n);\n for(int i=0; i<n; i++)\n {\n diff[i] = abs(ls[i]-rs[i]);\n }\n int maxDiff = INT_MIN;\n for(int i=0; i<n; i++)\n {\n maxDiff = max(maxDiff,diff[i]);\n }\n return maxDiff;\n }"
},
{
"code": null,
"e": 8032,
"s": 8030,
"text": "0"
},
{
"code": null,
"e": 8059,
"s": 8032,
"text": "tooweaktooslow2 months ago"
},
{
"code": null,
"e": 8078,
"s": 8059,
"text": "EASY JAVA SOLUTION"
},
{
"code": null,
"e": 10067,
"s": 8080,
"text": "class Solution{ int findMaxDiff(int arr[], int n) { if(n==1)return 0; Integer[] ls=new Integer[n];//left smaller Integer[] rs=new Integer[n];//right smaller Stack<Integer>st=new Stack<>(); findls(ls,arr,st,n); st=new Stack<>(); findrs(rs,arr,st,n); // System.out.println(Arrays.toString(ls)); int max=Integer.MIN_VALUE; for(int i=0;i<n;i++) { int t=Math.abs(ls[i]-rs[i]); if(t>max)max=t; } return max; } public static void findls(Integer[]ans,int[]arr,Stack<Integer>st,int n) { ans[0]=0; st.push(arr[0]); for(int i=1;i<n;i++) { if(st.size()>0 && st.peek()<arr[i]) { ans[i]=st.peek(); st.push(arr[i]); } else{ if(st.size()==0) { ans[i]=0; st.push(arr[i]); } else{ while(st.size()>0 && st.peek()>=arr[i]) { st.pop(); } if(st.size()==0) { ans[i]=0; st.push(arr[i]); } else{ ans[i]=st.peek(); st.push(arr[i]); } } } } } public static void findrs(Integer[]ans,int[]arr,Stack<Integer>st,int n){ ans[n-1]=0; st.push(arr[n-1]); for(int i=n-2;i>=0;i--) { if(st.peek()<arr[i]) { ans[i]=st.peek(); st.push(arr[i]); } else{ while(st.size()>0 && st.peek()>=arr[i]) { st.pop(); } if(st.size()==0) { ans[i]=0; st.push(arr[i]); }else{ ans[i]=st.peek(); st.push(arr[i]); } } } }}"
},
{
"code": null,
"e": 10069,
"s": 10067,
"text": "0"
},
{
"code": null,
"e": 10100,
"s": 10069,
"text": "shubhankardey29sep2 months ago"
},
{
"code": null,
"e": 11365,
"s": 10100,
"text": "class Solution\n{\n int findMaxDiff(int a[], int n)\n {\n\t// Your code here\t\n\tint []r1 = nsl(a,n);\n\tint []r2 = nsr(a,n);\n\tint max = 0;\n\t\n\tfor(int i=0;i<n;i++)\n\t{\n\t int res = Math.abs(r1[i] - r2[i]);\n\t max = Math.max(max,res);\n\t}\n\treturn max;\n }\n int[] nsl(int []a,int n)\n {\n Stack<Integer> st = new Stack<>();\n int []res = new int[n];\n res[0] = 0;\n st.push(a[0]);\n int idx = 1;\n for(int i=1;i<n;i++)\n {\n while(!st.isEmpty() && st.peek()>=a[i])\n st.pop();\n \n if(st.size()==0)\n res[idx++] = 0;\n \n else\n res[idx++] = st.peek();\n \n st.push(a[i]);\n }\n return res;\n }\n int[] nsr(int []a,int n)\n {\n Stack<Integer> st = new Stack<>();\n int []res = new int[n];\n res[n-1] = 0;\n st.push(a[n-1]);\n int idx = n-2;\n for(int i=n-2;i>=0;i--)\n {\n while(!st.isEmpty() && st.peek()>=a[i])\n st.pop();\n \n if(st.size()==0)\n res[idx--] = 0;\n \n else\n res[idx--] = st.peek();\n \n st.push(a[i]);\n }\n return res;\n }\n}"
},
{
"code": null,
"e": 11511,
"s": 11365,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 11547,
"s": 11511,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 11557,
"s": 11547,
"text": "\nProblem\n"
},
{
"code": null,
"e": 11567,
"s": 11557,
"text": "\nContest\n"
},
{
"code": null,
"e": 11630,
"s": 11567,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 11815,
"s": 11630,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 12099,
"s": 11815,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 12245,
"s": 12099,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 12322,
"s": 12245,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 12363,
"s": 12322,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 12391,
"s": 12363,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 12462,
"s": 12391,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 12649,
"s": 12462,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
Use of min() and max() in Python | 06 Jun, 2021
Prerequisite: min() max() in Python Let’s see some interesting facts about min() and max() function. These functions are used to compute the maximum and minimum of the values as passed in its argument. or it gives the lexicographically largest value and lexicographically smallest value respectively, when we passed string or list of strings as arguments.
python3
l= ["ab", "abc", "abd", "b"] l1="abc" # prints 'b'print(max(l)) # prints 'ab'print(min(l)) #prints 'c'print(max(l1)) #prints 'a'print(min(l1))
Here you notice that output comes according to lexicographical order. but we can also find output according to length of string or as our requirement by simply passing function name or lambda expression. Parameters: By default, min() and max() doesn’t require any extra parameters. however, it has an optional parameters:
key – function that serves as a key for the min/max comparison
Syntax: max(x1, x2, ..., xn, key=function_name)here x1, x2, x3.., xn passed arguments function_name : denotes which type of operation you want to perform on these arguments. Let function_name=len, so now output gives according to length of x1, x2.., xn.
Return value:
It returns a maximum or minimum of list according to the passed parameter.
Python3
# Python code explaining min() and max()l = ["ab", "abc", "bc", "c"] print(max(l, key = len))print(min(l, key = len))
abc
c
Explanation: In the above program, max() function takes two arguments: l(list) and key = len(function_name).this key = len(function_name) function transforms each element before comparing, it takes the value and returns 1 value which is then used within max() or min() instead of the original value.Here key convert each element of the list to its length and then compare each element according to its length.
initially l = [“ab”, “abc”, “bc”, “c”] when we passed key=len as arguments then it works like l=[2,3,2,1]
Python3
# Python code explaining min() and max()def fun(element): return(len(element)) l =["ab", "abc", "bc", "c"]print(max(l, key = fun)) # you can also write in this formprint(max(l, key = lambda element:len(element)))
abc
abc
Another example:
Python3
# Python code explaining min() and max()l = [{'name':'ramu', 'score':90, 'age':24}, {'name':'golu', 'score':70, 'age':19}] # here anonymous function takes item as an argument.print(max(l, key = lambda item:item.get('age')))
{'age': 24, 'score': 90, 'name': 'ramu'}
Similar we can use min() function instead of max() function as per requirement.
rrlinus
Akanksha_Rai
simmytarika5
Python function-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jun, 2021"
},
{
"code": null,
"e": 409,
"s": 52,
"text": "Prerequisite: min() max() in Python Let’s see some interesting facts about min() and max() function. These functions are used to compute the maximum and minimum of the values as passed in its argument. or it gives the lexicographically largest value and lexicographically smallest value respectively, when we passed string or list of strings as arguments. "
},
{
"code": null,
"e": 417,
"s": 409,
"text": "python3"
},
{
"code": "l= [\"ab\", \"abc\", \"abd\", \"b\"] l1=\"abc\" # prints 'b'print(max(l)) # prints 'ab'print(min(l)) #prints 'c'print(max(l1)) #prints 'a'print(min(l1))",
"e": 560,
"s": 417,
"text": null
},
{
"code": null,
"e": 883,
"s": 560,
"text": "Here you notice that output comes according to lexicographical order. but we can also find output according to length of string or as our requirement by simply passing function name or lambda expression. Parameters: By default, min() and max() doesn’t require any extra parameters. however, it has an optional parameters: "
},
{
"code": null,
"e": 947,
"s": 883,
"text": "key – function that serves as a key for the min/max comparison "
},
{
"code": null,
"e": 1205,
"s": 949,
"text": "Syntax: max(x1, x2, ..., xn, key=function_name)here x1, x2, x3.., xn passed arguments function_name : denotes which type of operation you want to perform on these arguments. Let function_name=len, so now output gives according to length of x1, x2.., xn. "
},
{
"code": null,
"e": 1221,
"s": 1205,
"text": "Return value: "
},
{
"code": null,
"e": 1296,
"s": 1221,
"text": "It returns a maximum or minimum of list according to the passed parameter."
},
{
"code": null,
"e": 1306,
"s": 1298,
"text": "Python3"
},
{
"code": "# Python code explaining min() and max()l = [\"ab\", \"abc\", \"bc\", \"c\"] print(max(l, key = len))print(min(l, key = len))",
"e": 1424,
"s": 1306,
"text": null
},
{
"code": null,
"e": 1430,
"s": 1424,
"text": "abc\nc"
},
{
"code": null,
"e": 1843,
"s": 1432,
"text": "Explanation: In the above program, max() function takes two arguments: l(list) and key = len(function_name).this key = len(function_name) function transforms each element before comparing, it takes the value and returns 1 value which is then used within max() or min() instead of the original value.Here key convert each element of the list to its length and then compare each element according to its length. "
},
{
"code": null,
"e": 1950,
"s": 1843,
"text": "initially l = [“ab”, “abc”, “bc”, “c”] when we passed key=len as arguments then it works like l=[2,3,2,1] "
},
{
"code": null,
"e": 1962,
"s": 1954,
"text": "Python3"
},
{
"code": "# Python code explaining min() and max()def fun(element): return(len(element)) l =[\"ab\", \"abc\", \"bc\", \"c\"]print(max(l, key = fun)) # you can also write in this formprint(max(l, key = lambda element:len(element)))",
"e": 2178,
"s": 1962,
"text": null
},
{
"code": null,
"e": 2186,
"s": 2178,
"text": "abc\nabc"
},
{
"code": null,
"e": 2207,
"s": 2188,
"text": "Another example: "
},
{
"code": null,
"e": 2215,
"s": 2207,
"text": "Python3"
},
{
"code": "# Python code explaining min() and max()l = [{'name':'ramu', 'score':90, 'age':24}, {'name':'golu', 'score':70, 'age':19}] # here anonymous function takes item as an argument.print(max(l, key = lambda item:item.get('age')))",
"e": 2443,
"s": 2215,
"text": null
},
{
"code": null,
"e": 2484,
"s": 2443,
"text": "{'age': 24, 'score': 90, 'name': 'ramu'}"
},
{
"code": null,
"e": 2567,
"s": 2486,
"text": "Similar we can use min() function instead of max() function as per requirement. "
},
{
"code": null,
"e": 2575,
"s": 2567,
"text": "rrlinus"
},
{
"code": null,
"e": 2588,
"s": 2575,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 2601,
"s": 2588,
"text": "simmytarika5"
},
{
"code": null,
"e": 2626,
"s": 2601,
"text": "Python function-programs"
},
{
"code": null,
"e": 2633,
"s": 2626,
"text": "Python"
},
{
"code": null,
"e": 2731,
"s": 2633,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2749,
"s": 2731,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2791,
"s": 2749,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2813,
"s": 2791,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2839,
"s": 2813,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2871,
"s": 2839,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2900,
"s": 2871,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2927,
"s": 2900,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2948,
"s": 2927,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2984,
"s": 2948,
"text": "Convert integer to string in Python"
}
] |
Modify given array to make sum of odd and even indexed elements same | 10 Sep, 2021
Given a binary array arr[] of size N, remove at most N/2 elements from the array such that the sum of elements at odd and even indices becomes equal. The task is to print the modified array.Note: N is always even. There can be more than one possible result, print any of them.
Examples:
Input: arr[] = {1, 1, 1, 0}Output: 1 1Explanation:For the given array arr[] = {1, 1, 1, 0}The sum of elements at odd position, Odd_Sum = arr[1] + arr[3] = 1 + 1 = 2.The sum of elements at even position, Even_Sum = arr[2] + arr[4] = 1 + 0 = 1.Since Odd_Sum & Even_Sum are not equal, remove some elements to make them equal.After removing arr[3] and arr[4] the array become arr[] = {1, 1} such that sum of elements at odd indices and even indices are equal.
Input: arr[] = {1, 0}Output: 0Explanation:For the given array arr[] = {1, 0}The sum of elements at odd position, Odd_Sum = arr[1] = 0 = 0.The sum of elements at even position, Even_Sum = 1 = 1.Since Odd_Sum & Even_Sum are not equal, remove some elements to make them equal.After removing arr[0] the array become arr[] = {0} such that sum of elements at odd indices and even indices are equal.
Approach: The idea is to count the number of 1s and 0s in the given array and then make the resultant sum equal by the following steps:
Count the number of 0s and 1s in the given array arr[] and store them in variables say count_0 and count_1 respectively.If the sum of the elements at odd and even indices are equal, then no need to remove any array element. Print the original array as the answer.If count_0 ≥ N/2, then remove all 1s and print all the zeros count_0 number of times.Otherwise, if count_0 < N/2, by removing all the 0s, the sum of even and odd indices can be made the same as per the following conditions: If count_1 is odd, then print 1 as an element of the new array (count_1 – 1) number of times.Otherwise, print 1 as an element of the new array count_1 number of times.Print the resultant array as per the above conditions.
Count the number of 0s and 1s in the given array arr[] and store them in variables say count_0 and count_1 respectively.
If the sum of the elements at odd and even indices are equal, then no need to remove any array element. Print the original array as the answer.
If count_0 ≥ N/2, then remove all 1s and print all the zeros count_0 number of times.
Otherwise, if count_0 < N/2, by removing all the 0s, the sum of even and odd indices can be made the same as per the following conditions: If count_1 is odd, then print 1 as an element of the new array (count_1 – 1) number of times.Otherwise, print 1 as an element of the new array count_1 number of times.
If count_1 is odd, then print 1 as an element of the new array (count_1 – 1) number of times.
Otherwise, print 1 as an element of the new array count_1 number of times.
Print the resultant array as per the above conditions.
Below is the implementation of the above approach:
C++
C
Java
Python3
C#
Javascript
// C++ program for the above approach#include <iostream>using namespace std; // Function to modify array to make// sum of odd and even indexed// elements equalvoid makeArraySumEqual(int a[], int N){ // Stores the count of 0s, 1s int count_0 = 0, count_1 = 0; // Stores sum of odd and even // indexed elements respectively int odd_sum = 0, even_sum = 0; for (int i = 0; i < N; i++) { // Count 0s if (a[i] == 0) count_0++; // Count 1s else count_1++; // Calculate odd_sum and even_sum if ((i + 1) % 2 == 0) even_sum += a[i]; else if ((i + 1) % 2 > 0) odd_sum += a[i]; } // If both are equal if (odd_sum == even_sum) { // Print the original array for (int i = 0; i < N; i++) cout <<" "<< a[i]; } // Otherwise else { if (count_0 >= N / 2) { // Print all the 0s for (int i = 0; i < count_0; i++) cout <<"0 "; } else { // For checking even or odd int is_Odd = count_1 % 2; // Update total count of 1s count_1 -= is_Odd; // Print all 1s for (int i = 0; i < count_1; i++) cout <<"1 "; } }} // Driver Codeint main(){ // Given array arr[] int arr[] = { 1, 1, 1, 0 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call makeArraySumEqual(arr, N); return 0;} // This code is contributed by shivanisinghss2110.
// C++ program for the above approach #include <stdio.h> // Function to modify array to make// sum of odd and even indexed// elements equalvoid makeArraySumEqual(int a[], int N){ // Stores the count of 0s, 1s int count_0 = 0, count_1 = 0; // Stores sum of odd and even // indexed elements respectively int odd_sum = 0, even_sum = 0; for (int i = 0; i < N; i++) { // Count 0s if (a[i] == 0) count_0++; // Count 1s else count_1++; // Calculate odd_sum and even_sum if ((i + 1) % 2 == 0) even_sum += a[i]; else if ((i + 1) % 2 > 0) odd_sum += a[i]; } // If both are equal if (odd_sum == even_sum) { // Print the original array for (int i = 0; i < N; i++) printf("%d ", a[i]); } // Otherwise else { if (count_0 >= N / 2) { // Print all the 0s for (int i = 0; i < count_0; i++) printf("0 "); } else { // For checking even or odd int is_Odd = count_1 % 2; // Update total count of 1s count_1 -= is_Odd; // Print all 1s for (int i = 0; i < count_1; i++) printf("1 "); } }} // Driver Codeint main(){ // Given array arr[] int arr[] = { 1, 1, 1, 0 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call makeArraySumEqual(arr, N); return 0;}
// Java program for the above approach class GFG { // Function to modify array to make // sum of odd and even indexed // elements equal static void makeArraySumEqual(int a[], int N) { // Stores the count of 0s, 1s int count_0 = 0, count_1 = 0; // Stores sum of odd and even // indexed elements respectively int odd_sum = 0, even_sum = 0; for (int i = 0; i < N; i++) { // Count 0s if (a[i] == 0) count_0++; // Count 1s else count_1++; // Calculate odd_sum and even_sum if ((i + 1) % 2 == 0) even_sum += a[i]; else if ((i + 1) % 2 > 0) odd_sum += a[i]; } // If both are equal if (odd_sum == even_sum) { // Print the original array for (int i = 0; i < N; i++) System.out.print(a[i] + " "); } else { if (count_0 >= N / 2) { // Print all the 0s for (int i = 0; i < count_0; i++) System.out.print("0 "); } else { // For checking even or odd int is_Odd = count_1 % 2; // Update total count of 1s count_1 -= is_Odd; // Print all 1s for (int i = 0; i < count_1; i++) System.out.print("1 "); } } } // Driver Code public static void main(String[] args) { // Given array arr[] int arr[] = { 1, 1, 1, 0 }; int N = arr.length; // Function Call makeArraySumEqual(arr, N); }}
# Python3 program for the above approach # Function to modify array to make# sum of odd and even indexed# elements equaldef makeArraySumEqual(a, N): # Stores the count of 0s, 1s count_0 = 0 count_1 = 0 # Stores sum of odd and even # indexed elements respectively odd_sum = 0 even_sum = 0 for i in range(N): # Count 0s if (a[i] == 0): count_0 += 1 # Count 1s else: count_1 += 1 # Calculate odd_sum and even_sum if ((i + 1) % 2 == 0): even_sum += a[i] elif ((i + 1) % 2 > 0): odd_sum += a[i] # If both are equal if (odd_sum == even_sum): # Print the original array for i in range(N): print(a[i], end = " ") # Otherwise else: if (count_0 >= N / 2): # Print all the 0s for i in range(count_0): print("0", end = " ") else: # For checking even or odd is_Odd = count_1 % 2 # Update total count of 1s count_1 -= is_Odd # Print all 1s for i in range(count_1): print("1", end = " ") # Driver Code # Given array arr[]arr = [ 1, 1, 1, 0 ] N = len(arr) # Function callmakeArraySumEqual(arr, N) # This code is contributed by code_hunt
// C# program for// the above approachusing System;class GFG{ // Function to modify array to make// sum of odd and even indexed// elements equalstatic void makeArraySumEqual(int []a, int N){ // Stores the count of 0s, 1s int count_0 = 0, count_1 = 0; // Stores sum of odd and even // indexed elements respectively int odd_sum = 0, even_sum = 0; for (int i = 0; i < N; i++) { // Count 0s if (a[i] == 0) count_0++; // Count 1s else count_1++; // Calculate odd_sum and even_sum if ((i + 1) % 2 == 0) even_sum += a[i]; else if ((i + 1) % 2 > 0) odd_sum += a[i]; } // If both are equal if (odd_sum == even_sum) { // Print the original array for (int i = 0; i < N; i++) Console.Write(a[i] + " "); } else { if (count_0 >= N / 2) { // Print all the 0s for (int i = 0; i < count_0; i++) Console.Write("0 "); } else { // For checking even or odd int is_Odd = count_1 % 2; // Update total count of 1s count_1 -= is_Odd; // Print all 1s for (int i = 0; i < count_1; i++) Console.Write("1 "); } }} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []arr = {1, 1, 1, 0}; int N = arr.Length; // Function Call makeArraySumEqual(arr, N);}} // This code is contributed by 29AjayKumar
<script> // Javascript program to implement// the above approach // Function to modify array to make // sum of odd and even indexed // elements equal function makeArraySumEqual(a, N) { // Stores the count of 0s, 1s let count_0 = 0, count_1 = 0; // Stores sum of odd and even // indexed elements respectively let odd_sum = 0, even_sum = 0; for (let i = 0; i < N; i++) { // Count 0s if (a[i] == 0) count_0++; // Count 1s else count_1++; // Calculate odd_sum and even_sum if ((i + 1) % 2 == 0) even_sum += a[i]; else if ((i + 1) % 2 > 0) odd_sum += a[i]; } // If both are equal if (odd_sum == even_sum) { // Print the original array for (let i = 0; i < N; i++) document.write(a[i] + " "); } else { if (count_0 >= N / 2) { // Print all the 0s for (let i = 0; i < count_0; i++) document.write("0 "); } else { // For checking even or odd let is_Odd = count_1 % 2; // Update total count of 1s count_1 -= is_Odd; // Print all 1s for (let i = 0; i < count_1; i++) document.write("1 "); } } } // Driver Code // Given array arr[] let arr = [ 1, 1, 1, 0 ]; let N = arr.length; // Function Call makeArraySumEqual(arr, N); </script>
1 1
Time Complexity: O(N)Auxiliary Space: O(1)
aimformohan
29AjayKumar
code_hunt
avijitmondal1998
khushboogoyal499
shivanisinghss2110
array-rearrange
Arrays
Greedy
Mathematical
Arrays
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n10 Sep, 2021"
},
{
"code": null,
"e": 331,
"s": 54,
"text": "Given a binary array arr[] of size N, remove at most N/2 elements from the array such that the sum of elements at odd and even indices becomes equal. The task is to print the modified array.Note: N is always even. There can be more than one possible result, print any of them."
},
{
"code": null,
"e": 342,
"s": 331,
"text": "Examples: "
},
{
"code": null,
"e": 798,
"s": 342,
"text": "Input: arr[] = {1, 1, 1, 0}Output: 1 1Explanation:For the given array arr[] = {1, 1, 1, 0}The sum of elements at odd position, Odd_Sum = arr[1] + arr[3] = 1 + 1 = 2.The sum of elements at even position, Even_Sum = arr[2] + arr[4] = 1 + 0 = 1.Since Odd_Sum & Even_Sum are not equal, remove some elements to make them equal.After removing arr[3] and arr[4] the array become arr[] = {1, 1} such that sum of elements at odd indices and even indices are equal."
},
{
"code": null,
"e": 1191,
"s": 798,
"text": "Input: arr[] = {1, 0}Output: 0Explanation:For the given array arr[] = {1, 0}The sum of elements at odd position, Odd_Sum = arr[1] = 0 = 0.The sum of elements at even position, Even_Sum = 1 = 1.Since Odd_Sum & Even_Sum are not equal, remove some elements to make them equal.After removing arr[0] the array become arr[] = {0} such that sum of elements at odd indices and even indices are equal."
},
{
"code": null,
"e": 1328,
"s": 1191,
"text": "Approach: The idea is to count the number of 1s and 0s in the given array and then make the resultant sum equal by the following steps: "
},
{
"code": null,
"e": 2037,
"s": 1328,
"text": "Count the number of 0s and 1s in the given array arr[] and store them in variables say count_0 and count_1 respectively.If the sum of the elements at odd and even indices are equal, then no need to remove any array element. Print the original array as the answer.If count_0 ≥ N/2, then remove all 1s and print all the zeros count_0 number of times.Otherwise, if count_0 < N/2, by removing all the 0s, the sum of even and odd indices can be made the same as per the following conditions: If count_1 is odd, then print 1 as an element of the new array (count_1 – 1) number of times.Otherwise, print 1 as an element of the new array count_1 number of times.Print the resultant array as per the above conditions."
},
{
"code": null,
"e": 2158,
"s": 2037,
"text": "Count the number of 0s and 1s in the given array arr[] and store them in variables say count_0 and count_1 respectively."
},
{
"code": null,
"e": 2302,
"s": 2158,
"text": "If the sum of the elements at odd and even indices are equal, then no need to remove any array element. Print the original array as the answer."
},
{
"code": null,
"e": 2388,
"s": 2302,
"text": "If count_0 ≥ N/2, then remove all 1s and print all the zeros count_0 number of times."
},
{
"code": null,
"e": 2695,
"s": 2388,
"text": "Otherwise, if count_0 < N/2, by removing all the 0s, the sum of even and odd indices can be made the same as per the following conditions: If count_1 is odd, then print 1 as an element of the new array (count_1 – 1) number of times.Otherwise, print 1 as an element of the new array count_1 number of times."
},
{
"code": null,
"e": 2789,
"s": 2695,
"text": "If count_1 is odd, then print 1 as an element of the new array (count_1 – 1) number of times."
},
{
"code": null,
"e": 2864,
"s": 2789,
"text": "Otherwise, print 1 as an element of the new array count_1 number of times."
},
{
"code": null,
"e": 2919,
"s": 2864,
"text": "Print the resultant array as per the above conditions."
},
{
"code": null,
"e": 2970,
"s": 2919,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2974,
"s": 2970,
"text": "C++"
},
{
"code": null,
"e": 2976,
"s": 2974,
"text": "C"
},
{
"code": null,
"e": 2981,
"s": 2976,
"text": "Java"
},
{
"code": null,
"e": 2989,
"s": 2981,
"text": "Python3"
},
{
"code": null,
"e": 2992,
"s": 2989,
"text": "C#"
},
{
"code": null,
"e": 3003,
"s": 2992,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <iostream>using namespace std; // Function to modify array to make// sum of odd and even indexed// elements equalvoid makeArraySumEqual(int a[], int N){ // Stores the count of 0s, 1s int count_0 = 0, count_1 = 0; // Stores sum of odd and even // indexed elements respectively int odd_sum = 0, even_sum = 0; for (int i = 0; i < N; i++) { // Count 0s if (a[i] == 0) count_0++; // Count 1s else count_1++; // Calculate odd_sum and even_sum if ((i + 1) % 2 == 0) even_sum += a[i]; else if ((i + 1) % 2 > 0) odd_sum += a[i]; } // If both are equal if (odd_sum == even_sum) { // Print the original array for (int i = 0; i < N; i++) cout <<\" \"<< a[i]; } // Otherwise else { if (count_0 >= N / 2) { // Print all the 0s for (int i = 0; i < count_0; i++) cout <<\"0 \"; } else { // For checking even or odd int is_Odd = count_1 % 2; // Update total count of 1s count_1 -= is_Odd; // Print all 1s for (int i = 0; i < count_1; i++) cout <<\"1 \"; } }} // Driver Codeint main(){ // Given array arr[] int arr[] = { 1, 1, 1, 0 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call makeArraySumEqual(arr, N); return 0;} // This code is contributed by shivanisinghss2110.",
"e": 4545,
"s": 3003,
"text": null
},
{
"code": "// C++ program for the above approach #include <stdio.h> // Function to modify array to make// sum of odd and even indexed// elements equalvoid makeArraySumEqual(int a[], int N){ // Stores the count of 0s, 1s int count_0 = 0, count_1 = 0; // Stores sum of odd and even // indexed elements respectively int odd_sum = 0, even_sum = 0; for (int i = 0; i < N; i++) { // Count 0s if (a[i] == 0) count_0++; // Count 1s else count_1++; // Calculate odd_sum and even_sum if ((i + 1) % 2 == 0) even_sum += a[i]; else if ((i + 1) % 2 > 0) odd_sum += a[i]; } // If both are equal if (odd_sum == even_sum) { // Print the original array for (int i = 0; i < N; i++) printf(\"%d \", a[i]); } // Otherwise else { if (count_0 >= N / 2) { // Print all the 0s for (int i = 0; i < count_0; i++) printf(\"0 \"); } else { // For checking even or odd int is_Odd = count_1 % 2; // Update total count of 1s count_1 -= is_Odd; // Print all 1s for (int i = 0; i < count_1; i++) printf(\"1 \"); } }} // Driver Codeint main(){ // Given array arr[] int arr[] = { 1, 1, 1, 0 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call makeArraySumEqual(arr, N); return 0;}",
"e": 6017,
"s": 4545,
"text": null
},
{
"code": "// Java program for the above approach class GFG { // Function to modify array to make // sum of odd and even indexed // elements equal static void makeArraySumEqual(int a[], int N) { // Stores the count of 0s, 1s int count_0 = 0, count_1 = 0; // Stores sum of odd and even // indexed elements respectively int odd_sum = 0, even_sum = 0; for (int i = 0; i < N; i++) { // Count 0s if (a[i] == 0) count_0++; // Count 1s else count_1++; // Calculate odd_sum and even_sum if ((i + 1) % 2 == 0) even_sum += a[i]; else if ((i + 1) % 2 > 0) odd_sum += a[i]; } // If both are equal if (odd_sum == even_sum) { // Print the original array for (int i = 0; i < N; i++) System.out.print(a[i] + \" \"); } else { if (count_0 >= N / 2) { // Print all the 0s for (int i = 0; i < count_0; i++) System.out.print(\"0 \"); } else { // For checking even or odd int is_Odd = count_1 % 2; // Update total count of 1s count_1 -= is_Odd; // Print all 1s for (int i = 0; i < count_1; i++) System.out.print(\"1 \"); } } } // Driver Code public static void main(String[] args) { // Given array arr[] int arr[] = { 1, 1, 1, 0 }; int N = arr.length; // Function Call makeArraySumEqual(arr, N); }}",
"e": 7727,
"s": 6017,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to modify array to make# sum of odd and even indexed# elements equaldef makeArraySumEqual(a, N): # Stores the count of 0s, 1s count_0 = 0 count_1 = 0 # Stores sum of odd and even # indexed elements respectively odd_sum = 0 even_sum = 0 for i in range(N): # Count 0s if (a[i] == 0): count_0 += 1 # Count 1s else: count_1 += 1 # Calculate odd_sum and even_sum if ((i + 1) % 2 == 0): even_sum += a[i] elif ((i + 1) % 2 > 0): odd_sum += a[i] # If both are equal if (odd_sum == even_sum): # Print the original array for i in range(N): print(a[i], end = \" \") # Otherwise else: if (count_0 >= N / 2): # Print all the 0s for i in range(count_0): print(\"0\", end = \" \") else: # For checking even or odd is_Odd = count_1 % 2 # Update total count of 1s count_1 -= is_Odd # Print all 1s for i in range(count_1): print(\"1\", end = \" \") # Driver Code # Given array arr[]arr = [ 1, 1, 1, 0 ] N = len(arr) # Function callmakeArraySumEqual(arr, N) # This code is contributed by code_hunt",
"e": 9091,
"s": 7727,
"text": null
},
{
"code": "// C# program for// the above approachusing System;class GFG{ // Function to modify array to make// sum of odd and even indexed// elements equalstatic void makeArraySumEqual(int []a, int N){ // Stores the count of 0s, 1s int count_0 = 0, count_1 = 0; // Stores sum of odd and even // indexed elements respectively int odd_sum = 0, even_sum = 0; for (int i = 0; i < N; i++) { // Count 0s if (a[i] == 0) count_0++; // Count 1s else count_1++; // Calculate odd_sum and even_sum if ((i + 1) % 2 == 0) even_sum += a[i]; else if ((i + 1) % 2 > 0) odd_sum += a[i]; } // If both are equal if (odd_sum == even_sum) { // Print the original array for (int i = 0; i < N; i++) Console.Write(a[i] + \" \"); } else { if (count_0 >= N / 2) { // Print all the 0s for (int i = 0; i < count_0; i++) Console.Write(\"0 \"); } else { // For checking even or odd int is_Odd = count_1 % 2; // Update total count of 1s count_1 -= is_Odd; // Print all 1s for (int i = 0; i < count_1; i++) Console.Write(\"1 \"); } }} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []arr = {1, 1, 1, 0}; int N = arr.Length; // Function Call makeArraySumEqual(arr, N);}} // This code is contributed by 29AjayKumar",
"e": 10469,
"s": 9091,
"text": null
},
{
"code": "<script> // Javascript program to implement// the above approach // Function to modify array to make // sum of odd and even indexed // elements equal function makeArraySumEqual(a, N) { // Stores the count of 0s, 1s let count_0 = 0, count_1 = 0; // Stores sum of odd and even // indexed elements respectively let odd_sum = 0, even_sum = 0; for (let i = 0; i < N; i++) { // Count 0s if (a[i] == 0) count_0++; // Count 1s else count_1++; // Calculate odd_sum and even_sum if ((i + 1) % 2 == 0) even_sum += a[i]; else if ((i + 1) % 2 > 0) odd_sum += a[i]; } // If both are equal if (odd_sum == even_sum) { // Print the original array for (let i = 0; i < N; i++) document.write(a[i] + \" \"); } else { if (count_0 >= N / 2) { // Print all the 0s for (let i = 0; i < count_0; i++) document.write(\"0 \"); } else { // For checking even or odd let is_Odd = count_1 % 2; // Update total count of 1s count_1 -= is_Odd; // Print all 1s for (let i = 0; i < count_1; i++) document.write(\"1 \"); } } } // Driver Code // Given array arr[] let arr = [ 1, 1, 1, 0 ]; let N = arr.length; // Function Call makeArraySumEqual(arr, N); </script>",
"e": 12152,
"s": 10469,
"text": null
},
{
"code": null,
"e": 12156,
"s": 12152,
"text": "1 1"
},
{
"code": null,
"e": 12201,
"s": 12158,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 12213,
"s": 12201,
"text": "aimformohan"
},
{
"code": null,
"e": 12225,
"s": 12213,
"text": "29AjayKumar"
},
{
"code": null,
"e": 12235,
"s": 12225,
"text": "code_hunt"
},
{
"code": null,
"e": 12252,
"s": 12235,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 12269,
"s": 12252,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 12288,
"s": 12269,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 12304,
"s": 12288,
"text": "array-rearrange"
},
{
"code": null,
"e": 12311,
"s": 12304,
"text": "Arrays"
},
{
"code": null,
"e": 12318,
"s": 12311,
"text": "Greedy"
},
{
"code": null,
"e": 12331,
"s": 12318,
"text": "Mathematical"
},
{
"code": null,
"e": 12338,
"s": 12331,
"text": "Arrays"
},
{
"code": null,
"e": 12345,
"s": 12338,
"text": "Greedy"
},
{
"code": null,
"e": 12358,
"s": 12345,
"text": "Mathematical"
}
] |
Introduction to Vaex in Python | 14 Sep, 2021
Working on Big Data has become very common today, So we require some libraries which can facilitate us to work on big data from our systems (i.e., desktops, laptops) with instantaneous execution of Code and low memory usage.
Vaex is a Python library which helps us achieve that and makes working with large datasets super easy. It is especially for lazy Out-of-Core DataFrames (similar to Pandas). It can visualize, explore, perform computations on big tabular datasets swiftly and with minimal memory usage.
Using Conda:
conda install -c conda-forge vaex
Using pip:
pip install --upgrade vaex
Vaex helps us work with large datasets efficiently and swiftly by lazy computations, virtual columns, memory-mapping, zero memory copy policy, efficient data cleansing, etc. Vaex has efficient algorithms and it emphasizes aggregate data properties instead of looking at individual samples. It is able to overcome several shortcomings of other libraries (like:- pandas). So, Let’s Explore Vaex:-
For large tabular data, the reading performance of Vaex is much faster than pandas. Let’s analyze by importing same size dataset with both libraries. Link to the dataset
Reading Performance of Pandas:
Python3
import pandas as pd%time df_pandas = pd.read_csv("dataset1.csv")
Output:
Wall time: 1min 8s
Reading Performance of Vaex: (We read dataset in Vaex using vaex.open)
Python3
import vaex%time df_vaex = vaex.open("dataset1.csv.hdf5")
Output:
Wall time: 1.34 s
Vaex took very little time to read the same size dataset as compared to pandas:
Python3
print("Size =")print(df_pandas.shape)print(df_vaex.shape)
Output:
Size =
12852000, 36
12852000, 36
Vaex uses a lazy computation technique (i.e., compute on the fly without wasting RAM). In this technique, Vaex does not do the complete calculations, instead, it creates a Vaex expression, and when printed out it shows some preview values. So Vaex performs calculations only when needed else it stores the expression. This makes the computation speed of Vaex exceptionally fast. Let’s Perform an example on a simple computation:
Pandas DataFrame:
Python3
%time df_pandas['column2'] + df_pandas['column3']
Output:
Vaex DataFrame:
Python3
%time df_vaex.column2 + df_vaex.column3
Output:
Vaex can calculate statistics such as mean, sum, count, standard deviation, etc., on an N-dimensional grid up to a billion (109) objects/rows per second. So, Let’s Compare the performance of pandas and Vaex while computing statistics:-
Pandas Dataframe:
Python3
%time df_pandas["column3"].mean()
Output:
Wall time: 741 ms
49.49811570183629
Vaex DataFrame:
Python3
%time df_vaex.mean(df_vaex.column3)
Output:
Wall time: 347 ms
array(49.4981157)
Unlike Pandas, No copies of memory are created in Vaex during data filtering, selections, subsets, cleansing. Let’s take the case of data filtering, in achieving this task Vaex uses very little memory as no memory copying is done in Vaex. and the time for execution is also minimal.
Pandas:
Python3
%time df_pandas_filtered = df_pandas[df_pandas['column5'] > 1]
Output:
Wall time: 24.1 s
Vaex:
Python3
%time df_vaex_filtered = df_vaex[df_vaex['column5'] > 1]
Output:
Wall time: 91.4 ms
Here data filtering results in a reference to the existing data with a boolean mask which keeps track of selected rows and non-selected rows. Vaex performs multiple computations in single pass over the data:-
Python3
df_vaex.select(df_vaex.column4 < 20, name='less_than')df_vaex.select(df_vaex.column4 >= 20, name='gr_than') %time df_vaex.mean(df_vaex.column4, selection=['less_than', 'gr_than'])
Output:
Wall time: 128 ms
array([ 9.4940431, 59.49137605])
When we create a new column by adding expression to a DataFrame, Virtual columns are created. These columns are just like regular columns but occupy no memory and just stores the expression that defines them. This makes the task very fast and reduces the wastage of RAM. And Vaex makes no distinction between regular or virtual columns.
Python3
%time df_vaex['new_col'] = df_vaex['column3']**2df_vaex.mean(df_vaex['new_col'])
Output:
Vaex provides a faster alternative to pandas’s groupby as ‘binby’ which can calculate statistics on a regular N-dimensional grid swiftly in regular bins.
Python3
%time df_vaex.count(binby=df_vaex.column7, limits=[0, 20], shape=10)
Output:
Visualization of the large dataset is a tedious task. But Vaex can compute these visualizations pretty quickly. The dataset gives a better idea of data distribution when computed in bins and Vaex excels in group aggregate properties, selections, and bins. So, Vaex is able to visualize swiftly and interactively. By Vaex, visualizations can be done even in 3-dimensions on large datasets.Let’s plot a simple 1-dimensional graph:
Python3
%time df_vaex.viz.histogram(df_vaex.column1, limits = [0, 20])
Output:
Python
df_vaex.viz.heatmap(df_vaex.column7, df_vaex.column8 + df_vaex.column9, limits=[-3, 20])
Output:
We can add statistics expression and visualize by passing the “what=<statistic>(<expression>)” argument. So let’s perform a slightly complicated visualization:
Python3
df_vaex.viz.heatmap(df_vaex.column1, df_vaex.column2, what=(vaex.stat.mean(df_vaex.column4) / vaex.stat.std(df_vaex.column4)), limits='99.7%')
Output:
Here, the ‘vaex.stat.<statistic>’ objects are very similar to Vaex expressions, which represent an underlying calculation, and also we can apply typical arithmetic and Numpy functions to these calculations.
Blogathon-2021
python-modules
Blogathon
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Import JSON Data into SQL Server?
SQL Query to Convert Datetime to Date
Scrape LinkedIn Using Selenium And Beautiful Soup in Python
Python program to convert XML to Dictionary
Shared ViewModel in Android
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 279,
"s": 54,
"text": "Working on Big Data has become very common today, So we require some libraries which can facilitate us to work on big data from our systems (i.e., desktops, laptops) with instantaneous execution of Code and low memory usage."
},
{
"code": null,
"e": 563,
"s": 279,
"text": "Vaex is a Python library which helps us achieve that and makes working with large datasets super easy. It is especially for lazy Out-of-Core DataFrames (similar to Pandas). It can visualize, explore, perform computations on big tabular datasets swiftly and with minimal memory usage."
},
{
"code": null,
"e": 576,
"s": 563,
"text": "Using Conda:"
},
{
"code": null,
"e": 610,
"s": 576,
"text": "conda install -c conda-forge vaex"
},
{
"code": null,
"e": 621,
"s": 610,
"text": "Using pip:"
},
{
"code": null,
"e": 648,
"s": 621,
"text": "pip install --upgrade vaex"
},
{
"code": null,
"e": 1043,
"s": 648,
"text": "Vaex helps us work with large datasets efficiently and swiftly by lazy computations, virtual columns, memory-mapping, zero memory copy policy, efficient data cleansing, etc. Vaex has efficient algorithms and it emphasizes aggregate data properties instead of looking at individual samples. It is able to overcome several shortcomings of other libraries (like:- pandas). So, Let’s Explore Vaex:-"
},
{
"code": null,
"e": 1213,
"s": 1043,
"text": "For large tabular data, the reading performance of Vaex is much faster than pandas. Let’s analyze by importing same size dataset with both libraries. Link to the dataset"
},
{
"code": null,
"e": 1244,
"s": 1213,
"text": "Reading Performance of Pandas:"
},
{
"code": null,
"e": 1252,
"s": 1244,
"text": "Python3"
},
{
"code": "import pandas as pd%time df_pandas = pd.read_csv(\"dataset1.csv\")",
"e": 1317,
"s": 1252,
"text": null
},
{
"code": null,
"e": 1325,
"s": 1317,
"text": "Output:"
},
{
"code": null,
"e": 1344,
"s": 1325,
"text": "Wall time: 1min 8s"
},
{
"code": null,
"e": 1415,
"s": 1344,
"text": "Reading Performance of Vaex: (We read dataset in Vaex using vaex.open)"
},
{
"code": null,
"e": 1423,
"s": 1415,
"text": "Python3"
},
{
"code": "import vaex%time df_vaex = vaex.open(\"dataset1.csv.hdf5\")",
"e": 1481,
"s": 1423,
"text": null
},
{
"code": null,
"e": 1489,
"s": 1481,
"text": "Output:"
},
{
"code": null,
"e": 1507,
"s": 1489,
"text": "Wall time: 1.34 s"
},
{
"code": null,
"e": 1587,
"s": 1507,
"text": "Vaex took very little time to read the same size dataset as compared to pandas:"
},
{
"code": null,
"e": 1595,
"s": 1587,
"text": "Python3"
},
{
"code": "print(\"Size =\")print(df_pandas.shape)print(df_vaex.shape)",
"e": 1653,
"s": 1595,
"text": null
},
{
"code": null,
"e": 1661,
"s": 1653,
"text": "Output:"
},
{
"code": null,
"e": 1695,
"s": 1661,
"text": "Size = \n12852000, 36\n12852000, 36"
},
{
"code": null,
"e": 2124,
"s": 1695,
"text": "Vaex uses a lazy computation technique (i.e., compute on the fly without wasting RAM). In this technique, Vaex does not do the complete calculations, instead, it creates a Vaex expression, and when printed out it shows some preview values. So Vaex performs calculations only when needed else it stores the expression. This makes the computation speed of Vaex exceptionally fast. Let’s Perform an example on a simple computation:"
},
{
"code": null,
"e": 2142,
"s": 2124,
"text": "Pandas DataFrame:"
},
{
"code": null,
"e": 2150,
"s": 2142,
"text": "Python3"
},
{
"code": "%time df_pandas['column2'] + df_pandas['column3']",
"e": 2200,
"s": 2150,
"text": null
},
{
"code": null,
"e": 2208,
"s": 2200,
"text": "Output:"
},
{
"code": null,
"e": 2224,
"s": 2208,
"text": "Vaex DataFrame:"
},
{
"code": null,
"e": 2232,
"s": 2224,
"text": "Python3"
},
{
"code": "%time df_vaex.column2 + df_vaex.column3",
"e": 2272,
"s": 2232,
"text": null
},
{
"code": null,
"e": 2280,
"s": 2272,
"text": "Output:"
},
{
"code": null,
"e": 2517,
"s": 2280,
"text": "Vaex can calculate statistics such as mean, sum, count, standard deviation, etc., on an N-dimensional grid up to a billion (109) objects/rows per second. So, Let’s Compare the performance of pandas and Vaex while computing statistics:- "
},
{
"code": null,
"e": 2535,
"s": 2517,
"text": "Pandas Dataframe:"
},
{
"code": null,
"e": 2543,
"s": 2535,
"text": "Python3"
},
{
"code": "%time df_pandas[\"column3\"].mean()",
"e": 2577,
"s": 2543,
"text": null
},
{
"code": null,
"e": 2585,
"s": 2577,
"text": "Output:"
},
{
"code": null,
"e": 2621,
"s": 2585,
"text": "Wall time: 741 ms\n49.49811570183629"
},
{
"code": null,
"e": 2637,
"s": 2621,
"text": "Vaex DataFrame:"
},
{
"code": null,
"e": 2645,
"s": 2637,
"text": "Python3"
},
{
"code": "%time df_vaex.mean(df_vaex.column3)",
"e": 2681,
"s": 2645,
"text": null
},
{
"code": null,
"e": 2689,
"s": 2681,
"text": "Output:"
},
{
"code": null,
"e": 2725,
"s": 2689,
"text": "Wall time: 347 ms\narray(49.4981157)"
},
{
"code": null,
"e": 3008,
"s": 2725,
"text": "Unlike Pandas, No copies of memory are created in Vaex during data filtering, selections, subsets, cleansing. Let’s take the case of data filtering, in achieving this task Vaex uses very little memory as no memory copying is done in Vaex. and the time for execution is also minimal."
},
{
"code": null,
"e": 3016,
"s": 3008,
"text": "Pandas:"
},
{
"code": null,
"e": 3024,
"s": 3016,
"text": "Python3"
},
{
"code": "%time df_pandas_filtered = df_pandas[df_pandas['column5'] > 1]",
"e": 3087,
"s": 3024,
"text": null
},
{
"code": null,
"e": 3095,
"s": 3087,
"text": "Output:"
},
{
"code": null,
"e": 3113,
"s": 3095,
"text": "Wall time: 24.1 s"
},
{
"code": null,
"e": 3119,
"s": 3113,
"text": "Vaex:"
},
{
"code": null,
"e": 3127,
"s": 3119,
"text": "Python3"
},
{
"code": "%time df_vaex_filtered = df_vaex[df_vaex['column5'] > 1]",
"e": 3184,
"s": 3127,
"text": null
},
{
"code": null,
"e": 3192,
"s": 3184,
"text": "Output:"
},
{
"code": null,
"e": 3211,
"s": 3192,
"text": "Wall time: 91.4 ms"
},
{
"code": null,
"e": 3420,
"s": 3211,
"text": "Here data filtering results in a reference to the existing data with a boolean mask which keeps track of selected rows and non-selected rows. Vaex performs multiple computations in single pass over the data:-"
},
{
"code": null,
"e": 3428,
"s": 3420,
"text": "Python3"
},
{
"code": "df_vaex.select(df_vaex.column4 < 20, name='less_than')df_vaex.select(df_vaex.column4 >= 20, name='gr_than') %time df_vaex.mean(df_vaex.column4, selection=['less_than', 'gr_than'])",
"e": 3656,
"s": 3428,
"text": null
},
{
"code": null,
"e": 3664,
"s": 3656,
"text": "Output:"
},
{
"code": null,
"e": 3715,
"s": 3664,
"text": "Wall time: 128 ms\narray([ 9.4940431, 59.49137605])"
},
{
"code": null,
"e": 4052,
"s": 3715,
"text": "When we create a new column by adding expression to a DataFrame, Virtual columns are created. These columns are just like regular columns but occupy no memory and just stores the expression that defines them. This makes the task very fast and reduces the wastage of RAM. And Vaex makes no distinction between regular or virtual columns."
},
{
"code": null,
"e": 4060,
"s": 4052,
"text": "Python3"
},
{
"code": "%time df_vaex['new_col'] = df_vaex['column3']**2df_vaex.mean(df_vaex['new_col'])",
"e": 4141,
"s": 4060,
"text": null
},
{
"code": null,
"e": 4149,
"s": 4141,
"text": "Output:"
},
{
"code": null,
"e": 4304,
"s": 4149,
"text": "Vaex provides a faster alternative to pandas’s groupby as ‘binby’ which can calculate statistics on a regular N-dimensional grid swiftly in regular bins. "
},
{
"code": null,
"e": 4312,
"s": 4304,
"text": "Python3"
},
{
"code": "%time df_vaex.count(binby=df_vaex.column7, limits=[0, 20], shape=10)",
"e": 4400,
"s": 4312,
"text": null
},
{
"code": null,
"e": 4408,
"s": 4400,
"text": "Output:"
},
{
"code": null,
"e": 4837,
"s": 4408,
"text": "Visualization of the large dataset is a tedious task. But Vaex can compute these visualizations pretty quickly. The dataset gives a better idea of data distribution when computed in bins and Vaex excels in group aggregate properties, selections, and bins. So, Vaex is able to visualize swiftly and interactively. By Vaex, visualizations can be done even in 3-dimensions on large datasets.Let’s plot a simple 1-dimensional graph:"
},
{
"code": null,
"e": 4845,
"s": 4837,
"text": "Python3"
},
{
"code": "%time df_vaex.viz.histogram(df_vaex.column1, limits = [0, 20])",
"e": 4936,
"s": 4845,
"text": null
},
{
"code": null,
"e": 4944,
"s": 4936,
"text": "Output:"
},
{
"code": null,
"e": 4951,
"s": 4944,
"text": "Python"
},
{
"code": "df_vaex.viz.heatmap(df_vaex.column7, df_vaex.column8 + df_vaex.column9, limits=[-3, 20])",
"e": 5059,
"s": 4951,
"text": null
},
{
"code": null,
"e": 5067,
"s": 5059,
"text": "Output:"
},
{
"code": null,
"e": 5227,
"s": 5067,
"text": "We can add statistics expression and visualize by passing the “what=<statistic>(<expression>)” argument. So let’s perform a slightly complicated visualization:"
},
{
"code": null,
"e": 5235,
"s": 5227,
"text": "Python3"
},
{
"code": "df_vaex.viz.heatmap(df_vaex.column1, df_vaex.column2, what=(vaex.stat.mean(df_vaex.column4) / vaex.stat.std(df_vaex.column4)), limits='99.7%')",
"e": 5441,
"s": 5235,
"text": null
},
{
"code": null,
"e": 5449,
"s": 5441,
"text": "Output:"
},
{
"code": null,
"e": 5656,
"s": 5449,
"text": "Here, the ‘vaex.stat.<statistic>’ objects are very similar to Vaex expressions, which represent an underlying calculation, and also we can apply typical arithmetic and Numpy functions to these calculations."
},
{
"code": null,
"e": 5671,
"s": 5656,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 5686,
"s": 5671,
"text": "python-modules"
},
{
"code": null,
"e": 5696,
"s": 5686,
"text": "Blogathon"
},
{
"code": null,
"e": 5703,
"s": 5696,
"text": "Python"
},
{
"code": null,
"e": 5801,
"s": 5703,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5842,
"s": 5801,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 5880,
"s": 5842,
"text": "SQL Query to Convert Datetime to Date"
},
{
"code": null,
"e": 5940,
"s": 5880,
"text": "Scrape LinkedIn Using Selenium And Beautiful Soup in Python"
},
{
"code": null,
"e": 5984,
"s": 5940,
"text": "Python program to convert XML to Dictionary"
},
{
"code": null,
"e": 6012,
"s": 5984,
"text": "Shared ViewModel in Android"
},
{
"code": null,
"e": 6040,
"s": 6012,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 6062,
"s": 6040,
"text": "Python map() function"
},
{
"code": null,
"e": 6112,
"s": 6062,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 6130,
"s": 6112,
"text": "Python Dictionary"
}
] |
How to install Ruby on Windows? | 06 Oct, 2021
Prerequisite: Ruby Programming Language Before we start with the installation of Ruby on Windows, we must have first-hand knowledge of what Ruby is?. Ruby is a pure Object-Oriented language developed by Yukihiro Matsumoto (also known as Matz in the Ruby community) in the mid-1990s in Japan. Everything in Ruby is an object except the blocks but there are replacements too for it i.e procs and lambda. The objective of Ruby’s development was to make it act as a sensible buffer between human programmers and the underlying computing machinery. Ruby is based on many other languages like Perl, Lisp, Smalltalk, Eiffel and Ada. It is an interpreted scripting language which means most of its implementations execute instructions directly and freely, without previously compiling a program into machine-language instructions.
All the versions of Ruby for Windows can be downloaded from rubyinstaller.org. Download the latest version and follow the further instructions for its Installation.
Beginning with the installation:
Getting Started with License Agreement:
Selecting Installation Destination:
Selecting components to be installed:
Extracting Files and Installing:
Finishing Installation:
Installing MYSYS2 Components:
Choose what to install:
Updating Database and signing keys:
Installing Files:
Downloading Packages:
Installing Packages:
To check if Ruby installed correctly, perform a version check for the same using the following command on the command-line:
ruby -v
Here’s a sample Program to begin with the use of Ruby Programming:Let’s consider a simple Hello World Program.
puts "Hello World"
Using command-line, run the irb command. After this we can write the ruby code and it will run on command line.
how-to-install
Ruby-Basics
How To
Installation Guide
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 851,
"s": 28,
"text": "Prerequisite: Ruby Programming Language Before we start with the installation of Ruby on Windows, we must have first-hand knowledge of what Ruby is?. Ruby is a pure Object-Oriented language developed by Yukihiro Matsumoto (also known as Matz in the Ruby community) in the mid-1990s in Japan. Everything in Ruby is an object except the blocks but there are replacements too for it i.e procs and lambda. The objective of Ruby’s development was to make it act as a sensible buffer between human programmers and the underlying computing machinery. Ruby is based on many other languages like Perl, Lisp, Smalltalk, Eiffel and Ada. It is an interpreted scripting language which means most of its implementations execute instructions directly and freely, without previously compiling a program into machine-language instructions."
},
{
"code": null,
"e": 1016,
"s": 851,
"text": "All the versions of Ruby for Windows can be downloaded from rubyinstaller.org. Download the latest version and follow the further instructions for its Installation."
},
{
"code": null,
"e": 1049,
"s": 1016,
"text": "Beginning with the installation:"
},
{
"code": null,
"e": 1089,
"s": 1049,
"text": "Getting Started with License Agreement:"
},
{
"code": null,
"e": 1125,
"s": 1089,
"text": "Selecting Installation Destination:"
},
{
"code": null,
"e": 1163,
"s": 1125,
"text": "Selecting components to be installed:"
},
{
"code": null,
"e": 1196,
"s": 1163,
"text": "Extracting Files and Installing:"
},
{
"code": null,
"e": 1220,
"s": 1196,
"text": "Finishing Installation:"
},
{
"code": null,
"e": 1251,
"s": 1220,
"text": "Installing MYSYS2 Components: "
},
{
"code": null,
"e": 1275,
"s": 1251,
"text": "Choose what to install:"
},
{
"code": null,
"e": 1311,
"s": 1275,
"text": "Updating Database and signing keys:"
},
{
"code": null,
"e": 1329,
"s": 1311,
"text": "Installing Files:"
},
{
"code": null,
"e": 1351,
"s": 1329,
"text": "Downloading Packages:"
},
{
"code": null,
"e": 1372,
"s": 1351,
"text": "Installing Packages:"
},
{
"code": null,
"e": 1496,
"s": 1372,
"text": "To check if Ruby installed correctly, perform a version check for the same using the following command on the command-line:"
},
{
"code": null,
"e": 1504,
"s": 1496,
"text": "ruby -v"
},
{
"code": null,
"e": 1615,
"s": 1504,
"text": "Here’s a sample Program to begin with the use of Ruby Programming:Let’s consider a simple Hello World Program."
},
{
"code": "puts \"Hello World\"",
"e": 1634,
"s": 1615,
"text": null
},
{
"code": null,
"e": 1747,
"s": 1634,
"text": " Using command-line, run the irb command. After this we can write the ruby code and it will run on command line."
},
{
"code": null,
"e": 1762,
"s": 1747,
"text": "how-to-install"
},
{
"code": null,
"e": 1774,
"s": 1762,
"text": "Ruby-Basics"
},
{
"code": null,
"e": 1781,
"s": 1774,
"text": "How To"
},
{
"code": null,
"e": 1800,
"s": 1781,
"text": "Installation Guide"
},
{
"code": null,
"e": 1805,
"s": 1800,
"text": "Ruby"
}
] |
Node.js crypto.generateKeyPair() Method | 11 Oct, 2021
The crypto.generateKeyPair() method is an inbuilt application programming interface of crypto module which is used to generate a new asymmetric key pair of the specified type. For example, the currently supported key types are RSA, DSA, EC, Ed25519, Ed448, X25519, X448, and DH. Moreover, if option’s publicKeyEncoding or privateKeyEncoding is stated here, then this function acts as if keyObject.export() had been called on its output. Else, the particular part of the key is returned as a KeyObject.However, it is suggested to encode the public keys as ‘spki’ and private keys as ‘pkcs8’ with encryption for long-term storage.
Syntax:
crypto.generateKeyPair( type, options, callback )
Parameters: This method accept three parameters as mentioned above and described below:
type: It holds a string and it must include one or more of the following algorithms: ‘rsa’, ‘dsa’, ‘ec’, ‘ed25519’, ‘ed448’, ‘x25519’, ‘x448’, or ‘dh’.
options: is of type object. It can hold the following parameters:modulusLength: It holds a number. It is the key size in bits and is applicable for RSA, and DSA algorithm only.publicExponent: It holds a number. It is the Public exponent of RSA algorithm. Its by default value is 0x10001.divisorLength: It holds a number. It is the size of q in bits of DSA algorithm.namedCurve: It holds a string. It is the name of the curve to be used in EC algorithm.prime: It holds a buffer. It is the prime parameter of DH algorithm.primeLength: It holds a number. It is the prime length of DH algorithm in bits.generator: It holds a number. It is the custom generator of DH algorithm. Its by default value is 2.groupName: It holds string. It is the Diffie-Hellman group name of DH algorithm.publicKeyEncoding: It holds a string.privateKeyEncoding: It holds an Object.
modulusLength: It holds a number. It is the key size in bits and is applicable for RSA, and DSA algorithm only.publicExponent: It holds a number. It is the Public exponent of RSA algorithm. Its by default value is 0x10001.divisorLength: It holds a number. It is the size of q in bits of DSA algorithm.namedCurve: It holds a string. It is the name of the curve to be used in EC algorithm.prime: It holds a buffer. It is the prime parameter of DH algorithm.primeLength: It holds a number. It is the prime length of DH algorithm in bits.generator: It holds a number. It is the custom generator of DH algorithm. Its by default value is 2.groupName: It holds string. It is the Diffie-Hellman group name of DH algorithm.publicKeyEncoding: It holds a string.privateKeyEncoding: It holds an Object.
modulusLength: It holds a number. It is the key size in bits and is applicable for RSA, and DSA algorithm only.
publicExponent: It holds a number. It is the Public exponent of RSA algorithm. Its by default value is 0x10001.
divisorLength: It holds a number. It is the size of q in bits of DSA algorithm.
namedCurve: It holds a string. It is the name of the curve to be used in EC algorithm.
prime: It holds a buffer. It is the prime parameter of DH algorithm.
primeLength: It holds a number. It is the prime length of DH algorithm in bits.
generator: It holds a number. It is the custom generator of DH algorithm. Its by default value is 2.
groupName: It holds string. It is the Diffie-Hellman group name of DH algorithm.
publicKeyEncoding: It holds a string.
privateKeyEncoding: It holds an Object.
callback: It is a function, with parameters publicKey, privateKey and err.err: holds an error.publicKey: It holds a string, buffer or a KeyObject.privateKey: holds a string, buffer or a KeyObject.
err: holds an error.publicKey: It holds a string, buffer or a KeyObject.privateKey: holds a string, buffer or a KeyObject.
err: holds an error.
publicKey: It holds a string, buffer or a KeyObject.
privateKey: holds a string, buffer or a KeyObject.
Return Value: It returns a new asymmetric key pair of the given type.
Below examples illustrate the use of crypto.generateKeyPair() method in Node.js:
Example 1:
// Node.js program to demonstrate the// crypto.generateKeyPair() method // Including generateKeyPair from crypto moduleconst { generateKeyPair } = require('crypto'); // Calling generateKeyPair() method// with its parametersgenerateKeyPair('rsa', { modulusLength: 530, // options publicExponent: 0x10101, publicKeyEncoding: { type: 'pkcs1', format: 'der' }, privateKeyEncoding: { type: 'pkcs8', format: 'der', cipher: 'aes-192-cbc', passphrase: 'GeeksforGeeks is a CS-Portal!' }}, (err, publicKey, privateKey) => { // Callback function if(!err) { // Prints new asymmetric key pair console.log("Public Key is : ", publicKey); console.log(); console.log("Private Key is: ", privateKey); } else { // Prints error console.log("Errr is: ", err); } });
Output:
Public Key is : <Buffer 30 4a 02 43 03 12 b9
4c 1a 3f 96 07 51 c6 31 02d7 11 e2 e3 a5 2b 0c
7c 18 55 88 39 04 4c 86 e2 77 c4 29 47 82 2c 5b
4b 9e f3 e8 83 4b 5d 4b 31 e7 d5 ... >
Private Key is: <Buffer 30 82 01 cd 30 57 06
09 2a 86 48 86 f7 0d 01 050d 30 4a 30 29 06 09
2a 86 48 86 f7 0d 01 05 0c 30 1c 04 08 e0 31 2b
a0 38 82 e1 db 02 02 08 00 30 0c ... >
Example 2:
// Node.js program to demonstrate the// crypto.generateKeyPair() method // Including generateKeyPair from crypto moduleconst { generateKeyPair } = require('crypto'); // Calling generateKeyPair() method// with its parametersgenerateKeyPair('ec', { namedCurve: 'secp256k1', // Options publicKeyEncoding: { type: 'spki', format: 'der' }, privateKeyEncoding: { type: 'pkcs8', format: 'der' }}, (err, publicKey, privateKey) => { // Callback function if(!err) { // Prints new asymmetric key // pair after encoding console.log("Public Key is: ", publicKey.toString('hex')); console.log(); console.log("Private Key is: ", privateKey.toString('hex')); } else { // Prints error console.log("Errr is: ", err); } });
Output:
Public Key is: 3056301006072a8648ce3d020106052b8104000a0342000499c5f442c3264bcdfb093b0bc820e3f0f6546972856ebec2f8ccc03f49abdb47ffcfcaf4f37e0ec53050760e74014767e30a8a3e891f4db8c83fa27627898f15
Private Key is: 308184020100301006072a8648ce3d020106052b8104000a046d306b0201010420326b340a964512bfc3e010850ff05e077b2f016fce9eded11f40643e4231efc4a1440342000499c5f442c3264bcdfb093b0bc820e3f0f6546972856ebec2f8ccc03f49abdb47ffcfcaf4f37e0ec53050760e74014767e30a8a3e891f4db8c83fa27627898f15
Reference: https://nodejs.org/api/crypto.html#crypto_crypto_generatekeypair_type_options_callback
Node.js-crypto-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
JWT Authentication with Node.js
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
How do you run JavaScript script through the Terminal? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 657,
"s": 28,
"text": "The crypto.generateKeyPair() method is an inbuilt application programming interface of crypto module which is used to generate a new asymmetric key pair of the specified type. For example, the currently supported key types are RSA, DSA, EC, Ed25519, Ed448, X25519, X448, and DH. Moreover, if option’s publicKeyEncoding or privateKeyEncoding is stated here, then this function acts as if keyObject.export() had been called on its output. Else, the particular part of the key is returned as a KeyObject.However, it is suggested to encode the public keys as ‘spki’ and private keys as ‘pkcs8’ with encryption for long-term storage."
},
{
"code": null,
"e": 665,
"s": 657,
"text": "Syntax:"
},
{
"code": null,
"e": 715,
"s": 665,
"text": "crypto.generateKeyPair( type, options, callback )"
},
{
"code": null,
"e": 803,
"s": 715,
"text": "Parameters: This method accept three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 955,
"s": 803,
"text": "type: It holds a string and it must include one or more of the following algorithms: ‘rsa’, ‘dsa’, ‘ec’, ‘ed25519’, ‘ed448’, ‘x25519’, ‘x448’, or ‘dh’."
},
{
"code": null,
"e": 1811,
"s": 955,
"text": "options: is of type object. It can hold the following parameters:modulusLength: It holds a number. It is the key size in bits and is applicable for RSA, and DSA algorithm only.publicExponent: It holds a number. It is the Public exponent of RSA algorithm. Its by default value is 0x10001.divisorLength: It holds a number. It is the size of q in bits of DSA algorithm.namedCurve: It holds a string. It is the name of the curve to be used in EC algorithm.prime: It holds a buffer. It is the prime parameter of DH algorithm.primeLength: It holds a number. It is the prime length of DH algorithm in bits.generator: It holds a number. It is the custom generator of DH algorithm. Its by default value is 2.groupName: It holds string. It is the Diffie-Hellman group name of DH algorithm.publicKeyEncoding: It holds a string.privateKeyEncoding: It holds an Object."
},
{
"code": null,
"e": 2602,
"s": 1811,
"text": "modulusLength: It holds a number. It is the key size in bits and is applicable for RSA, and DSA algorithm only.publicExponent: It holds a number. It is the Public exponent of RSA algorithm. Its by default value is 0x10001.divisorLength: It holds a number. It is the size of q in bits of DSA algorithm.namedCurve: It holds a string. It is the name of the curve to be used in EC algorithm.prime: It holds a buffer. It is the prime parameter of DH algorithm.primeLength: It holds a number. It is the prime length of DH algorithm in bits.generator: It holds a number. It is the custom generator of DH algorithm. Its by default value is 2.groupName: It holds string. It is the Diffie-Hellman group name of DH algorithm.publicKeyEncoding: It holds a string.privateKeyEncoding: It holds an Object."
},
{
"code": null,
"e": 2714,
"s": 2602,
"text": "modulusLength: It holds a number. It is the key size in bits and is applicable for RSA, and DSA algorithm only."
},
{
"code": null,
"e": 2826,
"s": 2714,
"text": "publicExponent: It holds a number. It is the Public exponent of RSA algorithm. Its by default value is 0x10001."
},
{
"code": null,
"e": 2906,
"s": 2826,
"text": "divisorLength: It holds a number. It is the size of q in bits of DSA algorithm."
},
{
"code": null,
"e": 2993,
"s": 2906,
"text": "namedCurve: It holds a string. It is the name of the curve to be used in EC algorithm."
},
{
"code": null,
"e": 3062,
"s": 2993,
"text": "prime: It holds a buffer. It is the prime parameter of DH algorithm."
},
{
"code": null,
"e": 3142,
"s": 3062,
"text": "primeLength: It holds a number. It is the prime length of DH algorithm in bits."
},
{
"code": null,
"e": 3243,
"s": 3142,
"text": "generator: It holds a number. It is the custom generator of DH algorithm. Its by default value is 2."
},
{
"code": null,
"e": 3324,
"s": 3243,
"text": "groupName: It holds string. It is the Diffie-Hellman group name of DH algorithm."
},
{
"code": null,
"e": 3362,
"s": 3324,
"text": "publicKeyEncoding: It holds a string."
},
{
"code": null,
"e": 3402,
"s": 3362,
"text": "privateKeyEncoding: It holds an Object."
},
{
"code": null,
"e": 3599,
"s": 3402,
"text": "callback: It is a function, with parameters publicKey, privateKey and err.err: holds an error.publicKey: It holds a string, buffer or a KeyObject.privateKey: holds a string, buffer or a KeyObject."
},
{
"code": null,
"e": 3722,
"s": 3599,
"text": "err: holds an error.publicKey: It holds a string, buffer or a KeyObject.privateKey: holds a string, buffer or a KeyObject."
},
{
"code": null,
"e": 3743,
"s": 3722,
"text": "err: holds an error."
},
{
"code": null,
"e": 3796,
"s": 3743,
"text": "publicKey: It holds a string, buffer or a KeyObject."
},
{
"code": null,
"e": 3847,
"s": 3796,
"text": "privateKey: holds a string, buffer or a KeyObject."
},
{
"code": null,
"e": 3917,
"s": 3847,
"text": "Return Value: It returns a new asymmetric key pair of the given type."
},
{
"code": null,
"e": 3998,
"s": 3917,
"text": "Below examples illustrate the use of crypto.generateKeyPair() method in Node.js:"
},
{
"code": null,
"e": 4009,
"s": 3998,
"text": "Example 1:"
},
{
"code": "// Node.js program to demonstrate the// crypto.generateKeyPair() method // Including generateKeyPair from crypto moduleconst { generateKeyPair } = require('crypto'); // Calling generateKeyPair() method// with its parametersgenerateKeyPair('rsa', { modulusLength: 530, // options publicExponent: 0x10101, publicKeyEncoding: { type: 'pkcs1', format: 'der' }, privateKeyEncoding: { type: 'pkcs8', format: 'der', cipher: 'aes-192-cbc', passphrase: 'GeeksforGeeks is a CS-Portal!' }}, (err, publicKey, privateKey) => { // Callback function if(!err) { // Prints new asymmetric key pair console.log(\"Public Key is : \", publicKey); console.log(); console.log(\"Private Key is: \", privateKey); } else { // Prints error console.log(\"Errr is: \", err); } });",
"e": 4878,
"s": 4009,
"text": null
},
{
"code": null,
"e": 4886,
"s": 4878,
"text": "Output:"
},
{
"code": null,
"e": 5246,
"s": 4886,
"text": "Public Key is : <Buffer 30 4a 02 43 03 12 b9\n4c 1a 3f 96 07 51 c6 31 02d7 11 e2 e3 a5 2b 0c\n7c 18 55 88 39 04 4c 86 e2 77 c4 29 47 82 2c 5b\n4b 9e f3 e8 83 4b 5d 4b 31 e7 d5 ... >\n\nPrivate Key is: <Buffer 30 82 01 cd 30 57 06\n09 2a 86 48 86 f7 0d 01 050d 30 4a 30 29 06 09\n2a 86 48 86 f7 0d 01 05 0c 30 1c 04 08 e0 31 2b\na0 38 82 e1 db 02 02 08 00 30 0c ... >\n"
},
{
"code": null,
"e": 5257,
"s": 5246,
"text": "Example 2:"
},
{
"code": "// Node.js program to demonstrate the// crypto.generateKeyPair() method // Including generateKeyPair from crypto moduleconst { generateKeyPair } = require('crypto'); // Calling generateKeyPair() method// with its parametersgenerateKeyPair('ec', { namedCurve: 'secp256k1', // Options publicKeyEncoding: { type: 'spki', format: 'der' }, privateKeyEncoding: { type: 'pkcs8', format: 'der' }}, (err, publicKey, privateKey) => { // Callback function if(!err) { // Prints new asymmetric key // pair after encoding console.log(\"Public Key is: \", publicKey.toString('hex')); console.log(); console.log(\"Private Key is: \", privateKey.toString('hex')); } else { // Prints error console.log(\"Errr is: \", err); } });",
"e": 6118,
"s": 5257,
"text": null
},
{
"code": null,
"e": 6126,
"s": 6118,
"text": "Output:"
},
{
"code": null,
"e": 6609,
"s": 6126,
"text": "Public Key is: 3056301006072a8648ce3d020106052b8104000a0342000499c5f442c3264bcdfb093b0bc820e3f0f6546972856ebec2f8ccc03f49abdb47ffcfcaf4f37e0ec53050760e74014767e30a8a3e891f4db8c83fa27627898f15\n\nPrivate Key is: 308184020100301006072a8648ce3d020106052b8104000a046d306b0201010420326b340a964512bfc3e010850ff05e077b2f016fce9eded11f40643e4231efc4a1440342000499c5f442c3264bcdfb093b0bc820e3f0f6546972856ebec2f8ccc03f49abdb47ffcfcaf4f37e0ec53050760e74014767e30a8a3e891f4db8c83fa27627898f15\n"
},
{
"code": null,
"e": 6707,
"s": 6609,
"text": "Reference: https://nodejs.org/api/crypto.html#crypto_crypto_generatekeypair_type_options_callback"
},
{
"code": null,
"e": 6729,
"s": 6707,
"text": "Node.js-crypto-module"
},
{
"code": null,
"e": 6737,
"s": 6729,
"text": "Node.js"
},
{
"code": null,
"e": 6754,
"s": 6737,
"text": "Web Technologies"
},
{
"code": null,
"e": 6852,
"s": 6754,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6882,
"s": 6852,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 6939,
"s": 6882,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 6993,
"s": 6939,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 7033,
"s": 6993,
"text": "Mongoose | findByIdAndUpdate() Function"
},
{
"code": null,
"e": 7065,
"s": 7033,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 7115,
"s": 7065,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 7177,
"s": 7115,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 7237,
"s": 7177,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 7298,
"s": 7237,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
PyQt5 | How to set value of Progress Bar ? | 22 Apr, 2020
In this article we will see how to set the value of progress bar. Progress bar is basically a bar which is used to visualize the progression of an extended computer operation, such as a download, file transfer, or installation.
In order to set value to progress bar we will use setValue method.
Syntax : bar.setValue(value)
Argument : It takes integer as argument, which should vary from 0 to 100.
Action performed : It will set value to progress bar.
Code :
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating progress bar bar = QProgressBar(self) # setting geometry to progress bar bar.setGeometry(200, 150, 200, 30) # setting value to progress bar bar.setValue(50) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 256,
"s": 28,
"text": "In this article we will see how to set the value of progress bar. Progress bar is basically a bar which is used to visualize the progression of an extended computer operation, such as a download, file transfer, or installation."
},
{
"code": null,
"e": 323,
"s": 256,
"text": "In order to set value to progress bar we will use setValue method."
},
{
"code": null,
"e": 352,
"s": 323,
"text": "Syntax : bar.setValue(value)"
},
{
"code": null,
"e": 426,
"s": 352,
"text": "Argument : It takes integer as argument, which should vary from 0 to 100."
},
{
"code": null,
"e": 480,
"s": 426,
"text": "Action performed : It will set value to progress bar."
},
{
"code": null,
"e": 487,
"s": 480,
"text": "Code :"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating progress bar bar = QProgressBar(self) # setting geometry to progress bar bar.setGeometry(200, 150, 200, 30) # setting value to progress bar bar.setValue(50) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 1341,
"s": 487,
"text": null
},
{
"code": null,
"e": 1350,
"s": 1341,
"text": "Output :"
},
{
"code": null,
"e": 1361,
"s": 1350,
"text": "Python-gui"
},
{
"code": null,
"e": 1373,
"s": 1361,
"text": "Python-PyQt"
},
{
"code": null,
"e": 1380,
"s": 1373,
"text": "Python"
}
] |
Multiprocessing in Python | Set 1 (Introduction) | 09 Feb, 2018
This article is a brief yet concise introduction to multiprocessing in Python programming language.
What is multiprocessing?
Multiprocessing refers to the ability of a system to support more than one processor at the same time. Applications in a multiprocessing system are broken to smaller routines that run independently. The operating system allocates these threads to the processors improving performance of the system.
Why multiprocessing?
Consider a computer system with a single processor. If it is assigned several processes at the same time, it will have to interrupt each task and switch briefly to another, to keep all of the processes going.This situation is just like a chef working in a kitchen alone. He has to do several tasks like baking, stirring, kneading dough, etc.
So the gist is that: The more tasks you must do at once, the more difficult it gets to keep track of them all, and keeping the timing right becomes more of a challenge.This is where the concept of multiprocessing arises!A multiprocessing system can have:
multiprocessor, i.e. a computer with more than one central processor.
multi-core processor, i.e. a single computing component with two or more independent actual processing units (called “cores”).
Here, the CPU can easily executes several tasks at once, with each task using its own processor.
It is just like the chef in last situation being assisted by his assistants. Now, they can divide the tasks among themselves and chef doesn’t need to switch between his tasks.
Multiprocessing in Python
In Python, the multiprocessing module includes a very simple and intuitive API for dividing work between multiple processes.Let us consider a simple example using multiprocessing module:
# importing the multiprocessing moduleimport multiprocessing def print_cube(num): """ function to print cube of given num """ print("Cube: {}".format(num * num * num)) def print_square(num): """ function to print square of given num """ print("Square: {}".format(num * num)) if __name__ == "__main__": # creating processes p1 = multiprocessing.Process(target=print_square, args=(10, )) p2 = multiprocessing.Process(target=print_cube, args=(10, )) # starting process 1 p1.start() # starting process 2 p2.start() # wait until process 1 is finished p1.join() # wait until process 2 is finished p2.join() # both processes finished print("Done!")
Square: 100
Cube: 1000
Done!
Let us try to understand the above code:
To import the multiprocessing module, we do:import multiprocessing
import multiprocessing
To create a process, we create an object of Process class. It takes following arguments:target: the function to be executed by processargs: the arguments to be passed to the target functionNote: Process constructor takes many other arguments also which will be discussed later. In above example, we created 2 processes with different target functions:p1 = multiprocessing.Process(target=print_square, args=(10, ))
p2 = multiprocessing.Process(target=print_cube, args=(10, ))
target: the function to be executed by process
args: the arguments to be passed to the target function
Note: Process constructor takes many other arguments also which will be discussed later. In above example, we created 2 processes with different target functions:
p1 = multiprocessing.Process(target=print_square, args=(10, ))
p2 = multiprocessing.Process(target=print_cube, args=(10, ))
To start a process, we use start method of Process class.p1.start()
p2.start()
p1.start()
p2.start()
Once the processes start, the current program also keeps on executing. In order to stop execution of current program until a process is complete, we use join method.p1.join()
p2.join()
As a result, the current program will first wait for the completion of p1 and then p2. Once, they are completed, the next statements of current program are executed.
p1.join()
p2.join()
As a result, the current program will first wait for the completion of p1 and then p2. Once, they are completed, the next statements of current program are executed.
Let us consider another program to understand the concept of different processes running on same python script. In this example below, we print the ID of the processes running the target functions:
# importing the multiprocessing moduleimport multiprocessingimport os def worker1(): # printing process id print("ID of process running worker1: {}".format(os.getpid())) def worker2(): # printing process id print("ID of process running worker2: {}".format(os.getpid())) if __name__ == "__main__": # printing main program process id print("ID of main process: {}".format(os.getpid())) # creating processes p1 = multiprocessing.Process(target=worker1) p2 = multiprocessing.Process(target=worker2) # starting processes p1.start() p2.start() # process IDs print("ID of process p1: {}".format(p1.pid)) print("ID of process p2: {}".format(p2.pid)) # wait until processes are finished p1.join() p2.join() # both processes finished print("Both processes finished execution!") # check if processes are alive print("Process p1 is alive: {}".format(p1.is_alive())) print("Process p2 is alive: {}".format(p2.is_alive()))
ID of main process: 28628
ID of process running worker1: 29305
ID of process running worker2: 29306
ID of process p1: 29305
ID of process p2: 29306
Both processes finished execution!
Process p1 is alive: False
Process p2 is alive: False
The main python script has a different process ID and multiprocessing module spawns new processes with different process IDs as we create Process objects p1 and p2. In above program, we use os.getpid() function to get ID of process running the current target function.Notice that it matches with the process IDs of p1 and p2 which we obtain using pid attribute of Process class.
Notice that it matches with the process IDs of p1 and p2 which we obtain using pid attribute of Process class.
Each process runs independently and has its own memory space.
As soon as the execution of target function is finished, the processes get terminated. In above program we used is_alive method of Process class to check if a process is still active or not.
Consider the diagram below to understand how new processes are different from main Python script:So, this was a brief introduction to multiprocessing in Python. Next few articles will cover following topics related to multiprocessing:
Sharing data between processes using Array, value and queues.
Lock and Pool concepts in multiprocessing
Next:
Multiprocessing in Python | Set 2
Synchronization and Pooling of processes in Python
References:
http://learn.parallax.com/tutorials/language/blocklyprop/blocklyprop-functions-and-multicore/bit-about-multicore
https://docs.python.org/3/library/multiprocessing.html
This article is contributed by Nikhil Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Feb, 2018"
},
{
"code": null,
"e": 152,
"s": 52,
"text": "This article is a brief yet concise introduction to multiprocessing in Python programming language."
},
{
"code": null,
"e": 177,
"s": 152,
"text": "What is multiprocessing?"
},
{
"code": null,
"e": 476,
"s": 177,
"text": "Multiprocessing refers to the ability of a system to support more than one processor at the same time. Applications in a multiprocessing system are broken to smaller routines that run independently. The operating system allocates these threads to the processors improving performance of the system."
},
{
"code": null,
"e": 497,
"s": 476,
"text": "Why multiprocessing?"
},
{
"code": null,
"e": 839,
"s": 497,
"text": "Consider a computer system with a single processor. If it is assigned several processes at the same time, it will have to interrupt each task and switch briefly to another, to keep all of the processes going.This situation is just like a chef working in a kitchen alone. He has to do several tasks like baking, stirring, kneading dough, etc."
},
{
"code": null,
"e": 1094,
"s": 839,
"text": "So the gist is that: The more tasks you must do at once, the more difficult it gets to keep track of them all, and keeping the timing right becomes more of a challenge.This is where the concept of multiprocessing arises!A multiprocessing system can have:"
},
{
"code": null,
"e": 1164,
"s": 1094,
"text": "multiprocessor, i.e. a computer with more than one central processor."
},
{
"code": null,
"e": 1291,
"s": 1164,
"text": "multi-core processor, i.e. a single computing component with two or more independent actual processing units (called “cores”)."
},
{
"code": null,
"e": 1388,
"s": 1291,
"text": "Here, the CPU can easily executes several tasks at once, with each task using its own processor."
},
{
"code": null,
"e": 1564,
"s": 1388,
"text": "It is just like the chef in last situation being assisted by his assistants. Now, they can divide the tasks among themselves and chef doesn’t need to switch between his tasks."
},
{
"code": null,
"e": 1590,
"s": 1564,
"text": "Multiprocessing in Python"
},
{
"code": null,
"e": 1777,
"s": 1590,
"text": "In Python, the multiprocessing module includes a very simple and intuitive API for dividing work between multiple processes.Let us consider a simple example using multiprocessing module:"
},
{
"code": "# importing the multiprocessing moduleimport multiprocessing def print_cube(num): \"\"\" function to print cube of given num \"\"\" print(\"Cube: {}\".format(num * num * num)) def print_square(num): \"\"\" function to print square of given num \"\"\" print(\"Square: {}\".format(num * num)) if __name__ == \"__main__\": # creating processes p1 = multiprocessing.Process(target=print_square, args=(10, )) p2 = multiprocessing.Process(target=print_cube, args=(10, )) # starting process 1 p1.start() # starting process 2 p2.start() # wait until process 1 is finished p1.join() # wait until process 2 is finished p2.join() # both processes finished print(\"Done!\")",
"e": 2491,
"s": 1777,
"text": null
},
{
"code": null,
"e": 2521,
"s": 2491,
"text": "Square: 100\nCube: 1000\nDone!\n"
},
{
"code": null,
"e": 2562,
"s": 2521,
"text": "Let us try to understand the above code:"
},
{
"code": null,
"e": 2630,
"s": 2562,
"text": "To import the multiprocessing module, we do:import multiprocessing\n"
},
{
"code": null,
"e": 2654,
"s": 2630,
"text": "import multiprocessing\n"
},
{
"code": null,
"e": 3130,
"s": 2654,
"text": "To create a process, we create an object of Process class. It takes following arguments:target: the function to be executed by processargs: the arguments to be passed to the target functionNote: Process constructor takes many other arguments also which will be discussed later. In above example, we created 2 processes with different target functions:p1 = multiprocessing.Process(target=print_square, args=(10, ))\np2 = multiprocessing.Process(target=print_cube, args=(10, ))\n"
},
{
"code": null,
"e": 3177,
"s": 3130,
"text": "target: the function to be executed by process"
},
{
"code": null,
"e": 3233,
"s": 3177,
"text": "args: the arguments to be passed to the target function"
},
{
"code": null,
"e": 3396,
"s": 3233,
"text": "Note: Process constructor takes many other arguments also which will be discussed later. In above example, we created 2 processes with different target functions:"
},
{
"code": null,
"e": 3521,
"s": 3396,
"text": "p1 = multiprocessing.Process(target=print_square, args=(10, ))\np2 = multiprocessing.Process(target=print_cube, args=(10, ))\n"
},
{
"code": null,
"e": 3601,
"s": 3521,
"text": "To start a process, we use start method of Process class.p1.start()\np2.start()\n"
},
{
"code": null,
"e": 3624,
"s": 3601,
"text": "p1.start()\np2.start()\n"
},
{
"code": null,
"e": 3975,
"s": 3624,
"text": "Once the processes start, the current program also keeps on executing. In order to stop execution of current program until a process is complete, we use join method.p1.join()\np2.join()\nAs a result, the current program will first wait for the completion of p1 and then p2. Once, they are completed, the next statements of current program are executed."
},
{
"code": null,
"e": 3996,
"s": 3975,
"text": "p1.join()\np2.join()\n"
},
{
"code": null,
"e": 4162,
"s": 3996,
"text": "As a result, the current program will first wait for the completion of p1 and then p2. Once, they are completed, the next statements of current program are executed."
},
{
"code": null,
"e": 4360,
"s": 4162,
"text": "Let us consider another program to understand the concept of different processes running on same python script. In this example below, we print the ID of the processes running the target functions:"
},
{
"code": "# importing the multiprocessing moduleimport multiprocessingimport os def worker1(): # printing process id print(\"ID of process running worker1: {}\".format(os.getpid())) def worker2(): # printing process id print(\"ID of process running worker2: {}\".format(os.getpid())) if __name__ == \"__main__\": # printing main program process id print(\"ID of main process: {}\".format(os.getpid())) # creating processes p1 = multiprocessing.Process(target=worker1) p2 = multiprocessing.Process(target=worker2) # starting processes p1.start() p2.start() # process IDs print(\"ID of process p1: {}\".format(p1.pid)) print(\"ID of process p2: {}\".format(p2.pid)) # wait until processes are finished p1.join() p2.join() # both processes finished print(\"Both processes finished execution!\") # check if processes are alive print(\"Process p1 is alive: {}\".format(p1.is_alive())) print(\"Process p2 is alive: {}\".format(p2.is_alive()))",
"e": 5353,
"s": 4360,
"text": null
},
{
"code": null,
"e": 5591,
"s": 5353,
"text": "ID of main process: 28628\nID of process running worker1: 29305\nID of process running worker2: 29306\nID of process p1: 29305\nID of process p2: 29306\nBoth processes finished execution!\nProcess p1 is alive: False\nProcess p2 is alive: False\n"
},
{
"code": null,
"e": 5970,
"s": 5591,
"text": "The main python script has a different process ID and multiprocessing module spawns new processes with different process IDs as we create Process objects p1 and p2. In above program, we use os.getpid() function to get ID of process running the current target function.Notice that it matches with the process IDs of p1 and p2 which we obtain using pid attribute of Process class."
},
{
"code": null,
"e": 6081,
"s": 5970,
"text": "Notice that it matches with the process IDs of p1 and p2 which we obtain using pid attribute of Process class."
},
{
"code": null,
"e": 6143,
"s": 6081,
"text": "Each process runs independently and has its own memory space."
},
{
"code": null,
"e": 6334,
"s": 6143,
"text": "As soon as the execution of target function is finished, the processes get terminated. In above program we used is_alive method of Process class to check if a process is still active or not."
},
{
"code": null,
"e": 6569,
"s": 6334,
"text": "Consider the diagram below to understand how new processes are different from main Python script:So, this was a brief introduction to multiprocessing in Python. Next few articles will cover following topics related to multiprocessing:"
},
{
"code": null,
"e": 6631,
"s": 6569,
"text": "Sharing data between processes using Array, value and queues."
},
{
"code": null,
"e": 6673,
"s": 6631,
"text": "Lock and Pool concepts in multiprocessing"
},
{
"code": null,
"e": 6679,
"s": 6673,
"text": "Next:"
},
{
"code": null,
"e": 6713,
"s": 6679,
"text": "Multiprocessing in Python | Set 2"
},
{
"code": null,
"e": 6764,
"s": 6713,
"text": "Synchronization and Pooling of processes in Python"
},
{
"code": null,
"e": 6776,
"s": 6764,
"text": "References:"
},
{
"code": null,
"e": 6889,
"s": 6776,
"text": "http://learn.parallax.com/tutorials/language/blocklyprop/blocklyprop-functions-and-multicore/bit-about-multicore"
},
{
"code": null,
"e": 6944,
"s": 6889,
"text": "https://docs.python.org/3/library/multiprocessing.html"
},
{
"code": null,
"e": 7244,
"s": 6944,
"text": "This article is contributed by Nikhil Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 7369,
"s": 7244,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 7376,
"s": 7369,
"text": "Python"
}
] |
p5.js | textSize() Function | 16 Apr, 2019
The textSize() function in p5.js is used to set or return the font size of text. This function is used in all subsequent calls to the text() function.
Syntax:
textSize(size)
or
textSize()
Parameters: This function accepts single parameter sizewhich stores the size of the text in terms of pixels.
Below programs illustrate the textSize() function in p5.js:
Example 1: This example uses textSize() function to set the font size of text.
function setup() { // Create Canvas of given size createCanvas(380, 170);} function draw() { let string = "GeeksforGeeks"; // Set the background color background(220); // Set the text size textSize(30); // Set the text text(string, 100, 30);}
Output:
Example 2: This example uses textSize() function to return the font size of text.
function setup() { // Create Canvas of given size createCanvas(380, 170);} function draw() { let string = "GeeksforGeeks"; // Set the background color background(220); // Set the text size textSize(16); // store the size of text var u = textSize(); // Set the stroke color stroke(255, 204, 0); // Display result text("Value of Text Size is : " + u, 50, 30);}
Output:
Reference: https://p5js.org/reference/#/p5/textSize
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Apr, 2019"
},
{
"code": null,
"e": 179,
"s": 28,
"text": "The textSize() function in p5.js is used to set or return the font size of text. This function is used in all subsequent calls to the text() function."
},
{
"code": null,
"e": 187,
"s": 179,
"text": "Syntax:"
},
{
"code": null,
"e": 202,
"s": 187,
"text": "textSize(size)"
},
{
"code": null,
"e": 205,
"s": 202,
"text": "or"
},
{
"code": null,
"e": 216,
"s": 205,
"text": "textSize()"
},
{
"code": null,
"e": 325,
"s": 216,
"text": "Parameters: This function accepts single parameter sizewhich stores the size of the text in terms of pixels."
},
{
"code": null,
"e": 385,
"s": 325,
"text": "Below programs illustrate the textSize() function in p5.js:"
},
{
"code": null,
"e": 464,
"s": 385,
"text": "Example 1: This example uses textSize() function to set the font size of text."
},
{
"code": "function setup() { // Create Canvas of given size createCanvas(380, 170);} function draw() { let string = \"GeeksforGeeks\"; // Set the background color background(220); // Set the text size textSize(30); // Set the text text(string, 100, 30);}",
"e": 766,
"s": 464,
"text": null
},
{
"code": null,
"e": 774,
"s": 766,
"text": "Output:"
},
{
"code": null,
"e": 856,
"s": 774,
"text": "Example 2: This example uses textSize() function to return the font size of text."
},
{
"code": "function setup() { // Create Canvas of given size createCanvas(380, 170);} function draw() { let string = \"GeeksforGeeks\"; // Set the background color background(220); // Set the text size textSize(16); // store the size of text var u = textSize(); // Set the stroke color stroke(255, 204, 0); // Display result text(\"Value of Text Size is : \" + u, 50, 30);}",
"e": 1304,
"s": 856,
"text": null
},
{
"code": null,
"e": 1312,
"s": 1304,
"text": "Output:"
},
{
"code": null,
"e": 1364,
"s": 1312,
"text": "Reference: https://p5js.org/reference/#/p5/textSize"
},
{
"code": null,
"e": 1381,
"s": 1364,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 1392,
"s": 1381,
"text": "JavaScript"
},
{
"code": null,
"e": 1409,
"s": 1392,
"text": "Web Technologies"
}
] |
React Native | Expo – BarCodeScanner | 28 May, 2020
Our aim for this article is to understand the usage of BarCodeScanner component by Expo, by developing a simple Scanner app.Before moving onto the development part, we need to initialize the project and install the dependencies. So, open up the terminal and enter the following commands:
expo init // Choose the Blank template when prompted
Move into the project folder and then run the following command:
expo install expo-barcode-scanner
Now that we have installed the scanner component, it’s time to write the code. Let us start by importing the required components, code for which is shown below:
Now it’s time to get inside the App class and carry out the development process step by step
In this step we are going to prompt user, for the permission to access camera. Status of this request is stored in the state of the component, code for which is shown below:
Now, inside the render function we are going to return different views depending upon the status of our request as show below:
After the user has given us the permission to access camera, we will return the BarCodeScanner component which is demonstrated in the next part.
Got the permission, it’s time to move on to the BarCodeScanner Component.
It’s time to define the barCodeScanned function to access the response data which is demonstrated in the next step.
We are going to alert the user with the response data as an example.
We have successfully completed the development process of this simple BarCodeScanner application.
Github Repo Link: https://github.com/notnotparas/expo-BarCodeScanner
API Reference: https://docs.expo.io/versions/latest/sdk/bar-code-scanner/
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Difference Between PUT and PATCH Request
ReactJS | Router
How to float three div side by side using CSS?
Design a Tribute Page using HTML & CSS
Roadmap to Learn JavaScript For Beginners | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 May, 2020"
},
{
"code": null,
"e": 316,
"s": 28,
"text": "Our aim for this article is to understand the usage of BarCodeScanner component by Expo, by developing a simple Scanner app.Before moving onto the development part, we need to initialize the project and install the dependencies. So, open up the terminal and enter the following commands:"
},
{
"code": null,
"e": 369,
"s": 316,
"text": "expo init // Choose the Blank template when prompted"
},
{
"code": null,
"e": 434,
"s": 369,
"text": "Move into the project folder and then run the following command:"
},
{
"code": null,
"e": 468,
"s": 434,
"text": "expo install expo-barcode-scanner"
},
{
"code": null,
"e": 629,
"s": 468,
"text": "Now that we have installed the scanner component, it’s time to write the code. Let us start by importing the required components, code for which is shown below:"
},
{
"code": null,
"e": 722,
"s": 629,
"text": "Now it’s time to get inside the App class and carry out the development process step by step"
},
{
"code": null,
"e": 896,
"s": 722,
"text": "In this step we are going to prompt user, for the permission to access camera. Status of this request is stored in the state of the component, code for which is shown below:"
},
{
"code": null,
"e": 1023,
"s": 896,
"text": "Now, inside the render function we are going to return different views depending upon the status of our request as show below:"
},
{
"code": null,
"e": 1169,
"s": 1023,
"text": " After the user has given us the permission to access camera, we will return the BarCodeScanner component which is demonstrated in the next part."
},
{
"code": null,
"e": 1243,
"s": 1169,
"text": "Got the permission, it’s time to move on to the BarCodeScanner Component."
},
{
"code": null,
"e": 1359,
"s": 1243,
"text": "It’s time to define the barCodeScanned function to access the response data which is demonstrated in the next step."
},
{
"code": null,
"e": 1428,
"s": 1359,
"text": "We are going to alert the user with the response data as an example."
},
{
"code": null,
"e": 1527,
"s": 1428,
"text": "We have successfully completed the development process of this simple BarCodeScanner application. "
},
{
"code": null,
"e": 1596,
"s": 1527,
"text": "Github Repo Link: https://github.com/notnotparas/expo-BarCodeScanner"
},
{
"code": null,
"e": 1670,
"s": 1596,
"text": "API Reference: https://docs.expo.io/versions/latest/sdk/bar-code-scanner/"
},
{
"code": null,
"e": 1679,
"s": 1670,
"text": "react-js"
},
{
"code": null,
"e": 1696,
"s": 1679,
"text": "Web Technologies"
},
{
"code": null,
"e": 1794,
"s": 1696,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1855,
"s": 1794,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1898,
"s": 1855,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 1970,
"s": 1898,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2010,
"s": 1970,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2034,
"s": 2010,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2075,
"s": 2034,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2092,
"s": 2075,
"text": "ReactJS | Router"
},
{
"code": null,
"e": 2139,
"s": 2092,
"text": "How to float three div side by side using CSS?"
},
{
"code": null,
"e": 2178,
"s": 2139,
"text": "Design a Tribute Page using HTML & CSS"
}
] |
How to Build a Simple Flashlight/TorchLight Android App? | 12 Jan, 2022
All the beginners who are into the android development world should build a simple android application that can turn on/off the flashlight or torchlight by clicking a Button. So at the end of this article, one will be able to build their own android flashlight application with a simple layout. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Working with the activity_main.xml
This layout contains a simple TextView, View (as divider), and one ToggleButton to toggle the Flashlight unit.
Please refer to How to add Toggle Button in an Android Application, to implement, and to see how the toggle button works.
Invoke the following code in the activity_main.xml file or one can design custom widgets.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="HardcodedText"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="100dp" android:text="Flashlight" android:textColor="@color/colorPrimary" android:textSize="50sp" android:textStyle="bold|italic" /> <!--This is the simple divider between above TextView and ToggleButton--> <View android:layout_width="match_parent" android:layout_height="1dp" android:layout_marginStart="32dp" android:layout_marginTop="16dp" android:layout_marginEnd="32dp" android:background="@android:color/darker_gray" /> <!--This toggle button by default toggles between the ON and OFF we no need to set separate TextView for it--> <ToggleButton android:id="@+id/toggle_flashlight" android:layout_width="200dp" android:layout_height="75dp" android:layout_gravity="center" android:layout_marginTop="32dp" android:onClick="toggleFlashLight" android:textSize="25sp" /> </LinearLayout>
The following output UI is produced:
Step 3: Handling the Toggle Button widget to toggle ON or OFF inside the MainActivity.java file
The complete code for the MainActivity.java file is given below. Comments are added inside the code to understand the code in more detail.
Java
import android.content.Context;import android.hardware.camera2.CameraAccessException;import android.hardware.camera2.CameraManager;import android.os.Build;import android.os.Bundle;import android.view.View;import android.widget.Toast;import android.widget.ToggleButton;import androidx.annotation.RequiresApi;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private ToggleButton toggleFlashLightOnOff; private CameraManager cameraManager; private String getCameraID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Register the ToggleButton with specific ID toggleFlashLightOnOff = findViewById(R.id.toggle_flashlight); // cameraManager to interact with camera devices cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE); // Exception is handled, because to check whether // the camera resource is being used by another // service or not. try { // O means back camera unit, // 1 means front camera unit getCameraID = cameraManager.getCameraIdList()[0]; } catch (CameraAccessException e) { e.printStackTrace(); } } // RequiresApi is set because, the devices which are // below API level 10 don't have the flash unit with // camera. @RequiresApi(api = Build.VERSION_CODES.M) public void toggleFlashLight(View view) { if (toggleFlashLightOnOff.isChecked()) { // Exception is handled, because to check // whether the camera resource is being used by // another service or not. try { // true sets the torch in ON mode cameraManager.setTorchMode(getCameraID, true); // Inform the user about the flashlight // status using Toast message Toast.makeText(MainActivity.this, "Flashlight is turned ON", Toast.LENGTH_SHORT).show(); } catch (CameraAccessException e) { // prints stack trace on standard error // output error stream e.printStackTrace(); } } else { // Exception is handled, because to check // whether the camera resource is being used by // another service or not. try { // true sets the torch in OFF mode cameraManager.setTorchMode(getCameraID, false); // Inform the user about the flashlight // status using Toast message Toast.makeText(MainActivity.this, "Flashlight is turned OFF", Toast.LENGTH_SHORT).show(); } catch (CameraAccessException e) { // prints stack trace on standard error // output error stream e.printStackTrace(); } } } // when you click on button and torch open and // you do not close the tourch again this code // will off the tourch automatically @RequiresApi(api = Build.VERSION_CODES.M) @Override public void finish() { super.finish(); try { // true sets the torch in OFF mode cameraManager.setTorchMode(getCameraID, false); // Inform the user about the flashlight // status using Toast message Toast.makeText(SlaphScreen.this, "Flashlight is turned OFF", Toast.LENGTH_SHORT).show(); } catch (CameraAccessException e) { // prints stack trace on standard error // output error stream e.printStackTrace(); } }}
Read about the printStackTrace() function here: Throwable printStackTrace() method in Java with Examples.
After handling the ToggleButton one needs to test the application under a physical android device. Because if you run the application in the emulator which comes with android studio, the app is going to crash as soon as ToggleButton is clicked, because the emulator device wouldn’t come with the camera flash unit.
This method of accessing the camera hardware doesn’t require special permission from the user to access the camera unit. Because in this we are accessing the flash unit through only camera ID (whether it’s a front camera or back camera).
Output:
himanshugupta3385
simmytarika5
android
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n12 Jan, 2022"
},
{
"code": null,
"e": 514,
"s": 54,
"text": "All the beginners who are into the android development world should build a simple android application that can turn on/off the flashlight or torchlight by clicking a Button. So at the end of this article, one will be able to build their own android flashlight application with a simple layout. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 543,
"s": 514,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 705,
"s": 543,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 748,
"s": 705,
"text": "Step 2: Working with the activity_main.xml"
},
{
"code": null,
"e": 859,
"s": 748,
"text": "This layout contains a simple TextView, View (as divider), and one ToggleButton to toggle the Flashlight unit."
},
{
"code": null,
"e": 981,
"s": 859,
"text": "Please refer to How to add Toggle Button in an Android Application, to implement, and to see how the toggle button works."
},
{
"code": null,
"e": 1071,
"s": 981,
"text": "Invoke the following code in the activity_main.xml file or one can design custom widgets."
},
{
"code": null,
"e": 1075,
"s": 1071,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_marginTop=\"100dp\" android:text=\"Flashlight\" android:textColor=\"@color/colorPrimary\" android:textSize=\"50sp\" android:textStyle=\"bold|italic\" /> <!--This is the simple divider between above TextView and ToggleButton--> <View android:layout_width=\"match_parent\" android:layout_height=\"1dp\" android:layout_marginStart=\"32dp\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"32dp\" android:background=\"@android:color/darker_gray\" /> <!--This toggle button by default toggles between the ON and OFF we no need to set separate TextView for it--> <ToggleButton android:id=\"@+id/toggle_flashlight\" android:layout_width=\"200dp\" android:layout_height=\"75dp\" android:layout_gravity=\"center\" android:layout_marginTop=\"32dp\" android:onClick=\"toggleFlashLight\" android:textSize=\"25sp\" /> </LinearLayout>",
"e": 2531,
"s": 1075,
"text": null
},
{
"code": null,
"e": 2568,
"s": 2531,
"text": "The following output UI is produced:"
},
{
"code": null,
"e": 2664,
"s": 2568,
"text": "Step 3: Handling the Toggle Button widget to toggle ON or OFF inside the MainActivity.java file"
},
{
"code": null,
"e": 2804,
"s": 2664,
"text": "The complete code for the MainActivity.java file is given below. Comments are added inside the code to understand the code in more detail. "
},
{
"code": null,
"e": 2809,
"s": 2804,
"text": "Java"
},
{
"code": "import android.content.Context;import android.hardware.camera2.CameraAccessException;import android.hardware.camera2.CameraManager;import android.os.Build;import android.os.Bundle;import android.view.View;import android.widget.Toast;import android.widget.ToggleButton;import androidx.annotation.RequiresApi;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private ToggleButton toggleFlashLightOnOff; private CameraManager cameraManager; private String getCameraID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Register the ToggleButton with specific ID toggleFlashLightOnOff = findViewById(R.id.toggle_flashlight); // cameraManager to interact with camera devices cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE); // Exception is handled, because to check whether // the camera resource is being used by another // service or not. try { // O means back camera unit, // 1 means front camera unit getCameraID = cameraManager.getCameraIdList()[0]; } catch (CameraAccessException e) { e.printStackTrace(); } } // RequiresApi is set because, the devices which are // below API level 10 don't have the flash unit with // camera. @RequiresApi(api = Build.VERSION_CODES.M) public void toggleFlashLight(View view) { if (toggleFlashLightOnOff.isChecked()) { // Exception is handled, because to check // whether the camera resource is being used by // another service or not. try { // true sets the torch in ON mode cameraManager.setTorchMode(getCameraID, true); // Inform the user about the flashlight // status using Toast message Toast.makeText(MainActivity.this, \"Flashlight is turned ON\", Toast.LENGTH_SHORT).show(); } catch (CameraAccessException e) { // prints stack trace on standard error // output error stream e.printStackTrace(); } } else { // Exception is handled, because to check // whether the camera resource is being used by // another service or not. try { // true sets the torch in OFF mode cameraManager.setTorchMode(getCameraID, false); // Inform the user about the flashlight // status using Toast message Toast.makeText(MainActivity.this, \"Flashlight is turned OFF\", Toast.LENGTH_SHORT).show(); } catch (CameraAccessException e) { // prints stack trace on standard error // output error stream e.printStackTrace(); } } } // when you click on button and torch open and // you do not close the tourch again this code // will off the tourch automatically @RequiresApi(api = Build.VERSION_CODES.M) @Override public void finish() { super.finish(); try { // true sets the torch in OFF mode cameraManager.setTorchMode(getCameraID, false); // Inform the user about the flashlight // status using Toast message Toast.makeText(SlaphScreen.this, \"Flashlight is turned OFF\", Toast.LENGTH_SHORT).show(); } catch (CameraAccessException e) { // prints stack trace on standard error // output error stream e.printStackTrace(); } }}",
"e": 6508,
"s": 2809,
"text": null
},
{
"code": null,
"e": 6614,
"s": 6508,
"text": "Read about the printStackTrace() function here: Throwable printStackTrace() method in Java with Examples."
},
{
"code": null,
"e": 6929,
"s": 6614,
"text": "After handling the ToggleButton one needs to test the application under a physical android device. Because if you run the application in the emulator which comes with android studio, the app is going to crash as soon as ToggleButton is clicked, because the emulator device wouldn’t come with the camera flash unit."
},
{
"code": null,
"e": 7167,
"s": 6929,
"text": "This method of accessing the camera hardware doesn’t require special permission from the user to access the camera unit. Because in this we are accessing the flash unit through only camera ID (whether it’s a front camera or back camera)."
},
{
"code": null,
"e": 7175,
"s": 7167,
"text": "Output:"
},
{
"code": null,
"e": 7193,
"s": 7175,
"text": "himanshugupta3385"
},
{
"code": null,
"e": 7206,
"s": 7193,
"text": "simmytarika5"
},
{
"code": null,
"e": 7214,
"s": 7206,
"text": "android"
},
{
"code": null,
"e": 7222,
"s": 7214,
"text": "Android"
},
{
"code": null,
"e": 7227,
"s": 7222,
"text": "Java"
},
{
"code": null,
"e": 7232,
"s": 7227,
"text": "Java"
},
{
"code": null,
"e": 7240,
"s": 7232,
"text": "Android"
}
] |
JavaScript SyntaxError – Missing ) after argument list | 24 Jul, 2020
This JavaScript exception missing ) after argument list occurs if there is an error in function calls. This could be a typing mistake, a missing operator, or an unescaped string.
Message:
SyntaxError: Expected ')' (Edge)
SyntaxError: missing ) after argument list (Firefox)
Error Type:
SyntaxError
Cause of Error: Somewhere in the code, there is an error with function calls. This could be either be a typing mistake, a missing operator, or an unescaped string.
Example 1: In this example, there is a missing operator in string concatenation, So the error has occurred.
HTML
<!DOCTYPE html><html><head> <title>Syntax Error</title></head><body> <script> var str1 = 'This is '; var str2 = 'GeeksforGeeks'; document.write(str1 str2); </script></body></html>
Output(In console):
SyntaxError: missing ) after argument list
Example 2: In this example, there is a unescaped string, So the error has occurred.
HTML
<!DOCTYPE html><html><head> <title>Syntax Error</title></head><body> <script> var str1 = 'This is '; var str2 = 'GeeksforGeeks'; document.write(str1 \str2); </script></body></html>
Output(in console):
SyntaxError: missing ) after argument list
JavaScript-Errors
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Jul, 2020"
},
{
"code": null,
"e": 207,
"s": 28,
"text": "This JavaScript exception missing ) after argument list occurs if there is an error in function calls. This could be a typing mistake, a missing operator, or an unescaped string."
},
{
"code": null,
"e": 216,
"s": 207,
"text": "Message:"
},
{
"code": null,
"e": 303,
"s": 216,
"text": "SyntaxError: Expected ')' (Edge)\nSyntaxError: missing ) after argument list (Firefox)\n"
},
{
"code": null,
"e": 315,
"s": 303,
"text": "Error Type:"
},
{
"code": null,
"e": 328,
"s": 315,
"text": "SyntaxError\n"
},
{
"code": null,
"e": 492,
"s": 328,
"text": "Cause of Error: Somewhere in the code, there is an error with function calls. This could be either be a typing mistake, a missing operator, or an unescaped string."
},
{
"code": null,
"e": 600,
"s": 492,
"text": "Example 1: In this example, there is a missing operator in string concatenation, So the error has occurred."
},
{
"code": null,
"e": 605,
"s": 600,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>Syntax Error</title></head><body> <script> var str1 = 'This is '; var str2 = 'GeeksforGeeks'; document.write(str1 str2); </script></body></html>",
"e": 815,
"s": 605,
"text": null
},
{
"code": null,
"e": 835,
"s": 815,
"text": "Output(In console):"
},
{
"code": null,
"e": 879,
"s": 835,
"text": "SyntaxError: missing ) after argument list\n"
},
{
"code": null,
"e": 963,
"s": 879,
"text": "Example 2: In this example, there is a unescaped string, So the error has occurred."
},
{
"code": null,
"e": 968,
"s": 963,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>Syntax Error</title></head><body> <script> var str1 = 'This is '; var str2 = 'GeeksforGeeks'; document.write(str1 \\str2); </script></body></html>",
"e": 1179,
"s": 968,
"text": null
},
{
"code": null,
"e": 1199,
"s": 1179,
"text": "Output(in console):"
},
{
"code": null,
"e": 1243,
"s": 1199,
"text": "SyntaxError: missing ) after argument list\n"
},
{
"code": null,
"e": 1261,
"s": 1243,
"text": "JavaScript-Errors"
},
{
"code": null,
"e": 1272,
"s": 1261,
"text": "JavaScript"
},
{
"code": null,
"e": 1289,
"s": 1272,
"text": "Web Technologies"
}
] |
Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) | 17 Jun, 2022
A disjoint-set data structure is a data structure that keeps track of a set of elements partitioned into a number of disjoint (non-overlapping) subsets. A union-find algorithm is an algorithm that performs two useful operations on such a data structure:
Find: Determine which subset a particular element is in. This can be used for determining if two elements are in the same subset.
Union: Join two subsets into a single subset. Here first we have to check if the two subsets belong to same set. If no, then we cannot perform union.
In this post, we will discuss the application of Disjoint Set Data Structure. The application is to check whether a given graph contains a cycle or not.
Union-Find Algorithm can be used to check whether an undirected graph contains cycle or not. Note that we have discussed an algorithm to detect cycle. This is another method based on Union-Find. This method assumes that the graph doesn’t contain any self-loops.
We can keep track of the subsets in a 1D array, let’s call it parent[].Let us consider the following graph:
For each edge, make subsets using both the vertices of the edge. If both the vertices are in the same subset, a cycle is found.
Initially, all slots of parent array are initialized to -1 (means there is only one item in every subset).
0 1 2
-1 -1 -1
Now process all edges one by one.Edge 0-1: Find the subsets in which vertices 0 and 1 are. Since they are in different subsets, we take the union of them. For taking the union, either make node 0 as parent of node 1 or vice-versa.
0 1 2 <----- 1 is made parent of 0 (1 is now representative of subset {0, 1})
1 -1 -1
Edge 1-2: 1 is in subset 1 and 2 is in subset 2. So, take union.
0 1 2 <----- 2 is made parent of 1 (2 is now representative of subset {0, 1, 2})
1 2 -1
Edge 0-2: 0 is in subset 2 and 2 is also in subset 2. Hence, including this edge forms a cycle.How subset of 0 is same as 2? 0->1->2 // 1 is parent of 0 and 2 is parent of 1
Based on the above explanation, below are implementations:
C++
C
Java
Python3
C#
Javascript
// A union-find algorithm to detect cycle in a graph#include <bits/stdc++.h>using namespace std; // a structure to represent an edge in graphclass Edge{public: int src, dest;}; // a structure to represent a graphclass Graph{public: // V-> Number of vertices, E-> Number of edges int V, E; // graph is represented as an array of edges Edge* edge;}; // Creates a graph with V vertices and E edgesGraph* createGraph(int V, int E){ Graph* graph = new Graph(); graph->V = V; graph->E = E; graph->edge = new Edge[graph->E * sizeof(Edge)]; return graph;} // A utility function to find the subset of an element iint find(int parent[], int i){ if (parent[i] == -1) return i; return find(parent, parent[i]);} // A utility function to do union of two subsetsvoid Union(int parent[], int x, int y){ parent[x] = y;} // The main function to check whether a given graph contains// cycle or notint isCycle(Graph* graph){ // Allocate memory for creating V subsets int* parent = new int[graph->V * sizeof(int)]; // Initialize all subsets as single element sets memset(parent, -1, sizeof(int) * graph->V); // Iterate through all edges of graph, find subset of // both vertices of every edge, if both subsets are // same, then there is cycle in graph. for (int i = 0; i < graph->E; ++i) { int x = find(parent, graph->edge[i].src); int y = find(parent, graph->edge[i].dest); if (x == y) return 1; Union(parent, x, y); } return 0;} // Driver codeint main(){ /* Let us create the following graph 0 | \ | \ 1---2 */ int V = 3, E = 3; Graph* graph = createGraph(V, E); // add edge 0-1 graph->edge[0].src = 0; graph->edge[0].dest = 1; // add edge 1-2 graph->edge[1].src = 1; graph->edge[1].dest = 2; // add edge 0-2 graph->edge[2].src = 0; graph->edge[2].dest = 2; if (isCycle(graph)) cout << "graph contains cycle"; else cout << "graph doesn't contain cycle"; return 0;} // This code is contributed by rathbhupendra
// A union-find algorithm to detect cycle in a graph#include <stdio.h>#include <stdlib.h>#include <string.h> // a structure to represent an edge in graphstruct Edge{ int src, dest;}; // a structure to represent a graphstruct Graph{ // V-> Number of vertices, E-> Number of edges int V, E; // graph is represented as an array of edges struct Edge* edge;}; // Creates a graph with V vertices and E edgesstruct Graph* createGraph(int V, int E){ struct Graph* graph = (struct Graph*) malloc( sizeof(struct Graph) ); graph->V = V; graph->E = E; graph->edge = (struct Edge*) malloc( graph->E * sizeof( struct Edge ) ); return graph;} // A utility function to find the subset of an element iint find(int parent[], int i){ if (parent[i] == -1) return i; return find(parent, parent[i]);} // A utility function to do union of two subsetsvoid Union(int parent[], int x, int y){ parent[x] = y;} // The main function to check whether a given graph contains// cycle or notint isCycle( struct Graph* graph ){ // Allocate memory for creating V subsets int *parent = (int*) malloc( graph->V * sizeof(int) ); // Initialize all subsets as single element sets memset(parent, -1, sizeof(int) * graph->V); // Iterate through all edges of graph, find subset of both // vertices of every edge, if both subsets are same, then // there is cycle in graph. for(int i = 0; i < graph->E; ++i) { int x = find(parent, graph->edge[i].src); int y = find(parent, graph->edge[i].dest); if (x == y) return 1; Union(parent, x, y); } return 0;} // Driver program to test above functionsint main(){ /* Let us create the following graph 0 | \ | \ 1---2 */ int V = 3, E = 3; struct Graph* graph = createGraph(V, E); // add edge 0-1 graph->edge[0].src = 0; graph->edge[0].dest = 1; // add edge 1-2 graph->edge[1].src = 1; graph->edge[1].dest = 2; // add edge 0-2 graph->edge[2].src = 0; graph->edge[2].dest = 2; if (isCycle(graph)) printf( "graph contains cycle" ); else printf( "graph doesn't contain cycle" ); return 0;}
// Java Program for union-find algorithm to detect cycle in a graphimport java.util.*;import java.lang.*;import java.io.*; class Graph{ int V, E; // V-> no. of vertices & E->no.of edges Edge edge[]; // /collection of all edges class Edge { int src, dest; }; // Creates a graph with V vertices and E edges Graph(int v,int e) { V = v; E = e; edge = new Edge[E]; for (int i=0; i<e; ++i) edge[i] = new Edge(); } // A utility function to find the subset of an element i int find(int parent[], int i) { if (parent[i] == -1) return i; return find(parent, parent[i]); } // A utility function to do union of two subsets void Union(int parent[], int x, int y) { parent[x] = y; } // The main function to check whether a given graph // contains cycle or not int isCycle( Graph graph) { // Allocate memory for creating V subsets int parent[] = new int[graph.V]; // Initialize all subsets as single element sets for (int i=0; i<graph.V; ++i) parent[i]=-1; // Iterate through all edges of graph, find subset of both // vertices of every edge, if both subsets are same, then // there is cycle in graph. for (int i = 0; i < graph.E; ++i) { int x = graph.find(parent, graph.edge[i].src); int y = graph.find(parent, graph.edge[i].dest); if (x == y) return 1; graph.Union(parent, x, y); } return 0; } // Driver Method public static void main (String[] args) { /* Let us create the following graph 0 | \ | \ 1---2 */ int V = 3, E = 3; Graph graph = new Graph(V, E); // add edge 0-1 graph.edge[0].src = 0; graph.edge[0].dest = 1; // add edge 1-2 graph.edge[1].src = 1; graph.edge[1].dest = 2; // add edge 0-2 graph.edge[2].src = 0; graph.edge[2].dest = 2; if (graph.isCycle(graph)==1) System.out.println( "graph contains cycle" ); else System.out.println( "graph doesn't contain cycle" ); }}
# Python Program for union-find algorithm to detect cycle in a undirected graph# we have one egde for any two vertex i.e 1-2 is either 1-2 or 2-1 but not both from collections import defaultdict #This class represents a undirected graph using adjacency list representationclass Graph: def __init__(self,vertices): self.V= vertices #No. of vertices self.graph = defaultdict(list) # default dictionary to store graph # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) # A utility function to find the subset of an element i def find_parent(self, parent,i): if parent[i] == -1: return i if parent[i]!= -1: return self.find_parent(parent,parent[i]) # A utility function to do union of two subsets def union(self,parent,x,y): parent[x] = y # The main function to check whether a given graph # contains cycle or not def isCyclic(self): # Allocate memory for creating V subsets and # Initialize all subsets as single element sets parent = [-1]*(self.V) # Iterate through all edges of graph, find subset of both # vertices of every edge, if both subsets are same, then # there is cycle in graph. for i in self.graph: for j in self.graph[i]: x = self.find_parent(parent, i) y = self.find_parent(parent, j) if x == y: return True self.union(parent,x,y) # Create a graph given in the above diagramg = Graph(3)g.addEdge(0, 1)g.addEdge(1, 2)g.addEdge(2, 0) if g.isCyclic(): print ("Graph contains cycle")else : print ("Graph does not contain cycle ") #This code is contributed by Neelam Yadav
// C# Program for union-find// algorithm to detect cycle// in a graphusing System;class Graph{ // V-> no. of vertices &// E->no.of edges public int V, E; // collection of all edgespublic Edge []edge; class Edge{ public int src, dest;}; // Creates a graph with V// vertices and E edgespublic Graph(int v,int e){ V = v; E = e; edge = new Edge[E]; for (int i = 0; i < e; ++i) edge[i] = new Edge();} // A utility function to find// the subset of an element iint find(int []parent, int i){ if (parent[i] == -1) return i; return find(parent, parent[i]);} // A utility function to do// union of two subsetsvoid Union(int []parent, int x, int y){ parent[x] = y;} // The main function to check// whether a given graph// contains cycle or notint isCycle(Graph graph){ // Allocate memory for // creating V subsets int []parent = new int[graph.V]; // Initialize all subsets as // single element sets for (int i = 0; i < graph.V; ++i) parent[i] =- 1; // Iterate through all edges of graph, // find subset of both vertices of every // edge, if both subsets are same, then // there is cycle in graph. for (int i = 0; i < graph.E; ++i) { int x = graph.find(parent, graph.edge[i].src); int y = graph.find(parent, graph.edge[i].dest); if (x == y) return 1; graph.Union(parent, x, y); } return 0;} // Driver codepublic static void Main(String[] args){ /* Let us create the following graph 0 | \ | \ 1---2 */ int V = 3, E = 3; Graph graph = new Graph(V, E); // add edge 0-1 graph.edge[0].src = 0; graph.edge[0].dest = 1; // add edge 1-2 graph.edge[1].src = 1; graph.edge[1].dest = 2; // add edge 0-2 graph.edge[2].src = 0; graph.edge[2].dest = 2; if (graph.isCycle(graph) == 1) Console.WriteLine("graph contains cycle"); else Console.WriteLine("graph doesn't contain cycle");}} // This code is contributed by Princi Singh
<script> // Javascript program for union-find// algorithm to detect cycle// in a graph // V-> no. of vertices &// E->no.of edges var V, E; // Collection of all edgesvar edge; class Edge{ constructor() { this.src = 0; this.dest = 0; }}; // Creates a graph with V// vertices and E edgesfunction initialize(v,e){ V = v; E = e; edge = Array.from(Array(E), () => Array());} // A utility function to find// the subset of an element ifunction find(parent, i){ if (parent[i] == -1) return i; return find(parent, parent[i]);} // A utility function to do// union of two subsetsfunction Union(parent, x, y){ parent[x] = y;} // The main function to check// whether a given graph// contains cycle or notfunction isCycle(){ // Allocate memory for // creating V subsets var parent = Array(V).fill(0); // Initialize all subsets as // single element sets for(var i = 0; i < V; ++i) parent[i] =- 1; // Iterate through all edges of graph, // find subset of both vertices of every // edge, if both subsets are same, then // there is cycle in graph. for (var i = 0; i < E; ++i) { var x = find(parent, edge[i].src); var y = find(parent, edge[i].dest); if (x == y) return 1; Union(parent, x, y); } return 0;} // Driver code/* Let us create the following graph 0 | \ | \ 1---2 */var V = 3, E = 3;initialize(V, E); // Add edge 0-1edge[0].src = 0;edge[0].dest = 1; // Add edge 1-2edge[1].src = 1;edge[1].dest = 2; // Add edge 0-2edge[2].src = 0;edge[2].dest = 2; if (isCycle() == 1) document.write("graph contains cycle");else document.write("graph doesn't contain cycle"); // This code is contributed by rutvik_56 </script>
graph contains cycle
Note that the implementation of union() and find() is naive and takes O(n) time in the worst case. These methods can be improved to O(Logn) using Union by Rank or Height. We will soon be discussing Union by Rank in a separate post.
Union-Find Algorithm | Set 1 (Detect Cycle in an Undirected Graph) | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersUnion-Find Algorithm | Set 1 (Detect Cycle in an Undirected Graph) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 10:18•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=mHz-mx-8lJ8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Related Articles : Union-Find Algorithm | Set 2 (Union By Rank and Path Compression) Disjoint Set Data Structures (Java Implementation) Greedy Algorithms | Set 2 (Kruskal’s Minimum Spanning Tree Algorithm) Job Sequencing Problem | Set 2 (Using Disjoint Set)
avinashr175
KhushalVyas
rathbhupendra
f2008700
princi singh
rahulsharma9
gsivaram1998
rutvik_56
vector01
amartyaghoshgfg
hardikkoriintern
graph-cycle
union-find
Graph
Graph
union-find
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Breadth First Search or BFS for a Graph
Depth First Search or DFS for a Graph
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Graph and its representations
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Find if there is a path between two vertices in a directed graph
Introduction to Data Structures
Floyd Warshall Algorithm | DP-16
What is Data Structure: Types, Classifications and Applications | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Jun, 2022"
},
{
"code": null,
"e": 308,
"s": 54,
"text": "A disjoint-set data structure is a data structure that keeps track of a set of elements partitioned into a number of disjoint (non-overlapping) subsets. A union-find algorithm is an algorithm that performs two useful operations on such a data structure:"
},
{
"code": null,
"e": 438,
"s": 308,
"text": "Find: Determine which subset a particular element is in. This can be used for determining if two elements are in the same subset."
},
{
"code": null,
"e": 588,
"s": 438,
"text": "Union: Join two subsets into a single subset. Here first we have to check if the two subsets belong to same set. If no, then we cannot perform union."
},
{
"code": null,
"e": 741,
"s": 588,
"text": "In this post, we will discuss the application of Disjoint Set Data Structure. The application is to check whether a given graph contains a cycle or not."
},
{
"code": null,
"e": 1004,
"s": 741,
"text": "Union-Find Algorithm can be used to check whether an undirected graph contains cycle or not. Note that we have discussed an algorithm to detect cycle. This is another method based on Union-Find. This method assumes that the graph doesn’t contain any self-loops. "
},
{
"code": null,
"e": 1113,
"s": 1004,
"text": "We can keep track of the subsets in a 1D array, let’s call it parent[].Let us consider the following graph: "
},
{
"code": null,
"e": 1241,
"s": 1113,
"text": "For each edge, make subsets using both the vertices of the edge. If both the vertices are in the same subset, a cycle is found."
},
{
"code": null,
"e": 1348,
"s": 1241,
"text": "Initially, all slots of parent array are initialized to -1 (means there is only one item in every subset)."
},
{
"code": null,
"e": 1368,
"s": 1348,
"text": "0 1 2\n-1 -1 -1"
},
{
"code": null,
"e": 1600,
"s": 1368,
"text": "Now process all edges one by one.Edge 0-1: Find the subsets in which vertices 0 and 1 are. Since they are in different subsets, we take the union of them. For taking the union, either make node 0 as parent of node 1 or vice-versa. "
},
{
"code": null,
"e": 1695,
"s": 1600,
"text": "0 1 2 <----- 1 is made parent of 0 (1 is now representative of subset {0, 1})\n1 -1 -1"
},
{
"code": null,
"e": 1760,
"s": 1695,
"text": "Edge 1-2: 1 is in subset 1 and 2 is in subset 2. So, take union."
},
{
"code": null,
"e": 1858,
"s": 1760,
"text": "0 1 2 <----- 2 is made parent of 1 (2 is now representative of subset {0, 1, 2})\n1 2 -1"
},
{
"code": null,
"e": 2034,
"s": 1858,
"text": "Edge 0-2: 0 is in subset 2 and 2 is also in subset 2. Hence, including this edge forms a cycle.How subset of 0 is same as 2? 0->1->2 // 1 is parent of 0 and 2 is parent of 1 "
},
{
"code": null,
"e": 2094,
"s": 2034,
"text": "Based on the above explanation, below are implementations: "
},
{
"code": null,
"e": 2098,
"s": 2094,
"text": "C++"
},
{
"code": null,
"e": 2100,
"s": 2098,
"text": "C"
},
{
"code": null,
"e": 2105,
"s": 2100,
"text": "Java"
},
{
"code": null,
"e": 2113,
"s": 2105,
"text": "Python3"
},
{
"code": null,
"e": 2116,
"s": 2113,
"text": "C#"
},
{
"code": null,
"e": 2127,
"s": 2116,
"text": "Javascript"
},
{
"code": "// A union-find algorithm to detect cycle in a graph#include <bits/stdc++.h>using namespace std; // a structure to represent an edge in graphclass Edge{public: int src, dest;}; // a structure to represent a graphclass Graph{public: // V-> Number of vertices, E-> Number of edges int V, E; // graph is represented as an array of edges Edge* edge;}; // Creates a graph with V vertices and E edgesGraph* createGraph(int V, int E){ Graph* graph = new Graph(); graph->V = V; graph->E = E; graph->edge = new Edge[graph->E * sizeof(Edge)]; return graph;} // A utility function to find the subset of an element iint find(int parent[], int i){ if (parent[i] == -1) return i; return find(parent, parent[i]);} // A utility function to do union of two subsetsvoid Union(int parent[], int x, int y){ parent[x] = y;} // The main function to check whether a given graph contains// cycle or notint isCycle(Graph* graph){ // Allocate memory for creating V subsets int* parent = new int[graph->V * sizeof(int)]; // Initialize all subsets as single element sets memset(parent, -1, sizeof(int) * graph->V); // Iterate through all edges of graph, find subset of // both vertices of every edge, if both subsets are // same, then there is cycle in graph. for (int i = 0; i < graph->E; ++i) { int x = find(parent, graph->edge[i].src); int y = find(parent, graph->edge[i].dest); if (x == y) return 1; Union(parent, x, y); } return 0;} // Driver codeint main(){ /* Let us create the following graph 0 | \\ | \\ 1---2 */ int V = 3, E = 3; Graph* graph = createGraph(V, E); // add edge 0-1 graph->edge[0].src = 0; graph->edge[0].dest = 1; // add edge 1-2 graph->edge[1].src = 1; graph->edge[1].dest = 2; // add edge 0-2 graph->edge[2].src = 0; graph->edge[2].dest = 2; if (isCycle(graph)) cout << \"graph contains cycle\"; else cout << \"graph doesn't contain cycle\"; return 0;} // This code is contributed by rathbhupendra",
"e": 4233,
"s": 2127,
"text": null
},
{
"code": "// A union-find algorithm to detect cycle in a graph#include <stdio.h>#include <stdlib.h>#include <string.h> // a structure to represent an edge in graphstruct Edge{ int src, dest;}; // a structure to represent a graphstruct Graph{ // V-> Number of vertices, E-> Number of edges int V, E; // graph is represented as an array of edges struct Edge* edge;}; // Creates a graph with V vertices and E edgesstruct Graph* createGraph(int V, int E){ struct Graph* graph = (struct Graph*) malloc( sizeof(struct Graph) ); graph->V = V; graph->E = E; graph->edge = (struct Edge*) malloc( graph->E * sizeof( struct Edge ) ); return graph;} // A utility function to find the subset of an element iint find(int parent[], int i){ if (parent[i] == -1) return i; return find(parent, parent[i]);} // A utility function to do union of two subsetsvoid Union(int parent[], int x, int y){ parent[x] = y;} // The main function to check whether a given graph contains// cycle or notint isCycle( struct Graph* graph ){ // Allocate memory for creating V subsets int *parent = (int*) malloc( graph->V * sizeof(int) ); // Initialize all subsets as single element sets memset(parent, -1, sizeof(int) * graph->V); // Iterate through all edges of graph, find subset of both // vertices of every edge, if both subsets are same, then // there is cycle in graph. for(int i = 0; i < graph->E; ++i) { int x = find(parent, graph->edge[i].src); int y = find(parent, graph->edge[i].dest); if (x == y) return 1; Union(parent, x, y); } return 0;} // Driver program to test above functionsint main(){ /* Let us create the following graph 0 | \\ | \\ 1---2 */ int V = 3, E = 3; struct Graph* graph = createGraph(V, E); // add edge 0-1 graph->edge[0].src = 0; graph->edge[0].dest = 1; // add edge 1-2 graph->edge[1].src = 1; graph->edge[1].dest = 2; // add edge 0-2 graph->edge[2].src = 0; graph->edge[2].dest = 2; if (isCycle(graph)) printf( \"graph contains cycle\" ); else printf( \"graph doesn't contain cycle\" ); return 0;}",
"e": 6449,
"s": 4233,
"text": null
},
{
"code": "// Java Program for union-find algorithm to detect cycle in a graphimport java.util.*;import java.lang.*;import java.io.*; class Graph{ int V, E; // V-> no. of vertices & E->no.of edges Edge edge[]; // /collection of all edges class Edge { int src, dest; }; // Creates a graph with V vertices and E edges Graph(int v,int e) { V = v; E = e; edge = new Edge[E]; for (int i=0; i<e; ++i) edge[i] = new Edge(); } // A utility function to find the subset of an element i int find(int parent[], int i) { if (parent[i] == -1) return i; return find(parent, parent[i]); } // A utility function to do union of two subsets void Union(int parent[], int x, int y) { parent[x] = y; } // The main function to check whether a given graph // contains cycle or not int isCycle( Graph graph) { // Allocate memory for creating V subsets int parent[] = new int[graph.V]; // Initialize all subsets as single element sets for (int i=0; i<graph.V; ++i) parent[i]=-1; // Iterate through all edges of graph, find subset of both // vertices of every edge, if both subsets are same, then // there is cycle in graph. for (int i = 0; i < graph.E; ++i) { int x = graph.find(parent, graph.edge[i].src); int y = graph.find(parent, graph.edge[i].dest); if (x == y) return 1; graph.Union(parent, x, y); } return 0; } // Driver Method public static void main (String[] args) { /* Let us create the following graph 0 | \\ | \\ 1---2 */ int V = 3, E = 3; Graph graph = new Graph(V, E); // add edge 0-1 graph.edge[0].src = 0; graph.edge[0].dest = 1; // add edge 1-2 graph.edge[1].src = 1; graph.edge[1].dest = 2; // add edge 0-2 graph.edge[2].src = 0; graph.edge[2].dest = 2; if (graph.isCycle(graph)==1) System.out.println( \"graph contains cycle\" ); else System.out.println( \"graph doesn't contain cycle\" ); }}",
"e": 8689,
"s": 6449,
"text": null
},
{
"code": "# Python Program for union-find algorithm to detect cycle in a undirected graph# we have one egde for any two vertex i.e 1-2 is either 1-2 or 2-1 but not both from collections import defaultdict #This class represents a undirected graph using adjacency list representationclass Graph: def __init__(self,vertices): self.V= vertices #No. of vertices self.graph = defaultdict(list) # default dictionary to store graph # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) # A utility function to find the subset of an element i def find_parent(self, parent,i): if parent[i] == -1: return i if parent[i]!= -1: return self.find_parent(parent,parent[i]) # A utility function to do union of two subsets def union(self,parent,x,y): parent[x] = y # The main function to check whether a given graph # contains cycle or not def isCyclic(self): # Allocate memory for creating V subsets and # Initialize all subsets as single element sets parent = [-1]*(self.V) # Iterate through all edges of graph, find subset of both # vertices of every edge, if both subsets are same, then # there is cycle in graph. for i in self.graph: for j in self.graph[i]: x = self.find_parent(parent, i) y = self.find_parent(parent, j) if x == y: return True self.union(parent,x,y) # Create a graph given in the above diagramg = Graph(3)g.addEdge(0, 1)g.addEdge(1, 2)g.addEdge(2, 0) if g.isCyclic(): print (\"Graph contains cycle\")else : print (\"Graph does not contain cycle \") #This code is contributed by Neelam Yadav",
"e": 10467,
"s": 8689,
"text": null
},
{
"code": "// C# Program for union-find// algorithm to detect cycle// in a graphusing System;class Graph{ // V-> no. of vertices &// E->no.of edges public int V, E; // collection of all edgespublic Edge []edge; class Edge{ public int src, dest;}; // Creates a graph with V// vertices and E edgespublic Graph(int v,int e){ V = v; E = e; edge = new Edge[E]; for (int i = 0; i < e; ++i) edge[i] = new Edge();} // A utility function to find// the subset of an element iint find(int []parent, int i){ if (parent[i] == -1) return i; return find(parent, parent[i]);} // A utility function to do// union of two subsetsvoid Union(int []parent, int x, int y){ parent[x] = y;} // The main function to check// whether a given graph// contains cycle or notint isCycle(Graph graph){ // Allocate memory for // creating V subsets int []parent = new int[graph.V]; // Initialize all subsets as // single element sets for (int i = 0; i < graph.V; ++i) parent[i] =- 1; // Iterate through all edges of graph, // find subset of both vertices of every // edge, if both subsets are same, then // there is cycle in graph. for (int i = 0; i < graph.E; ++i) { int x = graph.find(parent, graph.edge[i].src); int y = graph.find(parent, graph.edge[i].dest); if (x == y) return 1; graph.Union(parent, x, y); } return 0;} // Driver codepublic static void Main(String[] args){ /* Let us create the following graph 0 | \\ | \\ 1---2 */ int V = 3, E = 3; Graph graph = new Graph(V, E); // add edge 0-1 graph.edge[0].src = 0; graph.edge[0].dest = 1; // add edge 1-2 graph.edge[1].src = 1; graph.edge[1].dest = 2; // add edge 0-2 graph.edge[2].src = 0; graph.edge[2].dest = 2; if (graph.isCycle(graph) == 1) Console.WriteLine(\"graph contains cycle\"); else Console.WriteLine(\"graph doesn't contain cycle\");}} // This code is contributed by Princi Singh",
"e": 12455,
"s": 10467,
"text": null
},
{
"code": "<script> // Javascript program for union-find// algorithm to detect cycle// in a graph // V-> no. of vertices &// E->no.of edges var V, E; // Collection of all edgesvar edge; class Edge{ constructor() { this.src = 0; this.dest = 0; }}; // Creates a graph with V// vertices and E edgesfunction initialize(v,e){ V = v; E = e; edge = Array.from(Array(E), () => Array());} // A utility function to find// the subset of an element ifunction find(parent, i){ if (parent[i] == -1) return i; return find(parent, parent[i]);} // A utility function to do// union of two subsetsfunction Union(parent, x, y){ parent[x] = y;} // The main function to check// whether a given graph// contains cycle or notfunction isCycle(){ // Allocate memory for // creating V subsets var parent = Array(V).fill(0); // Initialize all subsets as // single element sets for(var i = 0; i < V; ++i) parent[i] =- 1; // Iterate through all edges of graph, // find subset of both vertices of every // edge, if both subsets are same, then // there is cycle in graph. for (var i = 0; i < E; ++i) { var x = find(parent, edge[i].src); var y = find(parent, edge[i].dest); if (x == y) return 1; Union(parent, x, y); } return 0;} // Driver code/* Let us create the following graph 0 | \\ | \\ 1---2 */var V = 3, E = 3;initialize(V, E); // Add edge 0-1edge[0].src = 0;edge[0].dest = 1; // Add edge 1-2edge[1].src = 1;edge[1].dest = 2; // Add edge 0-2edge[2].src = 0;edge[2].dest = 2; if (isCycle() == 1) document.write(\"graph contains cycle\");else document.write(\"graph doesn't contain cycle\"); // This code is contributed by rutvik_56 </script>",
"e": 14321,
"s": 12455,
"text": null
},
{
"code": null,
"e": 14342,
"s": 14321,
"text": "graph contains cycle"
},
{
"code": null,
"e": 14575,
"s": 14342,
"text": "Note that the implementation of union() and find() is naive and takes O(n) time in the worst case. These methods can be improved to O(Logn) using Union by Rank or Height. We will soon be discussing Union by Rank in a separate post. "
},
{
"code": null,
"e": 15526,
"s": 14575,
"text": "Union-Find Algorithm | Set 1 (Detect Cycle in an Undirected Graph) | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersUnion-Find Algorithm | Set 1 (Detect Cycle in an Undirected Graph) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 10:18•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=mHz-mx-8lJ8\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 15784,
"s": 15526,
"text": "Related Articles : Union-Find Algorithm | Set 2 (Union By Rank and Path Compression) Disjoint Set Data Structures (Java Implementation) Greedy Algorithms | Set 2 (Kruskal’s Minimum Spanning Tree Algorithm) Job Sequencing Problem | Set 2 (Using Disjoint Set)"
},
{
"code": null,
"e": 15796,
"s": 15784,
"text": "avinashr175"
},
{
"code": null,
"e": 15808,
"s": 15796,
"text": "KhushalVyas"
},
{
"code": null,
"e": 15822,
"s": 15808,
"text": "rathbhupendra"
},
{
"code": null,
"e": 15831,
"s": 15822,
"text": "f2008700"
},
{
"code": null,
"e": 15844,
"s": 15831,
"text": "princi singh"
},
{
"code": null,
"e": 15857,
"s": 15844,
"text": "rahulsharma9"
},
{
"code": null,
"e": 15870,
"s": 15857,
"text": "gsivaram1998"
},
{
"code": null,
"e": 15880,
"s": 15870,
"text": "rutvik_56"
},
{
"code": null,
"e": 15889,
"s": 15880,
"text": "vector01"
},
{
"code": null,
"e": 15905,
"s": 15889,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 15922,
"s": 15905,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 15934,
"s": 15922,
"text": "graph-cycle"
},
{
"code": null,
"e": 15945,
"s": 15934,
"text": "union-find"
},
{
"code": null,
"e": 15951,
"s": 15945,
"text": "Graph"
},
{
"code": null,
"e": 15957,
"s": 15951,
"text": "Graph"
},
{
"code": null,
"e": 15968,
"s": 15957,
"text": "union-find"
},
{
"code": null,
"e": 16066,
"s": 15968,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 16106,
"s": 16066,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 16144,
"s": 16106,
"text": "Depth First Search or DFS for a Graph"
},
{
"code": null,
"e": 16195,
"s": 16144,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 16246,
"s": 16195,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 16276,
"s": 16246,
"text": "Graph and its representations"
},
{
"code": null,
"e": 16334,
"s": 16276,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 16399,
"s": 16334,
"text": "Find if there is a path between two vertices in a directed graph"
},
{
"code": null,
"e": 16431,
"s": 16399,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 16464,
"s": 16431,
"text": "Floyd Warshall Algorithm | DP-16"
}
] |
How to find all children with a specified class using jQuery ? | 29 Nov, 2021
There are lots of javascript libraries like – anime.js, screenfull.js, moment.js, etc. JQuery is also a part of javascript libraries. It is used to simplify the code. It is a lightweight and feature-rich library.
In this article, we will learn how to find all children with a specified class of each division.
.children(selector) – In jquery you can achieve this task by using the method named .children(). It takes the selector as a parameter and changes the children element with the specified name.
Example 1:
HTML
<!DOCTYPE html><html> <head> <script src="https://code.jquery.com/jquery-git.js"> </script> <style> body { font-size: 20px; font-style: italic; background-color: green; text-align: center; } </style></head> <body> <div> <h1 class="child"> GeeksForGeeks </h1> <span> This is a span in div element. (children but not specified) </span> <p class="child"> This is a paragraph with specified class in a div element. </p> <div class="child"> This is inner div with specified class in a div element. </div> <p> This is another paragraph in div element.(children but not specified) </p> </div> <script> $("div").children(".child").css({ "background-color": "lightgreen", "border-style": "inset" }); </script></body> </html>
Output:
Explanation: The div element has 5 children ( 1 heading, 1 span, 1 inner div, and 3 paragraphs). In the code, we have specified three-element with class=”child” i.e. two paragraphs and one div. You can notice that only specified elements get affected and change their style property.
Example 2:
HTML
<!DOCTYPE html><html> <head> <script src="https://code.jquery.com/jquery-git.js"> </script> <style> body { font-size: 20px; font-style: italic; background-color: green; text-align: center; } </style></head> <body> <div> <h1>GeeksForGeeks</h1> <p> class with prime will only get different style property </p> <p>'1' is not a prime number.</p> <p class="prime">'2' is a prime number.</p> <div class="prime">'3' is a prime number.</div> <p>'4' is not a prime number.</p> <p class="prime">'5' is a prime number</p> </div> <script> $("div").children(".prime").css({ "background-color": "lightgreen", "border-style": "inset" }); </script></body> </html>
Output –
surindertarika1234
CSS-Questions
HTML-Property
HTML-Questions
HTML-Tags
jQuery-Methods
jQuery-Questions
Picked
CSS
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of CSS (Cascading Style Sheet)
How to set space between the flexbox ?
Design a Tribute Page using HTML & CSS
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Types of CSS (Cascading Style Sheet) | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Nov, 2021"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "There are lots of javascript libraries like – anime.js, screenfull.js, moment.js, etc. JQuery is also a part of javascript libraries. It is used to simplify the code. It is a lightweight and feature-rich library. "
},
{
"code": null,
"e": 340,
"s": 242,
"text": "In this article, we will learn how to find all children with a specified class of each division. "
},
{
"code": null,
"e": 533,
"s": 340,
"text": ".children(selector) – In jquery you can achieve this task by using the method named .children(). It takes the selector as a parameter and changes the children element with the specified name. "
},
{
"code": null,
"e": 544,
"s": 533,
"text": "Example 1:"
},
{
"code": null,
"e": 549,
"s": 544,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://code.jquery.com/jquery-git.js\"> </script> <style> body { font-size: 20px; font-style: italic; background-color: green; text-align: center; } </style></head> <body> <div> <h1 class=\"child\"> GeeksForGeeks </h1> <span> This is a span in div element. (children but not specified) </span> <p class=\"child\"> This is a paragraph with specified class in a div element. </p> <div class=\"child\"> This is inner div with specified class in a div element. </div> <p> This is another paragraph in div element.(children but not specified) </p> </div> <script> $(\"div\").children(\".child\").css({ \"background-color\": \"lightgreen\", \"border-style\": \"inset\" }); </script></body> </html>",
"e": 1561,
"s": 549,
"text": null
},
{
"code": null,
"e": 1569,
"s": 1561,
"text": "Output:"
},
{
"code": null,
"e": 1853,
"s": 1569,
"text": "Explanation: The div element has 5 children ( 1 heading, 1 span, 1 inner div, and 3 paragraphs). In the code, we have specified three-element with class=”child” i.e. two paragraphs and one div. You can notice that only specified elements get affected and change their style property."
},
{
"code": null,
"e": 1864,
"s": 1853,
"text": "Example 2:"
},
{
"code": null,
"e": 1869,
"s": 1864,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://code.jquery.com/jquery-git.js\"> </script> <style> body { font-size: 20px; font-style: italic; background-color: green; text-align: center; } </style></head> <body> <div> <h1>GeeksForGeeks</h1> <p> class with prime will only get different style property </p> <p>'1' is not a prime number.</p> <p class=\"prime\">'2' is a prime number.</p> <div class=\"prime\">'3' is a prime number.</div> <p>'4' is not a prime number.</p> <p class=\"prime\">'5' is a prime number</p> </div> <script> $(\"div\").children(\".prime\").css({ \"background-color\": \"lightgreen\", \"border-style\": \"inset\" }); </script></body> </html>",
"e": 2737,
"s": 1869,
"text": null
},
{
"code": null,
"e": 2747,
"s": 2737,
"text": "Output – "
},
{
"code": null,
"e": 2766,
"s": 2747,
"text": "surindertarika1234"
},
{
"code": null,
"e": 2780,
"s": 2766,
"text": "CSS-Questions"
},
{
"code": null,
"e": 2794,
"s": 2780,
"text": "HTML-Property"
},
{
"code": null,
"e": 2809,
"s": 2794,
"text": "HTML-Questions"
},
{
"code": null,
"e": 2819,
"s": 2809,
"text": "HTML-Tags"
},
{
"code": null,
"e": 2834,
"s": 2819,
"text": "jQuery-Methods"
},
{
"code": null,
"e": 2851,
"s": 2834,
"text": "jQuery-Questions"
},
{
"code": null,
"e": 2858,
"s": 2851,
"text": "Picked"
},
{
"code": null,
"e": 2862,
"s": 2858,
"text": "CSS"
},
{
"code": null,
"e": 2867,
"s": 2862,
"text": "HTML"
},
{
"code": null,
"e": 2874,
"s": 2867,
"text": "JQuery"
},
{
"code": null,
"e": 2891,
"s": 2874,
"text": "Web Technologies"
},
{
"code": null,
"e": 2896,
"s": 2891,
"text": "HTML"
},
{
"code": null,
"e": 2994,
"s": 2896,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3031,
"s": 2994,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 3070,
"s": 3031,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 3109,
"s": 3070,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 3173,
"s": 3109,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 3234,
"s": 3173,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 3258,
"s": 3234,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 3311,
"s": 3258,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 3371,
"s": 3311,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 3432,
"s": 3371,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Python | Pandas dataframe.mad() | 19 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.mad() function return the mean absolute deviation of the values for the requested axis. The mean absolute deviation of a dataset is the average distance between each data point and the mean. It gives us an idea about the variability in a dataset.
Syntax: DataFrame.mad(axis=None, skipna=None, level=None)
Parameters :axis : {index (0), columns (1)}skipna : Exclude NA/null values when computing the resultlevel : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Seriesnumeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.
Returns : mad : Series or DataFrame (if level specified)
Example #1: Use mad() function to find the mean absolute deviation of the values over the index axis.
# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({"A":[12, 4, 5, 44, 1], "B":[5, 2, 54, 3, 2], "C":[20, 16, 7, 3, 8], "D":[14, 3, 17, 2, 6]}) # Print the dataframedf
Let’s use the dataframe.mad() function to find the mean absolute deviation.
# find the mean absolute deviation # over the index axisdf.mad(axis = 0)
Output :
Example #2: Use mad() function to find the mean absolute deviation of values over the column axis which is having some Na values in it.
# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({"A":[12, 4, 5, None, 1], "B":[7, 2, 54, 3, None], "C":[20, 16, 11, 3, 8], "D":[14, 3, None, 2, 6]}) # To find the mean absolute deviation# skip the Na values when finding the mad valuedf.mad(axis = 1, skipna = True)
Output :
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Nov, 2018"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 506,
"s": 242,
"text": "Pandas dataframe.mad() function return the mean absolute deviation of the values for the requested axis. The mean absolute deviation of a dataset is the average distance between each data point and the mean. It gives us an idea about the variability in a dataset."
},
{
"code": null,
"e": 564,
"s": 506,
"text": "Syntax: DataFrame.mad(axis=None, skipna=None, level=None)"
},
{
"code": null,
"e": 926,
"s": 564,
"text": "Parameters :axis : {index (0), columns (1)}skipna : Exclude NA/null values when computing the resultlevel : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Seriesnumeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series."
},
{
"code": null,
"e": 983,
"s": 926,
"text": "Returns : mad : Series or DataFrame (if level specified)"
},
{
"code": null,
"e": 1085,
"s": 983,
"text": "Example #1: Use mad() function to find the mean absolute deviation of the values over the index axis."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[12, 4, 5, 44, 1], \"B\":[5, 2, 54, 3, 2], \"C\":[20, 16, 7, 3, 8], \"D\":[14, 3, 17, 2, 6]}) # Print the dataframedf",
"e": 1346,
"s": 1085,
"text": null
},
{
"code": null,
"e": 1422,
"s": 1346,
"text": "Let’s use the dataframe.mad() function to find the mean absolute deviation."
},
{
"code": "# find the mean absolute deviation # over the index axisdf.mad(axis = 0)",
"e": 1495,
"s": 1422,
"text": null
},
{
"code": null,
"e": 1505,
"s": 1495,
"text": "Output : "
},
{
"code": null,
"e": 1641,
"s": 1505,
"text": "Example #2: Use mad() function to find the mean absolute deviation of values over the column axis which is having some Na values in it."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[12, 4, 5, None, 1], \"B\":[7, 2, 54, 3, None], \"C\":[20, 16, 11, 3, 8], \"D\":[14, 3, None, 2, 6]}) # To find the mean absolute deviation# skip the Na values when finding the mad valuedf.mad(axis = 1, skipna = True)",
"e": 2002,
"s": 1641,
"text": null
},
{
"code": null,
"e": 2011,
"s": 2002,
"text": "Output :"
},
{
"code": null,
"e": 2035,
"s": 2011,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2067,
"s": 2035,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 2081,
"s": 2067,
"text": "Python-pandas"
},
{
"code": null,
"e": 2088,
"s": 2081,
"text": "Python"
},
{
"code": null,
"e": 2186,
"s": 2088,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2204,
"s": 2186,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2246,
"s": 2204,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2268,
"s": 2246,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2303,
"s": 2268,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2329,
"s": 2303,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2361,
"s": 2329,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2390,
"s": 2361,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2417,
"s": 2390,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2447,
"s": 2417,
"text": "Iterate over a list in Python"
}
] |
Maximum difference between two elements such that larger element appears after the smaller number | 21 Jun, 2022
Given an array arr[] of integers, find out the maximum difference between any two elements such that larger element appears after the smaller number.
Examples :
Input : arr = {2, 3, 10, 6, 4, 8, 1}
Output : 8
Explanation : The maximum difference is between 10 and 2.
Input : arr = {7, 9, 5, 6, 3, 2}
Output : 2
Explanation : The maximum difference is between 9 and 7.
Method 1 (Simple) Use two loops. In the outer loop, pick elements one by one and in the inner loop calculate the difference of the picked element with every other element in the array and compare the difference with the maximum difference calculated so far. Below is the implementation of the above approach :
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number#include <bits/stdc++.h>using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */int maxDiff(int arr[], int arr_size){ int max_diff = arr[1] - arr[0]; for (int i = 0; i < arr_size; i++) { for (int j = i+1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff;} /* Driver program to test above function */int main(){ int arr[] = {1, 2, 90, 10, 110}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << "Maximum difference is " << maxDiff(arr, n); return 0;}
#include<stdio.h> /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order. Returns 0 if elements are equal */int maxDiff(int arr[], int arr_size){ int max_diff = arr[1] - arr[0]; int i, j; for (i = 0; i < arr_size; i++) { for (j = i+1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff;} /* Driver program to test above function */int main(){ int arr[] = {1, 2, 90, 10, 110}; printf("Maximum difference is %d", maxDiff(arr, 5)); getchar(); return 0;}
// Java program to find Maximum difference // between two elements such that larger // element appears after the smaller numberclass MaximumDifference { /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order. Returns 0 if elements are equal */ int maxDiff(int arr[], int arr_size) { int max_diff = arr[1] - arr[0]; int i, j; for (i = 0; i < arr_size; i++) { for (j = i + 1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff; } /* Driver program to test above functions */ public static void main(String[] args) { MaximumDifference maxdif = new MaximumDifference(); int arr[] = {1, 2, 90, 10, 110}; System.out.println("Maximum difference is " + maxdif.maxDiff(arr, 5)); }} // This code has been contributed by Mayank Jaiswal
# Python 3 code to find Maximum difference# between two elements such that larger # element appears after the smaller number # The function assumes that there are at # least two elements in array. The function # returns a negative value if the array is# sorted in decreasing order. Returns 0 # if elements are equaldef maxDiff(arr, arr_size): max_diff = arr[1] - arr[0] for i in range( arr_size ): for j in range( i+1, arr_size ): if(arr[j] - arr[i] > max_diff): max_diff = arr[j] - arr[i] return max_diff # Driver program to test above function arr = [1, 2, 90, 10, 110]size = len(arr)print ("Maximum difference is", maxDiff(arr, size)) # This code is contributed by Swetank Modi
// C# code to find Maximum differenceusing System; class GFG { // The function assumes that there // are at least two elements in array. // The function returns a negative // value if the array is sorted in // decreasing order. Returns 0 if // elements are equal static int maxDiff(int[] arr, int arr_size) { int max_diff = arr[1] - arr[0]; int i, j; for (i = 0; i < arr_size; i++) { for (j = i + 1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff; } // Driver code public static void Main() { int[] arr = { 1, 2, 90, 10, 110 }; Console.Write("Maximum difference is " + maxDiff(arr, 5)); }} // This code is contributed by Sam007
<?php// PHP program to find Maximum difference // between two elements such that larger // element appears after the smaller number /* The function assumes that there are at least two elements in array. The function returns a negative value if thearray is sorted in decreasing order and returns 0 if elements are equal */function maxDiff($arr, $arr_size){ $max_diff = $arr[1] - $arr[0];for ($i = 0; $i < $arr_size; $i++){ for ($j = $i+1; $j < $arr_size; $j++) { if ($arr[$j] - $arr[$i] > $max_diff) $max_diff = $arr[$j] - $arr[$i]; } } return $max_diff;} // Driver Code$arr = array(1, 2, 90, 10, 110);$n = sizeof($arr); // Function callingecho "Maximum difference is " . maxDiff($arr, $n); // This code is contributed // by Akanksha Rai(Abby_akku)
<script>// javascript program to find Maximum difference // between two elements such that larger // element appears after the smaller number /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */function maxDiff( arr, arr_size){ let max_diff = arr[1] - arr[0]; for (let i = 0; i < arr_size; i++) { for (let j = i+1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff;} // Driver program to test above function let arr = [1, 2, 90, 10, 110]; let n = arr.length; // Function calling document.write("Maximum difference is " + maxDiff(arr, n)); // This code is contributed by jana_sayantan.</script>
Output :
Maximum difference is 109
Time Complexity : O(n^2) Auxiliary Space : O(1)
Method 2 (Tricky and Efficient) In this method, instead of taking difference of the picked element with every other element, we take the difference with the minimum element found so far. So we need to keep track of 2 things: 1) Maximum difference found so far (max_diff). 2) Minimum number visited so far (min_element).
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number#include <bits/stdc++.h>using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */int maxDiff(int arr[], int arr_size){ // Maximum difference found so far int max_diff = arr[1] - arr[0]; // Minimum number visited so far int min_element = arr[0]; for(int i = 1; i < arr_size; i++) { if (arr[i] - min_element > max_diff) max_diff = arr[i] - min_element; if (arr[i] < min_element) min_element = arr[i]; } return max_diff;} /* Driver program to test above function */int main(){ int arr[] = {1, 2, 90, 10, 110}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << "Maximum difference is " << maxDiff(arr, n); return 0;}
#include<stdio.h> /* The function assumes that there are at least twoelements in array.The function returns a negative value if the array issorted in decreasing order.Returns 0 if elements are equal */int maxDiff(int arr[], int arr_size){int max_diff = arr[1] - arr[0];int min_element = arr[0];int i;for(i = 1; i < arr_size; i++){ if (arr[i] - min_element > max_diff) max_diff = arr[i] - min_element; if (arr[i] < min_element) min_element = arr[i]; }return max_diff;} /* Driver program to test above function */int main(){int arr[] = {1, 2, 6, 80, 100};int size = sizeof(arr)/sizeof(arr[0]);printf("Maximum difference is %d", maxDiff(arr, size));getchar();return 0;}
// Java program to find Maximum difference // between two elements such that larger // element appears after the smaller numberclass MaximumDifference { /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order. Returns 0 if elements are equal */ int maxDiff(int arr[], int arr_size) { int max_diff = arr[1] - arr[0]; int min_element = arr[0]; int i; for (i = 1; i < arr_size; i++) { if (arr[i] - min_element > max_diff) max_diff = arr[i] - min_element; if (arr[i] < min_element) min_element = arr[i]; } return max_diff; } /* Driver program to test above functions */ public static void main(String[] args) { MaximumDifference maxdif = new MaximumDifference(); int arr[] = {1, 2, 90, 10, 110}; int size = arr.length; System.out.println("MaximumDifference is " + maxdif.maxDiff(arr, size)); }} // This code has been contributed by Mayank Jaiswal
# Python 3 code to find Maximum difference# between two elements such that larger # element appears after the smaller number # The function assumes that there are # at least two elements in array.# The function returns a negative # value if the array is sorted in # decreasing order. Returns 0 if # elements are equaldef maxDiff(arr, arr_size): max_diff = arr[1] - arr[0] min_element = arr[0] for i in range( 1, arr_size ): if (arr[i] - min_element > max_diff): max_diff = arr[i] - min_element if (arr[i] < min_element): min_element = arr[i] return max_diff # Driver program to test above function arr = [1, 2, 6, 80, 100]size = len(arr)print ("Maximum difference is", maxDiff(arr, size)) # This code is contributed by Swetank Modi
// C# code to find Maximum differenceusing System; class GFG { // The function assumes that there // are at least two elements in array. // The function returns a negative // value if the array is sorted in // decreasing order.Returns 0 if // elements are equal static int maxDiff(int[] arr, int arr_size) { int max_diff = arr[1] - arr[0]; int min_element = arr[0]; int i; for (i = 1; i < arr_size; i++) { if (arr[i] - min_element > max_diff) max_diff = arr[i] - min_element; if (arr[i] < min_element) min_element = arr[i]; } return max_diff; } // Driver code public static void Main() { int[] arr = { 1, 2, 90, 10, 110 }; int size = arr.Length; Console.Write("MaximumDifference is " + maxDiff(arr, size)); }} // This code is contributed by Sam007
<?php// PHP program to find Maximum // difference between two elements // such that larger element appears// after the smaller number // The function assumes that there // are at least two elements in array. // The function returns a negative // value if the array is sorted in // decreasing order and returns 0 // if elements are equal function maxDiff($arr, $arr_size){ // Maximum difference found so far $max_diff = $arr[1] - $arr[0]; // Minimum number visited so far $min_element = $arr[0]; for($i = 1; $i < $arr_size; $i++) { if ($arr[$i] - $min_element > $max_diff) $max_diff = $arr[$i] - $min_element; if ($arr[$i] < $min_element) $min_element = $arr[$i]; } return $max_diff;} // Driver Code$arr = array(1, 2, 90, 10, 110);$n = count($arr); // Function callingecho "Maximum difference is " . maxDiff($arr, $n); // This code is contributed by Sam007?>
<script> // Javascript code to find Maximum difference // between two elements such that larger // element appears after the smaller number // The function assumes that there // are at least two elements in array. // The function returns a negative // value if the array is sorted in // decreasing order.Returns 0 if // elements are equal function maxDiff(arr, arr_size) { let max_diff = arr[1] - arr[0]; let min_element = arr[0]; let i; for (i = 1; i < arr_size; i++) { if (arr[i] - min_element > max_diff) max_diff = arr[i] - min_element; if (arr[i] < min_element) min_element = arr[i]; } return max_diff; } let arr = [ 1, 2, 90, 10, 110 ]; let size = arr.length; document.write("Maximum difference is " + maxDiff(arr, size)); </script>
Output:
Maximum difference is 109
Time Complexity : O(n) Auxiliary Space : O(1)
Like min element, we can also keep track of max element from right side. Thanks to Katamaran for suggesting this approach. Below is the implementation :
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number#include <bits/stdc++.h>using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */int maxDiff(int arr[], int n){ // Initialize Result int maxDiff = -1; // Initialize max element from right side int maxRight = arr[n-1]; for (int i = n-2; i >= 0; i--) { if (arr[i] > maxRight) maxRight = arr[i]; else { int diff = maxRight - arr[i]; if (diff > maxDiff) { maxDiff = diff; } } } return maxDiff;} /* Driver program to test above function */int main(){ int arr[] = {1, 2, 90, 10, 110}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << "Maximum difference is " << maxDiff(arr, n); return 0;}
// Java program to find Maximum difference // between two elements such that larger // element appears after the smaller number import java.io.*; class GFG {/* The function assumes that there are at least two elements in array. The function returns a negative value if thearray is sorted in decreasing order and returns 0 if elements are equal */static int maxDiff(int arr[], int n){ // Initialize Result int maxDiff = -1; // Initialize max element from right side int maxRight = arr[n-1]; for (int i = n-2; i >= 0; i--) { if (arr[i] > maxRight) maxRight = arr[i]; else { int diff = maxRight - arr[i]; if (diff > maxDiff) { maxDiff = diff; } } } return maxDiff;} /* Driver program to test above function */ public static void main (String[] args) { int arr[] = {1, 2, 90, 10, 110}; int n = arr.length; // Function calling System.out.println ("Maximum difference is " + maxDiff(arr, n)); }//This code is contributed by Tushil.. }
# Python3 program to find Maximum difference # between two elements such that larger # element appears after the smaller number # The function assumes that there are # at least two elements in array. The # function returns a negative value if the# array is sorted in decreasing order and # returns 0 if elements are equaldef maxDiff(arr, n): # Initialize Result maxDiff = -1 # Initialize max element from # right side maxRight = arr[-1] for i in reversed(arr[:-1]): if (i > maxRight): maxRight = i else: diff = maxRight - i if (diff > maxDiff): maxDiff = diff return maxDiff # Driver Codeif __name__ == '__main__': arr = [1, 2, 90, 10, 110] n = len(arr) # Function calling print("Maximum difference is", maxDiff(arr, n)) # This code is contributed by 29AjayKumar
// C# program to find Maximum difference // between two elements such that larger // element appears after the smaller numberusing System; class GFG{/* The function assumes that there are at least two elements in array. The function returns a negative value if thearray is sorted in decreasing order and returns 0 if elements are equal */static int maxDiff(int[] arr, int n){ // Initialize Result int maxDiff = -1; // Initialize max element from right side int maxRight = arr[n-1]; for (int i = n-2; i >= 0; i--) { if (arr[i] > maxRight) maxRight = arr[i]; else { int diff = maxRight - arr[i]; if (diff > maxDiff) { maxDiff = diff; } } } return maxDiff;} // Driver Codepublic static void Main () { int[] arr = {1, 2, 90, 10, 110}; int n = arr.Length; // Function calling Console.WriteLine("Maximum difference is " + maxDiff(arr, n));}} // This code is contributed // by Akanksha Rai
<?php// PHP program to find Maximum difference // between two elements such that larger // element appears after the smaller number /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */function maxDiff($arr, $n) { // Initialize Result $maxDiff = -1; // Initialize max element from // right side $maxRight = $arr[$n - 1]; for ($i = $n - 2; $i >= 0; $i--) { if ($arr[$i] > $maxRight) $maxRight = $arr[$i]; else { $diff = $maxRight - $arr[$i]; if ($diff > $maxDiff) { $maxDiff = $diff; } } } return $maxDiff; } // Driver Code$arr = array(1, 2, 90, 10, 110); $n = sizeof($arr); // Function calling echo "Maximum difference is ", maxDiff($arr, $n); // This code is contributed by ajit?>
<script> // Javascript program to find Maximum difference // between two elements such that larger // element appears after the smaller number /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */ function maxDiff(arr, n) { // Initialize Result let maxDiff = -1; // Initialize max element from right side let maxRight = arr[n-1]; for (let i = n-2; i >= 0; i--) { if (arr[i] > maxRight) maxRight = arr[i]; else { let diff = maxRight - arr[i]; if (diff > maxDiff) { maxDiff = diff; } } } return maxDiff; } let arr = [1, 2, 90, 10, 110]; let n = arr.length; // Function calling document.write("Maximum difference is " + maxDiff(arr, n)); </script>
Output:
Maximum difference is 109
Time Complexity : O(n) Auxiliary Space : O(1)
Method 3 (Another Tricky Solution) First find the difference between the adjacent elements of the array and store all differences in an auxiliary array diff[] of size n-1. Now this problems turns into finding the maximum sum subarray of this difference array.Thanks to Shubham Mittal for suggesting this solution. Below is the implementation :
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number#include <bits/stdc++.h>using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */int maxDiff(int arr[], int n){ // Create a diff array of size n-1. // The array will hold the difference // of adjacent elements int diff[n-1]; for (int i=0; i < n-1; i++) diff[i] = arr[i+1] - arr[i]; // Now find the maximum sum // subarray in diff array int max_diff = diff[0]; for (int i=1; i<n-1; i++) { if (diff[i-1] > 0) diff[i] += diff[i-1]; if (max_diff < diff[i]) max_diff = diff[i]; } return max_diff;} /* Driver program to test above function */int main(){ int arr[] = {80, 2, 6, 3, 100}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << "Maximum difference is " << maxDiff(arr, n); return 0;}
#include<stdio.h> int maxDiff(int arr[], int n){ // Create a diff array of size n-1. The array will hold // the difference of adjacent elements int diff[n-1]; for (int i=0; i < n-1; i++) diff[i] = arr[i+1] - arr[i]; // Now find the maximum sum subarray in diff array int max_diff = diff[0]; for (int i=1; i<n-1; i++) { if (diff[i-1] > 0) diff[i] += diff[i-1]; if (max_diff < diff[i]) max_diff = diff[i]; } return max_diff;} /* Driver program to test above function */int main(){ int arr[] = {80, 2, 6, 3, 100}; int size = sizeof(arr)/sizeof(arr[0]); printf("Maximum difference is %d", maxDiff(arr, size)); return 0;}
// Java program to find Maximum difference // between two elements such that larger // element appears after the smaller numberclass MaximumDifference { int maxDiff(int arr[], int n) { // Create a diff array of size n-1. The array will hold // the difference of adjacent elements int diff[] = new int[n - 1]; for (int i = 0; i < n - 1; i++) diff[i] = arr[i + 1] - arr[i]; // Now find the maximum sum subarray in diff array int max_diff = diff[0]; for (int i = 1; i < n - 1; i++) { if (diff[i - 1] > 0) diff[i] += diff[i - 1]; if (max_diff < diff[i]) max_diff = diff[i]; } return max_diff; } // Driver program to test above functions public static void main(String[] args) { MaximumDifference mxdif = new MaximumDifference(); int arr[] = {80, 2, 6, 3, 100}; int size = arr.length; System.out.println(mxdif.maxDiff(arr, size)); }}// This code has been contributed by Mayank Jaiswal
# Python 3 code to find Maximum difference# between two elements such that larger # element appears after the smaller number def maxDiff(arr, n): diff = [0] * (n - 1) for i in range (0, n-1): diff[i] = arr[i+1] - arr[i] # Now find the maximum sum # subarray in diff array max_diff = diff[0] for i in range(1, n-1): if (diff[i-1] > 0): diff[i] += diff[i-1] if (max_diff < diff[i]): max_diff = diff[i] return max_diff # Driver program to test above function arr = [80, 2, 6, 3, 100]size = len(arr)print ("Maximum difference is", maxDiff(arr, size)) # This code is contributed by Swetank Modi
// C# code to find Maximum differenceusing System; class GFG { static int maxDiff(int[] arr, int n) { // Create a diff array of size n-1. // The array will hold the // difference of adjacent elements int[] diff = new int[n - 1]; for (int i = 0; i < n - 1; i++) diff[i] = arr[i + 1] - arr[i]; // Now find the maximum sum // subarray in diff array int max_diff = diff[0]; for (int i = 1; i < n - 1; i++) { if (diff[i - 1] > 0) diff[i] += diff[i - 1]; if (max_diff < diff[i]) max_diff = diff[i]; } return max_diff; } // Driver code public static void Main() { int[] arr = { 80, 2, 6, 3, 100 }; int size = arr.Length; Console.Write(maxDiff(arr, size)); }} // This code is contributed by Sam007
<?php// PHP program to find Maximum difference // between two elements such that larger // element appears after the smaller number /* The function assumes that there are at least two elements in array. The function returns a negative value if thearray is sorted in decreasing order and returns 0 if elements are equal */function maxDiff($arr, $n){ // Create a diff array of size n-1. // The array will hold the difference // of adjacent elements $diff[$n-1] = array(); for ($i=0; $i < $n-1; $i++) $diff[$i] = $arr[$i+1] - $arr[$i]; // Now find the maximum sum // subarray in diff array $max_diff = $diff[0]; for ($i=1; $i<$n-1; $i++) { if ($diff[$i-1] > 0) $diff[$i] += $diff[$i-1]; if ($max_diff < $diff[$i]) $max_diff = $diff[$i]; } return $max_diff;} // Driver Code$arr = array(80, 2, 6, 3, 100);$n = sizeof($arr); // Function callingecho "Maximum difference is " . maxDiff($arr, $n); // This code is contributed // by Akanksha Rai
<script> // JavaScript program to find Maximum difference// between two elements such that larger// element appears after the smaller number /* The function assumes that there areat least two elements in array. Thefunction returns a negative value if thearray is sorted in decreasing order andreturns 0 if elements are equal */function maxDiff(arr, n){ // Create a diff array of size n-1. // The array will hold the difference // of adjacent elements let diff = new Array(n - 1); for(let i = 0; i < n - 1; i++) diff[i] = arr[i + 1] - arr[i]; // Now find the maximum sum // subarray in diff array let max_diff = diff[0]; for(let i = 1; i < n - 1; i++) { if (diff[i - 1] > 0) diff[i] += diff[i - 1]; if (max_diff < diff[i]) max_diff = diff[i]; } return max_diff;} // Driver codelet arr = [ 80, 2, 6, 3, 100 ];let n = arr.length; // Function callingdocument.write("Maximum difference is " + maxDiff(arr, n)); // This code is contributed by Mayank Tyagi </script>
Output:
Maximum difference is 98
Time Complexity : O(n) Auxiliary Space : O(n)
We can modify the above method to work in O(1) extra space. Instead of creating an auxiliary array, we can calculate diff and max sum in same loop. Following is the space optimized version.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number#include <bits/stdc++.h>using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */int maxDiff (int arr[], int n){ // Initialize diff, current sum and max sum int diff = arr[1]-arr[0]; int curr_sum = diff; int max_sum = curr_sum; for(int i=1; i<n-1; i++) { // Calculate current diff diff = arr[i+1]-arr[i]; // Calculate current sum if (curr_sum > 0) curr_sum += diff; else curr_sum = diff; // Update max sum, if needed if (curr_sum > max_sum) max_sum = curr_sum; } return max_sum;} /* Driver program to test above function */int main(){ int arr[] = {80, 2, 6, 3, 100}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << "Maximum difference is " << maxDiff(arr, n); return 0;}
// Java program to find Maximum // difference between two elements // such that larger element appears // after the smaller number class GFG{ /* The function assumes that thereare at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 ifelements are equal */static int maxDiff (int arr[], int n) { // Initialize diff, current // sum and max sum int diff = arr[1] - arr[0]; int curr_sum = diff; int max_sum = curr_sum; for(int i = 1; i < n - 1; i++) { // Calculate current diff diff = arr[i + 1] - arr[i]; // Calculate current sum if (curr_sum > 0) curr_sum += diff; else curr_sum = diff; // Update max sum, if needed if (curr_sum > max_sum) max_sum = curr_sum; } return max_sum; } // Driver Codepublic static void main(String[] args) { int arr[] = {80, 2, 6, 3, 100}; int n = arr.length; // Function calling System.out.print("Maximum difference is " + maxDiff(arr, n)); }} // This code is contributed by Smitha
# Python3 program to find Maximum difference # between two elements such that larger # element appears after the smaller number # The function assumes that there are # at least two elements in array. The # function returns a negative value if # the array is sorted in decreasing # order and returns 0 if elements are equaldef maxDiff (arr, n): # Initialize diff, current # sum and max sum diff = arr[1] - arr[0] curr_sum = diff max_sum = curr_sum for i in range(1, n - 1): # Calculate current diff diff = arr[i + 1] - arr[i] # Calculate current sum if (curr_sum > 0): curr_sum += diff else: curr_sum = diff # Update max sum, if needed if (curr_sum > max_sum): max_sum = curr_sum return max_sum # Driver Codeif __name__ == '__main__': arr = [80, 2, 6, 3, 100] n = len(arr) # Function calling print("Maximum difference is", maxDiff(arr, n)) # This code is contributed # by 29AjayKumar
// C# program to find Maximum // difference between two elements // such that larger element appears // after the smaller number using System;class GFG{ /* The function assumes that thereare at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 ifelements are equal */static int maxDiff (int[] arr, int n) { // Initialize diff, current // sum and max sum int diff = arr[1] - arr[0]; int curr_sum = diff; int max_sum = curr_sum; for(int i = 1; i < n - 1; i++) { // Calculate current diff diff = arr[i + 1] - arr[i]; // Calculate current sum if (curr_sum > 0) curr_sum += diff; else curr_sum = diff; // Update max sum, if needed if (curr_sum > max_sum) max_sum = curr_sum; } return max_sum; } // Driver Codepublic static void Main() { int[] arr = {80, 2, 6, 3, 100}; int n = arr.Length; // Function calling Console.WriteLine("Maximum difference is " + maxDiff(arr, n)); }} // This code is contributed // by Akanksha Rai(Abby_akku)
<?php// PHP program to find Maximum difference // between two elements such that larger // element appears after the smaller number /* The function assumes that there are at least two elements in array. The function returns a negative value if thearray is sorted in decreasing order and returns 0 if elements are equal */function maxDiff ($arr, $n){ // Initialize diff, current sum // and max sum $diff = $arr[1] - $arr[0]; $curr_sum = $diff; $max_sum = $curr_sum; for($i = 1; $i < $n - 1; $i++) { // Calculate current diff $diff = $arr[$i + 1] - $arr[$i]; // Calculate current sum if ($curr_sum > 0) $curr_sum += $diff; else $curr_sum = $diff; // Update max sum, if needed if ($curr_sum > $max_sum) $max_sum = $curr_sum; } return $max_sum;} // Driver Code$arr = array(80, 2, 6, 3, 100);$n = sizeof($arr); // Function callingecho "Maximum difference is ", maxDiff($arr, $n); // This code is contributed // by Sach_code?>
<script> // Javascript program to find Maximum// difference between two elements// such that larger element appears// after the smaller number /* The function assumes that thereare at least two elements in array.The function returns a negativevalue if the array is sorted indecreasing order and returns 0 ifelements are equal */function maxDiff (arr, n){ // Initialize diff, current // sum and max sum let diff = arr[1] - arr[0]; let curr_sum = diff; let max_sum = curr_sum; for(let i = 1; i < n - 1; i++) { // Calculate current diff diff = arr[i + 1] - arr[i]; // Calculate current sum if (curr_sum > 0) curr_sum += diff; else curr_sum = diff; // Update max sum, if needed if (curr_sum > max_sum) max_sum = curr_sum; } return max_sum;} // Driver Codelet arr = [ 80, 2, 6, 3, 100 ];let n = arr.length; // Function calling document.write("Maximum difference is " + maxDiff(arr, n)); // This code is contributed by rag2127 </script>
Output:
Maximum difference is 98
Time Complexity : O(n) Auxiliary Space : O(1)
Maximum difference between two elements (larger element appears after smaller) | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersMaximum difference between two elements (larger element appears after smaller) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 11:18•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=SO0bwMziLlU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Below is a variation of this problem: Maximum difference of sum of elements in two rows in a matrixPlease write comments if you find any bug in above codes/algorithms, or find other ways to solve the same problem
Sam007
Smitha Dinesh Semwal
Akanksha_Rai
jit_t
Sach_Code
29AjayKumar
jana_sayantan
decode2207
suresh07
mayanktyagi1709
rag2127
saurabh1990aror
devnawfalahmed
202051178
_shinchancode
Amazon
Hike
MakeMyTrip
Ola Cabs
SAP Labs
Arrays
Amazon
Hike
MakeMyTrip
Ola Cabs
SAP Labs
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in Java
Introduction to Arrays
K'th Smallest/Largest Element in Unsorted Array | Set 1
Subset Sum Problem | DP-25
Introduction to Data Structures
Python | Using 2D arrays/lists the right way
Search an element in a sorted and rotated array
Find Second largest element in an array
Find the Missing Number
Count Inversions in an array | Set 1 (Using Merge Sort) | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 205,
"s": 54,
"text": "Given an array arr[] of integers, find out the maximum difference between any two elements such that larger element appears after the smaller number. "
},
{
"code": null,
"e": 217,
"s": 205,
"text": "Examples : "
},
{
"code": null,
"e": 425,
"s": 217,
"text": "Input : arr = {2, 3, 10, 6, 4, 8, 1}\nOutput : 8\nExplanation : The maximum difference is between 10 and 2.\n\nInput : arr = {7, 9, 5, 6, 3, 2}\nOutput : 2\nExplanation : The maximum difference is between 9 and 7."
},
{
"code": null,
"e": 736,
"s": 425,
"text": "Method 1 (Simple) Use two loops. In the outer loop, pick elements one by one and in the inner loop calculate the difference of the picked element with every other element in the array and compare the difference with the maximum difference calculated so far. Below is the implementation of the above approach : "
},
{
"code": null,
"e": 740,
"s": 736,
"text": "C++"
},
{
"code": null,
"e": 742,
"s": 740,
"text": "C"
},
{
"code": null,
"e": 747,
"s": 742,
"text": "Java"
},
{
"code": null,
"e": 755,
"s": 747,
"text": "Python3"
},
{
"code": null,
"e": 758,
"s": 755,
"text": "C#"
},
{
"code": null,
"e": 762,
"s": 758,
"text": "PHP"
},
{
"code": null,
"e": 773,
"s": 762,
"text": "Javascript"
},
{
"code": "// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number#include <bits/stdc++.h>using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */int maxDiff(int arr[], int arr_size){ int max_diff = arr[1] - arr[0]; for (int i = 0; i < arr_size; i++) { for (int j = i+1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff;} /* Driver program to test above function */int main(){ int arr[] = {1, 2, 90, 10, 110}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << \"Maximum difference is \" << maxDiff(arr, n); return 0;}",
"e": 1645,
"s": 773,
"text": null
},
{
"code": "#include<stdio.h> /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order. Returns 0 if elements are equal */int maxDiff(int arr[], int arr_size){ int max_diff = arr[1] - arr[0]; int i, j; for (i = 0; i < arr_size; i++) { for (j = i+1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff;} /* Driver program to test above function */int main(){ int arr[] = {1, 2, 90, 10, 110}; printf(\"Maximum difference is %d\", maxDiff(arr, 5)); getchar(); return 0;}",
"e": 2321,
"s": 1645,
"text": null
},
{
"code": "// Java program to find Maximum difference // between two elements such that larger // element appears after the smaller numberclass MaximumDifference { /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order. Returns 0 if elements are equal */ int maxDiff(int arr[], int arr_size) { int max_diff = arr[1] - arr[0]; int i, j; for (i = 0; i < arr_size; i++) { for (j = i + 1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff; } /* Driver program to test above functions */ public static void main(String[] args) { MaximumDifference maxdif = new MaximumDifference(); int arr[] = {1, 2, 90, 10, 110}; System.out.println(\"Maximum difference is \" + maxdif.maxDiff(arr, 5)); }} // This code has been contributed by Mayank Jaiswal",
"e": 3411,
"s": 2321,
"text": null
},
{
"code": "# Python 3 code to find Maximum difference# between two elements such that larger # element appears after the smaller number # The function assumes that there are at # least two elements in array. The function # returns a negative value if the array is# sorted in decreasing order. Returns 0 # if elements are equaldef maxDiff(arr, arr_size): max_diff = arr[1] - arr[0] for i in range( arr_size ): for j in range( i+1, arr_size ): if(arr[j] - arr[i] > max_diff): max_diff = arr[j] - arr[i] return max_diff # Driver program to test above function arr = [1, 2, 90, 10, 110]size = len(arr)print (\"Maximum difference is\", maxDiff(arr, size)) # This code is contributed by Swetank Modi",
"e": 4154,
"s": 3411,
"text": null
},
{
"code": "// C# code to find Maximum differenceusing System; class GFG { // The function assumes that there // are at least two elements in array. // The function returns a negative // value if the array is sorted in // decreasing order. Returns 0 if // elements are equal static int maxDiff(int[] arr, int arr_size) { int max_diff = arr[1] - arr[0]; int i, j; for (i = 0; i < arr_size; i++) { for (j = i + 1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff; } // Driver code public static void Main() { int[] arr = { 1, 2, 90, 10, 110 }; Console.Write(\"Maximum difference is \" + maxDiff(arr, 5)); }} // This code is contributed by Sam007",
"e": 5024,
"s": 4154,
"text": null
},
{
"code": "<?php// PHP program to find Maximum difference // between two elements such that larger // element appears after the smaller number /* The function assumes that there are at least two elements in array. The function returns a negative value if thearray is sorted in decreasing order and returns 0 if elements are equal */function maxDiff($arr, $arr_size){ $max_diff = $arr[1] - $arr[0];for ($i = 0; $i < $arr_size; $i++){ for ($j = $i+1; $j < $arr_size; $j++) { if ($arr[$j] - $arr[$i] > $max_diff) $max_diff = $arr[$j] - $arr[$i]; } } return $max_diff;} // Driver Code$arr = array(1, 2, 90, 10, 110);$n = sizeof($arr); // Function callingecho \"Maximum difference is \" . maxDiff($arr, $n); // This code is contributed // by Akanksha Rai(Abby_akku)",
"e": 5815,
"s": 5024,
"text": null
},
{
"code": "<script>// javascript program to find Maximum difference // between two elements such that larger // element appears after the smaller number /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */function maxDiff( arr, arr_size){ let max_diff = arr[1] - arr[0]; for (let i = 0; i < arr_size; i++) { for (let j = i+1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff;} // Driver program to test above function let arr = [1, 2, 90, 10, 110]; let n = arr.length; // Function calling document.write(\"Maximum difference is \" + maxDiff(arr, n)); // This code is contributed by jana_sayantan.</script>",
"e": 6694,
"s": 5815,
"text": null
},
{
"code": null,
"e": 6703,
"s": 6694,
"text": "Output :"
},
{
"code": null,
"e": 6729,
"s": 6703,
"text": "Maximum difference is 109"
},
{
"code": null,
"e": 6777,
"s": 6729,
"text": "Time Complexity : O(n^2) Auxiliary Space : O(1)"
},
{
"code": null,
"e": 7097,
"s": 6777,
"text": "Method 2 (Tricky and Efficient) In this method, instead of taking difference of the picked element with every other element, we take the difference with the minimum element found so far. So we need to keep track of 2 things: 1) Maximum difference found so far (max_diff). 2) Minimum number visited so far (min_element)."
},
{
"code": null,
"e": 7101,
"s": 7097,
"text": "C++"
},
{
"code": null,
"e": 7103,
"s": 7101,
"text": "C"
},
{
"code": null,
"e": 7108,
"s": 7103,
"text": "Java"
},
{
"code": null,
"e": 7116,
"s": 7108,
"text": "Python3"
},
{
"code": null,
"e": 7119,
"s": 7116,
"text": "C#"
},
{
"code": null,
"e": 7123,
"s": 7119,
"text": "PHP"
},
{
"code": null,
"e": 7134,
"s": 7123,
"text": "Javascript"
},
{
"code": "// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number#include <bits/stdc++.h>using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */int maxDiff(int arr[], int arr_size){ // Maximum difference found so far int max_diff = arr[1] - arr[0]; // Minimum number visited so far int min_element = arr[0]; for(int i = 1; i < arr_size; i++) { if (arr[i] - min_element > max_diff) max_diff = arr[i] - min_element; if (arr[i] < min_element) min_element = arr[i]; } return max_diff;} /* Driver program to test above function */int main(){ int arr[] = {1, 2, 90, 10, 110}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << \"Maximum difference is \" << maxDiff(arr, n); return 0;}",
"e": 8204,
"s": 7134,
"text": null
},
{
"code": "#include<stdio.h> /* The function assumes that there are at least twoelements in array.The function returns a negative value if the array issorted in decreasing order.Returns 0 if elements are equal */int maxDiff(int arr[], int arr_size){int max_diff = arr[1] - arr[0];int min_element = arr[0];int i;for(i = 1; i < arr_size; i++){ if (arr[i] - min_element > max_diff) max_diff = arr[i] - min_element; if (arr[i] < min_element) min_element = arr[i]; }return max_diff;} /* Driver program to test above function */int main(){int arr[] = {1, 2, 6, 80, 100};int size = sizeof(arr)/sizeof(arr[0]);printf(\"Maximum difference is %d\", maxDiff(arr, size));getchar();return 0;}",
"e": 8944,
"s": 8204,
"text": null
},
{
"code": "// Java program to find Maximum difference // between two elements such that larger // element appears after the smaller numberclass MaximumDifference { /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order. Returns 0 if elements are equal */ int maxDiff(int arr[], int arr_size) { int max_diff = arr[1] - arr[0]; int min_element = arr[0]; int i; for (i = 1; i < arr_size; i++) { if (arr[i] - min_element > max_diff) max_diff = arr[i] - min_element; if (arr[i] < min_element) min_element = arr[i]; } return max_diff; } /* Driver program to test above functions */ public static void main(String[] args) { MaximumDifference maxdif = new MaximumDifference(); int arr[] = {1, 2, 90, 10, 110}; int size = arr.length; System.out.println(\"MaximumDifference is \" + maxdif.maxDiff(arr, size)); }} // This code has been contributed by Mayank Jaiswal",
"e": 10099,
"s": 8944,
"text": null
},
{
"code": "# Python 3 code to find Maximum difference# between two elements such that larger # element appears after the smaller number # The function assumes that there are # at least two elements in array.# The function returns a negative # value if the array is sorted in # decreasing order. Returns 0 if # elements are equaldef maxDiff(arr, arr_size): max_diff = arr[1] - arr[0] min_element = arr[0] for i in range( 1, arr_size ): if (arr[i] - min_element > max_diff): max_diff = arr[i] - min_element if (arr[i] < min_element): min_element = arr[i] return max_diff # Driver program to test above function arr = [1, 2, 6, 80, 100]size = len(arr)print (\"Maximum difference is\", maxDiff(arr, size)) # This code is contributed by Swetank Modi",
"e": 10906,
"s": 10099,
"text": null
},
{
"code": "// C# code to find Maximum differenceusing System; class GFG { // The function assumes that there // are at least two elements in array. // The function returns a negative // value if the array is sorted in // decreasing order.Returns 0 if // elements are equal static int maxDiff(int[] arr, int arr_size) { int max_diff = arr[1] - arr[0]; int min_element = arr[0]; int i; for (i = 1; i < arr_size; i++) { if (arr[i] - min_element > max_diff) max_diff = arr[i] - min_element; if (arr[i] < min_element) min_element = arr[i]; } return max_diff; } // Driver code public static void Main() { int[] arr = { 1, 2, 90, 10, 110 }; int size = arr.Length; Console.Write(\"MaximumDifference is \" + maxDiff(arr, size)); }} // This code is contributed by Sam007",
"e": 11852,
"s": 10906,
"text": null
},
{
"code": "<?php// PHP program to find Maximum // difference between two elements // such that larger element appears// after the smaller number // The function assumes that there // are at least two elements in array. // The function returns a negative // value if the array is sorted in // decreasing order and returns 0 // if elements are equal function maxDiff($arr, $arr_size){ // Maximum difference found so far $max_diff = $arr[1] - $arr[0]; // Minimum number visited so far $min_element = $arr[0]; for($i = 1; $i < $arr_size; $i++) { if ($arr[$i] - $min_element > $max_diff) $max_diff = $arr[$i] - $min_element; if ($arr[$i] < $min_element) $min_element = $arr[$i]; } return $max_diff;} // Driver Code$arr = array(1, 2, 90, 10, 110);$n = count($arr); // Function callingecho \"Maximum difference is \" . maxDiff($arr, $n); // This code is contributed by Sam007?>",
"e": 12841,
"s": 11852,
"text": null
},
{
"code": "<script> // Javascript code to find Maximum difference // between two elements such that larger // element appears after the smaller number // The function assumes that there // are at least two elements in array. // The function returns a negative // value if the array is sorted in // decreasing order.Returns 0 if // elements are equal function maxDiff(arr, arr_size) { let max_diff = arr[1] - arr[0]; let min_element = arr[0]; let i; for (i = 1; i < arr_size; i++) { if (arr[i] - min_element > max_diff) max_diff = arr[i] - min_element; if (arr[i] < min_element) min_element = arr[i]; } return max_diff; } let arr = [ 1, 2, 90, 10, 110 ]; let size = arr.length; document.write(\"Maximum difference is \" + maxDiff(arr, size)); </script>",
"e": 13767,
"s": 12841,
"text": null
},
{
"code": null,
"e": 13775,
"s": 13767,
"text": "Output:"
},
{
"code": null,
"e": 13801,
"s": 13775,
"text": "Maximum difference is 109"
},
{
"code": null,
"e": 13847,
"s": 13801,
"text": "Time Complexity : O(n) Auxiliary Space : O(1)"
},
{
"code": null,
"e": 14001,
"s": 13847,
"text": "Like min element, we can also keep track of max element from right side. Thanks to Katamaran for suggesting this approach. Below is the implementation : "
},
{
"code": null,
"e": 14005,
"s": 14001,
"text": "C++"
},
{
"code": null,
"e": 14010,
"s": 14005,
"text": "Java"
},
{
"code": null,
"e": 14018,
"s": 14010,
"text": "Python3"
},
{
"code": null,
"e": 14021,
"s": 14018,
"text": "C#"
},
{
"code": null,
"e": 14025,
"s": 14021,
"text": "PHP"
},
{
"code": null,
"e": 14036,
"s": 14025,
"text": "Javascript"
},
{
"code": "// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number#include <bits/stdc++.h>using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */int maxDiff(int arr[], int n){ // Initialize Result int maxDiff = -1; // Initialize max element from right side int maxRight = arr[n-1]; for (int i = n-2; i >= 0; i--) { if (arr[i] > maxRight) maxRight = arr[i]; else { int diff = maxRight - arr[i]; if (diff > maxDiff) { maxDiff = diff; } } } return maxDiff;} /* Driver program to test above function */int main(){ int arr[] = {1, 2, 90, 10, 110}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << \"Maximum difference is \" << maxDiff(arr, n); return 0;}",
"e": 15074,
"s": 14036,
"text": null
},
{
"code": "// Java program to find Maximum difference // between two elements such that larger // element appears after the smaller number import java.io.*; class GFG {/* The function assumes that there are at least two elements in array. The function returns a negative value if thearray is sorted in decreasing order and returns 0 if elements are equal */static int maxDiff(int arr[], int n){ // Initialize Result int maxDiff = -1; // Initialize max element from right side int maxRight = arr[n-1]; for (int i = n-2; i >= 0; i--) { if (arr[i] > maxRight) maxRight = arr[i]; else { int diff = maxRight - arr[i]; if (diff > maxDiff) { maxDiff = diff; } } } return maxDiff;} /* Driver program to test above function */ public static void main (String[] args) { int arr[] = {1, 2, 90, 10, 110}; int n = arr.length; // Function calling System.out.println (\"Maximum difference is \" + maxDiff(arr, n)); }//This code is contributed by Tushil.. }",
"e": 16166,
"s": 15074,
"text": null
},
{
"code": "# Python3 program to find Maximum difference # between two elements such that larger # element appears after the smaller number # The function assumes that there are # at least two elements in array. The # function returns a negative value if the# array is sorted in decreasing order and # returns 0 if elements are equaldef maxDiff(arr, n): # Initialize Result maxDiff = -1 # Initialize max element from # right side maxRight = arr[-1] for i in reversed(arr[:-1]): if (i > maxRight): maxRight = i else: diff = maxRight - i if (diff > maxDiff): maxDiff = diff return maxDiff # Driver Codeif __name__ == '__main__': arr = [1, 2, 90, 10, 110] n = len(arr) # Function calling print(\"Maximum difference is\", maxDiff(arr, n)) # This code is contributed by 29AjayKumar",
"e": 17066,
"s": 16166,
"text": null
},
{
"code": "// C# program to find Maximum difference // between two elements such that larger // element appears after the smaller numberusing System; class GFG{/* The function assumes that there are at least two elements in array. The function returns a negative value if thearray is sorted in decreasing order and returns 0 if elements are equal */static int maxDiff(int[] arr, int n){ // Initialize Result int maxDiff = -1; // Initialize max element from right side int maxRight = arr[n-1]; for (int i = n-2; i >= 0; i--) { if (arr[i] > maxRight) maxRight = arr[i]; else { int diff = maxRight - arr[i]; if (diff > maxDiff) { maxDiff = diff; } } } return maxDiff;} // Driver Codepublic static void Main () { int[] arr = {1, 2, 90, 10, 110}; int n = arr.Length; // Function calling Console.WriteLine(\"Maximum difference is \" + maxDiff(arr, n));}} // This code is contributed // by Akanksha Rai",
"e": 18129,
"s": 17066,
"text": null
},
{
"code": "<?php// PHP program to find Maximum difference // between two elements such that larger // element appears after the smaller number /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */function maxDiff($arr, $n) { // Initialize Result $maxDiff = -1; // Initialize max element from // right side $maxRight = $arr[$n - 1]; for ($i = $n - 2; $i >= 0; $i--) { if ($arr[$i] > $maxRight) $maxRight = $arr[$i]; else { $diff = $maxRight - $arr[$i]; if ($diff > $maxDiff) { $maxDiff = $diff; } } } return $maxDiff; } // Driver Code$arr = array(1, 2, 90, 10, 110); $n = sizeof($arr); // Function calling echo \"Maximum difference is \", maxDiff($arr, $n); // This code is contributed by ajit?>",
"e": 19121,
"s": 18129,
"text": null
},
{
"code": "<script> // Javascript program to find Maximum difference // between two elements such that larger // element appears after the smaller number /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */ function maxDiff(arr, n) { // Initialize Result let maxDiff = -1; // Initialize max element from right side let maxRight = arr[n-1]; for (let i = n-2; i >= 0; i--) { if (arr[i] > maxRight) maxRight = arr[i]; else { let diff = maxRight - arr[i]; if (diff > maxDiff) { maxDiff = diff; } } } return maxDiff; } let arr = [1, 2, 90, 10, 110]; let n = arr.length; // Function calling document.write(\"Maximum difference is \" + maxDiff(arr, n)); </script>",
"e": 20168,
"s": 19121,
"text": null
},
{
"code": null,
"e": 20177,
"s": 20168,
"text": "Output: "
},
{
"code": null,
"e": 20203,
"s": 20177,
"text": "Maximum difference is 109"
},
{
"code": null,
"e": 20249,
"s": 20203,
"text": "Time Complexity : O(n) Auxiliary Space : O(1)"
},
{
"code": null,
"e": 20593,
"s": 20249,
"text": "Method 3 (Another Tricky Solution) First find the difference between the adjacent elements of the array and store all differences in an auxiliary array diff[] of size n-1. Now this problems turns into finding the maximum sum subarray of this difference array.Thanks to Shubham Mittal for suggesting this solution. Below is the implementation :"
},
{
"code": null,
"e": 20597,
"s": 20593,
"text": "C++"
},
{
"code": null,
"e": 20599,
"s": 20597,
"text": "C"
},
{
"code": null,
"e": 20604,
"s": 20599,
"text": "Java"
},
{
"code": null,
"e": 20612,
"s": 20604,
"text": "Python3"
},
{
"code": null,
"e": 20615,
"s": 20612,
"text": "C#"
},
{
"code": null,
"e": 20619,
"s": 20615,
"text": "PHP"
},
{
"code": null,
"e": 20630,
"s": 20619,
"text": "Javascript"
},
{
"code": "// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number#include <bits/stdc++.h>using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */int maxDiff(int arr[], int n){ // Create a diff array of size n-1. // The array will hold the difference // of adjacent elements int diff[n-1]; for (int i=0; i < n-1; i++) diff[i] = arr[i+1] - arr[i]; // Now find the maximum sum // subarray in diff array int max_diff = diff[0]; for (int i=1; i<n-1; i++) { if (diff[i-1] > 0) diff[i] += diff[i-1]; if (max_diff < diff[i]) max_diff = diff[i]; } return max_diff;} /* Driver program to test above function */int main(){ int arr[] = {80, 2, 6, 3, 100}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << \"Maximum difference is \" << maxDiff(arr, n); return 0;}",
"e": 21721,
"s": 20630,
"text": null
},
{
"code": "#include<stdio.h> int maxDiff(int arr[], int n){ // Create a diff array of size n-1. The array will hold // the difference of adjacent elements int diff[n-1]; for (int i=0; i < n-1; i++) diff[i] = arr[i+1] - arr[i]; // Now find the maximum sum subarray in diff array int max_diff = diff[0]; for (int i=1; i<n-1; i++) { if (diff[i-1] > 0) diff[i] += diff[i-1]; if (max_diff < diff[i]) max_diff = diff[i]; } return max_diff;} /* Driver program to test above function */int main(){ int arr[] = {80, 2, 6, 3, 100}; int size = sizeof(arr)/sizeof(arr[0]); printf(\"Maximum difference is %d\", maxDiff(arr, size)); return 0;}",
"e": 22429,
"s": 21721,
"text": null
},
{
"code": "// Java program to find Maximum difference // between two elements such that larger // element appears after the smaller numberclass MaximumDifference { int maxDiff(int arr[], int n) { // Create a diff array of size n-1. The array will hold // the difference of adjacent elements int diff[] = new int[n - 1]; for (int i = 0; i < n - 1; i++) diff[i] = arr[i + 1] - arr[i]; // Now find the maximum sum subarray in diff array int max_diff = diff[0]; for (int i = 1; i < n - 1; i++) { if (diff[i - 1] > 0) diff[i] += diff[i - 1]; if (max_diff < diff[i]) max_diff = diff[i]; } return max_diff; } // Driver program to test above functions public static void main(String[] args) { MaximumDifference mxdif = new MaximumDifference(); int arr[] = {80, 2, 6, 3, 100}; int size = arr.length; System.out.println(mxdif.maxDiff(arr, size)); }}// This code has been contributed by Mayank Jaiswal",
"e": 23500,
"s": 22429,
"text": null
},
{
"code": "# Python 3 code to find Maximum difference# between two elements such that larger # element appears after the smaller number def maxDiff(arr, n): diff = [0] * (n - 1) for i in range (0, n-1): diff[i] = arr[i+1] - arr[i] # Now find the maximum sum # subarray in diff array max_diff = diff[0] for i in range(1, n-1): if (diff[i-1] > 0): diff[i] += diff[i-1] if (max_diff < diff[i]): max_diff = diff[i] return max_diff # Driver program to test above function arr = [80, 2, 6, 3, 100]size = len(arr)print (\"Maximum difference is\", maxDiff(arr, size)) # This code is contributed by Swetank Modi",
"e": 24191,
"s": 23500,
"text": null
},
{
"code": "// C# code to find Maximum differenceusing System; class GFG { static int maxDiff(int[] arr, int n) { // Create a diff array of size n-1. // The array will hold the // difference of adjacent elements int[] diff = new int[n - 1]; for (int i = 0; i < n - 1; i++) diff[i] = arr[i + 1] - arr[i]; // Now find the maximum sum // subarray in diff array int max_diff = diff[0]; for (int i = 1; i < n - 1; i++) { if (diff[i - 1] > 0) diff[i] += diff[i - 1]; if (max_diff < diff[i]) max_diff = diff[i]; } return max_diff; } // Driver code public static void Main() { int[] arr = { 80, 2, 6, 3, 100 }; int size = arr.Length; Console.Write(maxDiff(arr, size)); }} // This code is contributed by Sam007",
"e": 25079,
"s": 24191,
"text": null
},
{
"code": "<?php// PHP program to find Maximum difference // between two elements such that larger // element appears after the smaller number /* The function assumes that there are at least two elements in array. The function returns a negative value if thearray is sorted in decreasing order and returns 0 if elements are equal */function maxDiff($arr, $n){ // Create a diff array of size n-1. // The array will hold the difference // of adjacent elements $diff[$n-1] = array(); for ($i=0; $i < $n-1; $i++) $diff[$i] = $arr[$i+1] - $arr[$i]; // Now find the maximum sum // subarray in diff array $max_diff = $diff[0]; for ($i=1; $i<$n-1; $i++) { if ($diff[$i-1] > 0) $diff[$i] += $diff[$i-1]; if ($max_diff < $diff[$i]) $max_diff = $diff[$i]; } return $max_diff;} // Driver Code$arr = array(80, 2, 6, 3, 100);$n = sizeof($arr); // Function callingecho \"Maximum difference is \" . maxDiff($arr, $n); // This code is contributed // by Akanksha Rai",
"e": 26116,
"s": 25079,
"text": null
},
{
"code": "<script> // JavaScript program to find Maximum difference// between two elements such that larger// element appears after the smaller number /* The function assumes that there areat least two elements in array. Thefunction returns a negative value if thearray is sorted in decreasing order andreturns 0 if elements are equal */function maxDiff(arr, n){ // Create a diff array of size n-1. // The array will hold the difference // of adjacent elements let diff = new Array(n - 1); for(let i = 0; i < n - 1; i++) diff[i] = arr[i + 1] - arr[i]; // Now find the maximum sum // subarray in diff array let max_diff = diff[0]; for(let i = 1; i < n - 1; i++) { if (diff[i - 1] > 0) diff[i] += diff[i - 1]; if (max_diff < diff[i]) max_diff = diff[i]; } return max_diff;} // Driver codelet arr = [ 80, 2, 6, 3, 100 ];let n = arr.length; // Function callingdocument.write(\"Maximum difference is \" + maxDiff(arr, n)); // This code is contributed by Mayank Tyagi </script>",
"e": 27184,
"s": 26116,
"text": null
},
{
"code": null,
"e": 27192,
"s": 27184,
"text": "Output:"
},
{
"code": null,
"e": 27217,
"s": 27192,
"text": "Maximum difference is 98"
},
{
"code": null,
"e": 27263,
"s": 27217,
"text": "Time Complexity : O(n) Auxiliary Space : O(n)"
},
{
"code": null,
"e": 27453,
"s": 27263,
"text": "We can modify the above method to work in O(1) extra space. Instead of creating an auxiliary array, we can calculate diff and max sum in same loop. Following is the space optimized version."
},
{
"code": null,
"e": 27457,
"s": 27453,
"text": "C++"
},
{
"code": null,
"e": 27462,
"s": 27457,
"text": "Java"
},
{
"code": null,
"e": 27470,
"s": 27462,
"text": "Python3"
},
{
"code": null,
"e": 27473,
"s": 27470,
"text": "C#"
},
{
"code": null,
"e": 27477,
"s": 27473,
"text": "PHP"
},
{
"code": null,
"e": 27488,
"s": 27477,
"text": "Javascript"
},
{
"code": "// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number#include <bits/stdc++.h>using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */int maxDiff (int arr[], int n){ // Initialize diff, current sum and max sum int diff = arr[1]-arr[0]; int curr_sum = diff; int max_sum = curr_sum; for(int i=1; i<n-1; i++) { // Calculate current diff diff = arr[i+1]-arr[i]; // Calculate current sum if (curr_sum > 0) curr_sum += diff; else curr_sum = diff; // Update max sum, if needed if (curr_sum > max_sum) max_sum = curr_sum; } return max_sum;} /* Driver program to test above function */int main(){ int arr[] = {80, 2, 6, 3, 100}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << \"Maximum difference is \" << maxDiff(arr, n); return 0;}",
"e": 28584,
"s": 27488,
"text": null
},
{
"code": "// Java program to find Maximum // difference between two elements // such that larger element appears // after the smaller number class GFG{ /* The function assumes that thereare at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 ifelements are equal */static int maxDiff (int arr[], int n) { // Initialize diff, current // sum and max sum int diff = arr[1] - arr[0]; int curr_sum = diff; int max_sum = curr_sum; for(int i = 1; i < n - 1; i++) { // Calculate current diff diff = arr[i + 1] - arr[i]; // Calculate current sum if (curr_sum > 0) curr_sum += diff; else curr_sum = diff; // Update max sum, if needed if (curr_sum > max_sum) max_sum = curr_sum; } return max_sum; } // Driver Codepublic static void main(String[] args) { int arr[] = {80, 2, 6, 3, 100}; int n = arr.length; // Function calling System.out.print(\"Maximum difference is \" + maxDiff(arr, n)); }} // This code is contributed by Smitha",
"e": 29731,
"s": 28584,
"text": null
},
{
"code": "# Python3 program to find Maximum difference # between two elements such that larger # element appears after the smaller number # The function assumes that there are # at least two elements in array. The # function returns a negative value if # the array is sorted in decreasing # order and returns 0 if elements are equaldef maxDiff (arr, n): # Initialize diff, current # sum and max sum diff = arr[1] - arr[0] curr_sum = diff max_sum = curr_sum for i in range(1, n - 1): # Calculate current diff diff = arr[i + 1] - arr[i] # Calculate current sum if (curr_sum > 0): curr_sum += diff else: curr_sum = diff # Update max sum, if needed if (curr_sum > max_sum): max_sum = curr_sum return max_sum # Driver Codeif __name__ == '__main__': arr = [80, 2, 6, 3, 100] n = len(arr) # Function calling print(\"Maximum difference is\", maxDiff(arr, n)) # This code is contributed # by 29AjayKumar",
"e": 30782,
"s": 29731,
"text": null
},
{
"code": "// C# program to find Maximum // difference between two elements // such that larger element appears // after the smaller number using System;class GFG{ /* The function assumes that thereare at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 ifelements are equal */static int maxDiff (int[] arr, int n) { // Initialize diff, current // sum and max sum int diff = arr[1] - arr[0]; int curr_sum = diff; int max_sum = curr_sum; for(int i = 1; i < n - 1; i++) { // Calculate current diff diff = arr[i + 1] - arr[i]; // Calculate current sum if (curr_sum > 0) curr_sum += diff; else curr_sum = diff; // Update max sum, if needed if (curr_sum > max_sum) max_sum = curr_sum; } return max_sum; } // Driver Codepublic static void Main() { int[] arr = {80, 2, 6, 3, 100}; int n = arr.Length; // Function calling Console.WriteLine(\"Maximum difference is \" + maxDiff(arr, n)); }} // This code is contributed // by Akanksha Rai(Abby_akku)",
"e": 31946,
"s": 30782,
"text": null
},
{
"code": "<?php// PHP program to find Maximum difference // between two elements such that larger // element appears after the smaller number /* The function assumes that there are at least two elements in array. The function returns a negative value if thearray is sorted in decreasing order and returns 0 if elements are equal */function maxDiff ($arr, $n){ // Initialize diff, current sum // and max sum $diff = $arr[1] - $arr[0]; $curr_sum = $diff; $max_sum = $curr_sum; for($i = 1; $i < $n - 1; $i++) { // Calculate current diff $diff = $arr[$i + 1] - $arr[$i]; // Calculate current sum if ($curr_sum > 0) $curr_sum += $diff; else $curr_sum = $diff; // Update max sum, if needed if ($curr_sum > $max_sum) $max_sum = $curr_sum; } return $max_sum;} // Driver Code$arr = array(80, 2, 6, 3, 100);$n = sizeof($arr); // Function callingecho \"Maximum difference is \", maxDiff($arr, $n); // This code is contributed // by Sach_code?>",
"e": 32996,
"s": 31946,
"text": null
},
{
"code": "<script> // Javascript program to find Maximum// difference between two elements// such that larger element appears// after the smaller number /* The function assumes that thereare at least two elements in array.The function returns a negativevalue if the array is sorted indecreasing order and returns 0 ifelements are equal */function maxDiff (arr, n){ // Initialize diff, current // sum and max sum let diff = arr[1] - arr[0]; let curr_sum = diff; let max_sum = curr_sum; for(let i = 1; i < n - 1; i++) { // Calculate current diff diff = arr[i + 1] - arr[i]; // Calculate current sum if (curr_sum > 0) curr_sum += diff; else curr_sum = diff; // Update max sum, if needed if (curr_sum > max_sum) max_sum = curr_sum; } return max_sum;} // Driver Codelet arr = [ 80, 2, 6, 3, 100 ];let n = arr.length; // Function calling document.write(\"Maximum difference is \" + maxDiff(arr, n)); // This code is contributed by rag2127 </script>",
"e": 34084,
"s": 32996,
"text": null
},
{
"code": null,
"e": 34093,
"s": 34084,
"text": "Output: "
},
{
"code": null,
"e": 34118,
"s": 34093,
"text": "Maximum difference is 98"
},
{
"code": null,
"e": 34165,
"s": 34118,
"text": "Time Complexity : O(n) Auxiliary Space : O(1) "
},
{
"code": null,
"e": 35140,
"s": 34165,
"text": "Maximum difference between two elements (larger element appears after smaller) | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersMaximum difference between two elements (larger element appears after smaller) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 11:18•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=SO0bwMziLlU\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 35354,
"s": 35140,
"text": "Below is a variation of this problem: Maximum difference of sum of elements in two rows in a matrixPlease write comments if you find any bug in above codes/algorithms, or find other ways to solve the same problem "
},
{
"code": null,
"e": 35361,
"s": 35354,
"text": "Sam007"
},
{
"code": null,
"e": 35382,
"s": 35361,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 35395,
"s": 35382,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 35401,
"s": 35395,
"text": "jit_t"
},
{
"code": null,
"e": 35411,
"s": 35401,
"text": "Sach_Code"
},
{
"code": null,
"e": 35423,
"s": 35411,
"text": "29AjayKumar"
},
{
"code": null,
"e": 35437,
"s": 35423,
"text": "jana_sayantan"
},
{
"code": null,
"e": 35448,
"s": 35437,
"text": "decode2207"
},
{
"code": null,
"e": 35457,
"s": 35448,
"text": "suresh07"
},
{
"code": null,
"e": 35473,
"s": 35457,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 35481,
"s": 35473,
"text": "rag2127"
},
{
"code": null,
"e": 35497,
"s": 35481,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 35512,
"s": 35497,
"text": "devnawfalahmed"
},
{
"code": null,
"e": 35522,
"s": 35512,
"text": "202051178"
},
{
"code": null,
"e": 35536,
"s": 35522,
"text": "_shinchancode"
},
{
"code": null,
"e": 35543,
"s": 35536,
"text": "Amazon"
},
{
"code": null,
"e": 35548,
"s": 35543,
"text": "Hike"
},
{
"code": null,
"e": 35559,
"s": 35548,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 35568,
"s": 35559,
"text": "Ola Cabs"
},
{
"code": null,
"e": 35577,
"s": 35568,
"text": "SAP Labs"
},
{
"code": null,
"e": 35584,
"s": 35577,
"text": "Arrays"
},
{
"code": null,
"e": 35591,
"s": 35584,
"text": "Amazon"
},
{
"code": null,
"e": 35596,
"s": 35591,
"text": "Hike"
},
{
"code": null,
"e": 35607,
"s": 35596,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 35616,
"s": 35607,
"text": "Ola Cabs"
},
{
"code": null,
"e": 35625,
"s": 35616,
"text": "SAP Labs"
},
{
"code": null,
"e": 35632,
"s": 35625,
"text": "Arrays"
},
{
"code": null,
"e": 35730,
"s": 35632,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35762,
"s": 35730,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 35785,
"s": 35762,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 35841,
"s": 35785,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 35868,
"s": 35841,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 35900,
"s": 35868,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 35945,
"s": 35900,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 35993,
"s": 35945,
"text": "Search an element in a sorted and rotated array"
},
{
"code": null,
"e": 36033,
"s": 35993,
"text": "Find Second largest element in an array"
},
{
"code": null,
"e": 36057,
"s": 36033,
"text": "Find the Missing Number"
}
] |
MITM (Man in The Middle) Attack using ARP Poisoning | 15 Apr, 2021
Introduction :Man In The Middle Attack implies an active attack where the attacker/Hacker creates a connection between the victims and sends messages between them or may capture all the data packets from the victims. In this case, the victims think that they are communicating with each other, but in reality, the malicious attacker/hacker controls the communication i.e. a third person exists to control and monitor the traffic of communication between the two parties i.e. Client and Server.
Types of Man In The Middle Attack :Here, we will discuss the types of Man In The Middle Attack as follows.
ARP Spoofing – ARP Stands for Address Resolution Protocol. This protocol is used for resolving IP addresses to machine MAC addresses. All the devices which want to communicate in the network, broadcast ARP-queries in the system to find out the MAC addresses of other machines. ARP Spoofing is also known as ARP Poisoning. In this, ARP poisoning, ARP packets are forced to send data to the attacker’s machine. ARP Spoofing constructs a huge number of forced ARP requests and replies packets to overload the switch. The intention of the attacker all the network packets and switch set in forwarding mode. DNS Spoofing – Similar to ARP, DNS resolves domain names to IP addresses. DNS spoofing is very dangerous because in this case a hacker will be able to hijack and spoof any DNS request made by the user and can serve the user fake web pages, fake websites, fake login pages, fake updates, and so on.
ARP Spoofing – ARP Stands for Address Resolution Protocol. This protocol is used for resolving IP addresses to machine MAC addresses. All the devices which want to communicate in the network, broadcast ARP-queries in the system to find out the MAC addresses of other machines. ARP Spoofing is also known as ARP Poisoning. In this, ARP poisoning, ARP packets are forced to send data to the attacker’s machine. ARP Spoofing constructs a huge number of forced ARP requests and replies packets to overload the switch. The intention of the attacker all the network packets and switch set in forwarding mode.
DNS Spoofing – Similar to ARP, DNS resolves domain names to IP addresses. DNS spoofing is very dangerous because in this case a hacker will be able to hijack and spoof any DNS request made by the user and can serve the user fake web pages, fake websites, fake login pages, fake updates, and so on.
Man In The Middle Attack Techniques :Here, we will discuss the Man In The middle attack techniques as follows.
Packet Sniffing
Session Hijacking
SSL stripping
Packet Injection
Man in Middle Attack using ARP spoofing : Here we will discuss the steps for Man in Middle Attack using ARP spoofing as follows.
Step-1: ARP spoofing -It allows us to redirect the flow of packets in a computer network. Example of a typical Network as follows.
A Typical Computer Network
Step-2 :But when a hacker becomes Man-In-The-Middle by ARP Spoofing then all the requests and responses start flowing through the hacker’s system as shown below –
computer network after ARP spoofing
Step-3 :By doing this a hacker spoof’s the router by pretending to be the victim, and similarly, he spoofs the victim by pretending to be the router.
How to do an ARP Spoof Attack :We can do an ARP Spoof attack using the built-in tool called ARPSPOOF in Kali Linux, or we can also create an ARP Spoof attack using a python program.
Execution steps :Here, we will discuss the execution steps as follows.
Step-1: We can run the built-in “ARPSPOOF’” tool in Kali Linux. In case the ARPSPOOF tool is not present, install the tool by running the following command as follows.
apt install dsniff
Step-2 : To run this attack we need two things Victim machine’s IP address & the IP of Gateway. In this example, we are using a Windows Machine as our victim and Kali Machine to run the attack. To know the victim machines IP address and gateway IP by running the following command in both the Windows machine and Linux Machine as follows.
arp -a
Output :This will show us the following Outputs as follows.Victim Machine (Windows Machine) –
windows machine
Attacker Machine (Kali Linux) –From these, we can observe that the IP address of the Windows machine is 10.0.2.8 and the IP and MAC addresses of the gateway are 10.0.2.1 and 52:54:00:12:35:00, also the MAC address of our Kali Machine is 08:00:27:a6:1f:86.
Step-3 : Now, write the following commands to perform the ARP Spoof attack.
arpspoof -i eth0 -t 10.0.2.8 10.0.2.1
Here eth0 is the name of the interface, 10.0.2.8 is the IP of the Windows machine and 10.0.2.1 is the IP of the gateway. This will fool the victim by pretending to be the router. So again we will run the above command one more time by switching its IP addresses as follows.
arpspoof -i eth0 -t 10.0.2.1 10.0.2.8
Output :Attacker Machine (Kali Linux) – This shows that our ARP Spoof attack is running, and we have successfully placed our system in the middle of the client and server.
ARP Spoof attack running
We can also check it by running the command as follows.
arp -a
Output :In the output screen, you can observe that the MAC address of the gateway is changed to the MAC address of Kali Machine. Now all the data packets will flow through our Kali machine. Also, you can see that the internet connection of the victim machine is not working because it’s the security feature of Linux, which does not allow the flow of packets through it. So we need to enable Port Forwarding so that this computer will allow the packets to flow through it just like a router.
Step-4 : To enable Port Forwarding to run the command as follows.
echo 1 > /proc/sys/net/ipv4/ip_forward
Output :This command will again establish the Internet connectivity of the victim computer. In this way, we can become the Man-In-The-Middle by using the ARP Spoof attack. So all the requests from the victim’s computer will not directly go to the router it will flow through the attacker’s machine and the attacker can sniff or extract useful information by using various tools like Wire Shark, etc. as shown below as follows.
Wire Shark – used to sniff useful information from the packets.
Information-Security
linux
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Secure Socket Layer (SSL)
GSM in Wireless Communication
Wireless Application Protocol
Mobile Internet Protocol (or Mobile IP)
Introduction of Mobile Ad hoc Network (MANET)
Advanced Encryption Standard (AES)
Cryptography and its Types
Bluetooth
Intrusion Detection System (IDS)
Dynamic Host Configuration Protocol (DHCP) | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Apr, 2021"
},
{
"code": null,
"e": 522,
"s": 28,
"text": "Introduction :Man In The Middle Attack implies an active attack where the attacker/Hacker creates a connection between the victims and sends messages between them or may capture all the data packets from the victims. In this case, the victims think that they are communicating with each other, but in reality, the malicious attacker/hacker controls the communication i.e. a third person exists to control and monitor the traffic of communication between the two parties i.e. Client and Server."
},
{
"code": null,
"e": 629,
"s": 522,
"text": "Types of Man In The Middle Attack :Here, we will discuss the types of Man In The Middle Attack as follows."
},
{
"code": null,
"e": 1533,
"s": 629,
"text": "ARP Spoofing – ARP Stands for Address Resolution Protocol. This protocol is used for resolving IP addresses to machine MAC addresses. All the devices which want to communicate in the network, broadcast ARP-queries in the system to find out the MAC addresses of other machines. ARP Spoofing is also known as ARP Poisoning. In this, ARP poisoning, ARP packets are forced to send data to the attacker’s machine. ARP Spoofing constructs a huge number of forced ARP requests and replies packets to overload the switch. The intention of the attacker all the network packets and switch set in forwarding mode. DNS Spoofing – Similar to ARP, DNS resolves domain names to IP addresses. DNS spoofing is very dangerous because in this case a hacker will be able to hijack and spoof any DNS request made by the user and can serve the user fake web pages, fake websites, fake login pages, fake updates, and so on."
},
{
"code": null,
"e": 2140,
"s": 1533,
"text": "ARP Spoofing – ARP Stands for Address Resolution Protocol. This protocol is used for resolving IP addresses to machine MAC addresses. All the devices which want to communicate in the network, broadcast ARP-queries in the system to find out the MAC addresses of other machines. ARP Spoofing is also known as ARP Poisoning. In this, ARP poisoning, ARP packets are forced to send data to the attacker’s machine. ARP Spoofing constructs a huge number of forced ARP requests and replies packets to overload the switch. The intention of the attacker all the network packets and switch set in forwarding mode. "
},
{
"code": null,
"e": 2438,
"s": 2140,
"text": "DNS Spoofing – Similar to ARP, DNS resolves domain names to IP addresses. DNS spoofing is very dangerous because in this case a hacker will be able to hijack and spoof any DNS request made by the user and can serve the user fake web pages, fake websites, fake login pages, fake updates, and so on."
},
{
"code": null,
"e": 2549,
"s": 2438,
"text": "Man In The Middle Attack Techniques :Here, we will discuss the Man In The middle attack techniques as follows."
},
{
"code": null,
"e": 2565,
"s": 2549,
"text": "Packet Sniffing"
},
{
"code": null,
"e": 2583,
"s": 2565,
"text": "Session Hijacking"
},
{
"code": null,
"e": 2597,
"s": 2583,
"text": "SSL stripping"
},
{
"code": null,
"e": 2614,
"s": 2597,
"text": "Packet Injection"
},
{
"code": null,
"e": 2743,
"s": 2614,
"text": "Man in Middle Attack using ARP spoofing : Here we will discuss the steps for Man in Middle Attack using ARP spoofing as follows."
},
{
"code": null,
"e": 2874,
"s": 2743,
"text": "Step-1: ARP spoofing -It allows us to redirect the flow of packets in a computer network. Example of a typical Network as follows."
},
{
"code": null,
"e": 2901,
"s": 2874,
"text": "A Typical Computer Network"
},
{
"code": null,
"e": 3065,
"s": 2901,
"text": "Step-2 :But when a hacker becomes Man-In-The-Middle by ARP Spoofing then all the requests and responses start flowing through the hacker’s system as shown below – "
},
{
"code": null,
"e": 3101,
"s": 3065,
"text": "computer network after ARP spoofing"
},
{
"code": null,
"e": 3251,
"s": 3101,
"text": "Step-3 :By doing this a hacker spoof’s the router by pretending to be the victim, and similarly, he spoofs the victim by pretending to be the router."
},
{
"code": null,
"e": 3433,
"s": 3251,
"text": "How to do an ARP Spoof Attack :We can do an ARP Spoof attack using the built-in tool called ARPSPOOF in Kali Linux, or we can also create an ARP Spoof attack using a python program."
},
{
"code": null,
"e": 3504,
"s": 3433,
"text": "Execution steps :Here, we will discuss the execution steps as follows."
},
{
"code": null,
"e": 3672,
"s": 3504,
"text": "Step-1: We can run the built-in “ARPSPOOF’” tool in Kali Linux. In case the ARPSPOOF tool is not present, install the tool by running the following command as follows."
},
{
"code": null,
"e": 3691,
"s": 3672,
"text": "apt install dsniff"
},
{
"code": null,
"e": 4032,
"s": 3691,
"text": "Step-2 : To run this attack we need two things Victim machine’s IP address & the IP of Gateway. In this example, we are using a Windows Machine as our victim and Kali Machine to run the attack. To know the victim machines IP address and gateway IP by running the following command in both the Windows machine and Linux Machine as follows."
},
{
"code": null,
"e": 4039,
"s": 4032,
"text": "arp -a"
},
{
"code": null,
"e": 4133,
"s": 4039,
"text": "Output :This will show us the following Outputs as follows.Victim Machine (Windows Machine) –"
},
{
"code": null,
"e": 4150,
"s": 4133,
"text": "windows machine "
},
{
"code": null,
"e": 4406,
"s": 4150,
"text": "Attacker Machine (Kali Linux) –From these, we can observe that the IP address of the Windows machine is 10.0.2.8 and the IP and MAC addresses of the gateway are 10.0.2.1 and 52:54:00:12:35:00, also the MAC address of our Kali Machine is 08:00:27:a6:1f:86."
},
{
"code": null,
"e": 4483,
"s": 4406,
"text": "Step-3 : Now, write the following commands to perform the ARP Spoof attack."
},
{
"code": null,
"e": 4521,
"s": 4483,
"text": "arpspoof -i eth0 -t 10.0.2.8 10.0.2.1"
},
{
"code": null,
"e": 4795,
"s": 4521,
"text": "Here eth0 is the name of the interface, 10.0.2.8 is the IP of the Windows machine and 10.0.2.1 is the IP of the gateway. This will fool the victim by pretending to be the router. So again we will run the above command one more time by switching its IP addresses as follows."
},
{
"code": null,
"e": 4833,
"s": 4795,
"text": "arpspoof -i eth0 -t 10.0.2.1 10.0.2.8"
},
{
"code": null,
"e": 5006,
"s": 4833,
"text": "Output :Attacker Machine (Kali Linux) – This shows that our ARP Spoof attack is running, and we have successfully placed our system in the middle of the client and server. "
},
{
"code": null,
"e": 5031,
"s": 5006,
"text": "ARP Spoof attack running"
},
{
"code": null,
"e": 5088,
"s": 5031,
"text": " We can also check it by running the command as follows."
},
{
"code": null,
"e": 5096,
"s": 5088,
"text": "arp -a "
},
{
"code": null,
"e": 5588,
"s": 5096,
"text": "Output :In the output screen, you can observe that the MAC address of the gateway is changed to the MAC address of Kali Machine. Now all the data packets will flow through our Kali machine. Also, you can see that the internet connection of the victim machine is not working because it’s the security feature of Linux, which does not allow the flow of packets through it. So we need to enable Port Forwarding so that this computer will allow the packets to flow through it just like a router."
},
{
"code": null,
"e": 5654,
"s": 5588,
"text": "Step-4 : To enable Port Forwarding to run the command as follows."
},
{
"code": null,
"e": 5694,
"s": 5654,
"text": "echo 1 > /proc/sys/net/ipv4/ip_forward "
},
{
"code": null,
"e": 6121,
"s": 5694,
"text": "Output :This command will again establish the Internet connectivity of the victim computer. In this way, we can become the Man-In-The-Middle by using the ARP Spoof attack. So all the requests from the victim’s computer will not directly go to the router it will flow through the attacker’s machine and the attacker can sniff or extract useful information by using various tools like Wire Shark, etc. as shown below as follows."
},
{
"code": null,
"e": 6185,
"s": 6121,
"text": "Wire Shark – used to sniff useful information from the packets."
},
{
"code": null,
"e": 6206,
"s": 6185,
"text": "Information-Security"
},
{
"code": null,
"e": 6212,
"s": 6206,
"text": "linux"
},
{
"code": null,
"e": 6230,
"s": 6212,
"text": "Computer Networks"
},
{
"code": null,
"e": 6248,
"s": 6230,
"text": "Computer Networks"
},
{
"code": null,
"e": 6346,
"s": 6248,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6372,
"s": 6346,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 6402,
"s": 6372,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 6432,
"s": 6402,
"text": "Wireless Application Protocol"
},
{
"code": null,
"e": 6472,
"s": 6432,
"text": "Mobile Internet Protocol (or Mobile IP)"
},
{
"code": null,
"e": 6518,
"s": 6472,
"text": "Introduction of Mobile Ad hoc Network (MANET)"
},
{
"code": null,
"e": 6553,
"s": 6518,
"text": "Advanced Encryption Standard (AES)"
},
{
"code": null,
"e": 6580,
"s": 6553,
"text": "Cryptography and its Types"
},
{
"code": null,
"e": 6590,
"s": 6580,
"text": "Bluetooth"
},
{
"code": null,
"e": 6623,
"s": 6590,
"text": "Intrusion Detection System (IDS)"
}
] |
PHP | extract() Function | 29 Mar, 2022
The extract() Function is an inbuilt function in PHP. The extract() function does array to variable conversion. That is it converts array keys into variable names and array values into variable value. In other words, we can say that the extract() function imports variables from an array to the symbol table.Syntax:
int extract($input_array, $extract_rule, $prefix)
Parameters: The extract() function accepts three parameters, out of which one is compulsory and other two are optional. All three parameters are described below:
$input_array: This parameter is required. This specifies the array to use.$extract_rule: This parameter is optional. The extract() function checks for invalid variable names and collisions with existing variable names. This parameter specifies how invalid and colliding names will be treated. This parameter can take the following values: EXTR_OVERWRITE: This rule tells that if there is a collision, overwrite the existing variable.EXTR_SKIP: This rule tells that if there is a collision, don’t overwrite the existing variable.EXTR_PREFIX_SAME: This rule tells that if there is a collision then prefix the variable name according to $prefix parameter.EXTR_PREFIX_ALL: This rule tells that prefix all variable names according to $prefix parameter.EXTR_PREFIX_INVALID: This rule tells that only prefix invalid/numeric variable names according to parameter $prefix.EXTR_IF_EXISTS: This rule tells that to overwrite the variable only if it already exists in the current symbol table, otherwise do nothing.EXTR_PREFIX_IF_EXISTS: This rule tells to create prefixed variable names only if the non-prefixed version of the same variable exists in the current symbol table.$prefix: This parameter is optional. This parameter specifies the prefix. The prefix is automatically separated from the array key by an underscore character. Also this parameter is required only when the parameter $extract_rule is set to EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID or EXTR_PREFIX_IF_EXISTS.
$input_array: This parameter is required. This specifies the array to use.
$extract_rule: This parameter is optional. The extract() function checks for invalid variable names and collisions with existing variable names. This parameter specifies how invalid and colliding names will be treated. This parameter can take the following values: EXTR_OVERWRITE: This rule tells that if there is a collision, overwrite the existing variable.EXTR_SKIP: This rule tells that if there is a collision, don’t overwrite the existing variable.EXTR_PREFIX_SAME: This rule tells that if there is a collision then prefix the variable name according to $prefix parameter.EXTR_PREFIX_ALL: This rule tells that prefix all variable names according to $prefix parameter.EXTR_PREFIX_INVALID: This rule tells that only prefix invalid/numeric variable names according to parameter $prefix.EXTR_IF_EXISTS: This rule tells that to overwrite the variable only if it already exists in the current symbol table, otherwise do nothing.EXTR_PREFIX_IF_EXISTS: This rule tells to create prefixed variable names only if the non-prefixed version of the same variable exists in the current symbol table.
EXTR_OVERWRITE: This rule tells that if there is a collision, overwrite the existing variable.
EXTR_SKIP: This rule tells that if there is a collision, don’t overwrite the existing variable.
EXTR_PREFIX_SAME: This rule tells that if there is a collision then prefix the variable name according to $prefix parameter.
EXTR_PREFIX_ALL: This rule tells that prefix all variable names according to $prefix parameter.
EXTR_PREFIX_INVALID: This rule tells that only prefix invalid/numeric variable names according to parameter $prefix.
EXTR_IF_EXISTS: This rule tells that to overwrite the variable only if it already exists in the current symbol table, otherwise do nothing.
EXTR_PREFIX_IF_EXISTS: This rule tells to create prefixed variable names only if the non-prefixed version of the same variable exists in the current symbol table.
$prefix: This parameter is optional. This parameter specifies the prefix. The prefix is automatically separated from the array key by an underscore character. Also this parameter is required only when the parameter $extract_rule is set to EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID or EXTR_PREFIX_IF_EXISTS.
Return Value: The return value of extract() function is an integer and it represents the number of variables successfully extracted or imported from the array.Examples:
Input : array("a" => "one", "b" => "two", "c" => "three")
Output :$a = "one" , $b = "two" , $c = "three"
Explanation: The keys in the input array will become the
variable names and their values will be assigned to these
new variables.
Below programs illustrates working of extract() in PHP:Example-1:
PHP
<?php // input array $state = array("AS"=>"ASSAM", "OR"=>"ORISSA", "KR"=>"KERELA"); extract($state); // after using extract() function echo"\$AS is $AS\n\$KR is $KR\n\$OR is $OR"; ?>
Output:
$AS is ASSAM
$KR is KERELA
$OR is ORISSA
Example-2:
PHP
<?php $AS="Original"; $state = array("AS"=>"ASSAM", "OR"=>"ORISSA", "KR"=>"KERELA"); // handling collisions with extract() function extract($state, EXTR_PREFIX_SAME, "dup"); echo"\$AS is $AS\n\$KR is $KR\n\$OR if $OR \n\$dup_AS = $dup_AS"; ?>
Output:
$AS is Original
$KR is KERELA
$OR is ORISSA
$dup_AS = ASSAM
Reference: http://php.net/manual/en/function.extract.php
nnr223442
rkbhola5
PHP-array
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Mar, 2022"
},
{
"code": null,
"e": 345,
"s": 28,
"text": "The extract() Function is an inbuilt function in PHP. The extract() function does array to variable conversion. That is it converts array keys into variable names and array values into variable value. In other words, we can say that the extract() function imports variables from an array to the symbol table.Syntax: "
},
{
"code": null,
"e": 395,
"s": 345,
"text": "int extract($input_array, $extract_rule, $prefix)"
},
{
"code": null,
"e": 558,
"s": 395,
"text": "Parameters: The extract() function accepts three parameters, out of which one is compulsory and other two are optional. All three parameters are described below: "
},
{
"code": null,
"e": 2042,
"s": 558,
"text": "$input_array: This parameter is required. This specifies the array to use.$extract_rule: This parameter is optional. The extract() function checks for invalid variable names and collisions with existing variable names. This parameter specifies how invalid and colliding names will be treated. This parameter can take the following values: EXTR_OVERWRITE: This rule tells that if there is a collision, overwrite the existing variable.EXTR_SKIP: This rule tells that if there is a collision, don’t overwrite the existing variable.EXTR_PREFIX_SAME: This rule tells that if there is a collision then prefix the variable name according to $prefix parameter.EXTR_PREFIX_ALL: This rule tells that prefix all variable names according to $prefix parameter.EXTR_PREFIX_INVALID: This rule tells that only prefix invalid/numeric variable names according to parameter $prefix.EXTR_IF_EXISTS: This rule tells that to overwrite the variable only if it already exists in the current symbol table, otherwise do nothing.EXTR_PREFIX_IF_EXISTS: This rule tells to create prefixed variable names only if the non-prefixed version of the same variable exists in the current symbol table.$prefix: This parameter is optional. This parameter specifies the prefix. The prefix is automatically separated from the array key by an underscore character. Also this parameter is required only when the parameter $extract_rule is set to EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID or EXTR_PREFIX_IF_EXISTS."
},
{
"code": null,
"e": 2117,
"s": 2042,
"text": "$input_array: This parameter is required. This specifies the array to use."
},
{
"code": null,
"e": 3208,
"s": 2117,
"text": "$extract_rule: This parameter is optional. The extract() function checks for invalid variable names and collisions with existing variable names. This parameter specifies how invalid and colliding names will be treated. This parameter can take the following values: EXTR_OVERWRITE: This rule tells that if there is a collision, overwrite the existing variable.EXTR_SKIP: This rule tells that if there is a collision, don’t overwrite the existing variable.EXTR_PREFIX_SAME: This rule tells that if there is a collision then prefix the variable name according to $prefix parameter.EXTR_PREFIX_ALL: This rule tells that prefix all variable names according to $prefix parameter.EXTR_PREFIX_INVALID: This rule tells that only prefix invalid/numeric variable names according to parameter $prefix.EXTR_IF_EXISTS: This rule tells that to overwrite the variable only if it already exists in the current symbol table, otherwise do nothing.EXTR_PREFIX_IF_EXISTS: This rule tells to create prefixed variable names only if the non-prefixed version of the same variable exists in the current symbol table."
},
{
"code": null,
"e": 3303,
"s": 3208,
"text": "EXTR_OVERWRITE: This rule tells that if there is a collision, overwrite the existing variable."
},
{
"code": null,
"e": 3399,
"s": 3303,
"text": "EXTR_SKIP: This rule tells that if there is a collision, don’t overwrite the existing variable."
},
{
"code": null,
"e": 3524,
"s": 3399,
"text": "EXTR_PREFIX_SAME: This rule tells that if there is a collision then prefix the variable name according to $prefix parameter."
},
{
"code": null,
"e": 3620,
"s": 3524,
"text": "EXTR_PREFIX_ALL: This rule tells that prefix all variable names according to $prefix parameter."
},
{
"code": null,
"e": 3737,
"s": 3620,
"text": "EXTR_PREFIX_INVALID: This rule tells that only prefix invalid/numeric variable names according to parameter $prefix."
},
{
"code": null,
"e": 3877,
"s": 3737,
"text": "EXTR_IF_EXISTS: This rule tells that to overwrite the variable only if it already exists in the current symbol table, otherwise do nothing."
},
{
"code": null,
"e": 4040,
"s": 3877,
"text": "EXTR_PREFIX_IF_EXISTS: This rule tells to create prefixed variable names only if the non-prefixed version of the same variable exists in the current symbol table."
},
{
"code": null,
"e": 4360,
"s": 4040,
"text": "$prefix: This parameter is optional. This parameter specifies the prefix. The prefix is automatically separated from the array key by an underscore character. Also this parameter is required only when the parameter $extract_rule is set to EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID or EXTR_PREFIX_IF_EXISTS."
},
{
"code": null,
"e": 4530,
"s": 4360,
"text": "Return Value: The return value of extract() function is an integer and it represents the number of variables successfully extracted or imported from the array.Examples: "
},
{
"code": null,
"e": 4766,
"s": 4530,
"text": "Input : array(\"a\" => \"one\", \"b\" => \"two\", \"c\" => \"three\")\nOutput :$a = \"one\" , $b = \"two\" , $c = \"three\"\nExplanation: The keys in the input array will become the \nvariable names and their values will be assigned to these\nnew variables."
},
{
"code": null,
"e": 4833,
"s": 4766,
"text": "Below programs illustrates working of extract() in PHP:Example-1: "
},
{
"code": null,
"e": 4837,
"s": 4833,
"text": "PHP"
},
{
"code": "<?php // input array $state = array(\"AS\"=>\"ASSAM\", \"OR\"=>\"ORISSA\", \"KR\"=>\"KERELA\"); extract($state); // after using extract() function echo\"\\$AS is $AS\\n\\$KR is $KR\\n\\$OR is $OR\"; ?>",
"e": 5054,
"s": 4837,
"text": null
},
{
"code": null,
"e": 5064,
"s": 5054,
"text": "Output: "
},
{
"code": null,
"e": 5105,
"s": 5064,
"text": "$AS is ASSAM\n$KR is KERELA\n$OR is ORISSA"
},
{
"code": null,
"e": 5117,
"s": 5105,
"text": "Example-2: "
},
{
"code": null,
"e": 5121,
"s": 5117,
"text": "PHP"
},
{
"code": "<?php $AS=\"Original\"; $state = array(\"AS\"=>\"ASSAM\", \"OR\"=>\"ORISSA\", \"KR\"=>\"KERELA\"); // handling collisions with extract() function extract($state, EXTR_PREFIX_SAME, \"dup\"); echo\"\\$AS is $AS\\n\\$KR is $KR\\n\\$OR if $OR \\n\\$dup_AS = $dup_AS\"; ?>",
"e": 5403,
"s": 5121,
"text": null
},
{
"code": null,
"e": 5413,
"s": 5403,
"text": "Output: "
},
{
"code": null,
"e": 5474,
"s": 5413,
"text": "$AS is Original\n$KR is KERELA\n$OR is ORISSA \n$dup_AS = ASSAM"
},
{
"code": null,
"e": 5531,
"s": 5474,
"text": "Reference: http://php.net/manual/en/function.extract.php"
},
{
"code": null,
"e": 5541,
"s": 5531,
"text": "nnr223442"
},
{
"code": null,
"e": 5550,
"s": 5541,
"text": "rkbhola5"
},
{
"code": null,
"e": 5560,
"s": 5550,
"text": "PHP-array"
},
{
"code": null,
"e": 5573,
"s": 5560,
"text": "PHP-function"
},
{
"code": null,
"e": 5577,
"s": 5573,
"text": "PHP"
},
{
"code": null,
"e": 5594,
"s": 5577,
"text": "Web Technologies"
},
{
"code": null,
"e": 5598,
"s": 5594,
"text": "PHP"
}
] |
Tryit Editor v3.7 | Tryit: HTML table - colgroup | [] |
How to integrate Android Snackbar? | Snackbar is just like Toast in android but it going to interact with action. It going to show the message at the bottom of the screen without any interaction with other views and close automatically after a time-out.
This example demonstrates how to integrate Android Snackbar.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Open build.gradle and add design support library dependency.
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.andy.myapplication"
minSdkVersion 19
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
Step 3 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="@+id/layout"
android:layout_height="match_parent">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Click here" />
</android.support.design.widget.CoordinatorLayout>
In the above code, we have declare layout id because snackback required parent view. when user click on button it will open snackbar at the bottom.
Step 4 − Add the following code to src/MainActivity.java
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
CoordinatorLayout coordinatorLayout;
@TargetApi(Build.VERSION_CODES.O)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
coordinatorLayout=findViewById(R.id.layout);
Button button=findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "Welcome to tutorialspoint.com", Snackbar.LENGTH_LONG)
.setAction("Click", new View.OnClickListener() {
@Override
public void onClick(View view) {
String url = "http://www.tutorialspoint.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(
android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
});
}
}
In the above when user click on button, it will show snackbar as shown below -
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "Welcome to tutorialspoint.com", Snackbar.LENGTH_LONG)
.setAction("Click", new View.OnClickListener() {
@Override
public void onClick(View view) {
String url = "http://www.tutorialspoint.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
In the above code, we have declare snackbar with message as welcome to tutorialspoint.com and a button as "click". when user clicks on click button it will open a tutorialspoint web site in the default browser.
Step 5 − Add the following code to manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.andy.myapplication">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
In the above code, we have declare internet permission to show web site.
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from an android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
When you click on a button, it will show snackbar message with click button as shown above.
When you click on "click" button it will open default browser with tutorialspoint.com website.
Click here to download the project code | [
{
"code": null,
"e": 1279,
"s": 1062,
"text": "Snackbar is just like Toast in android but it going to interact with action. It going to show the message at the bottom of the screen without any interaction with other views and close automatically after a time-out."
},
{
"code": null,
"e": 1340,
"s": 1279,
"text": "This example demonstrates how to integrate Android Snackbar."
},
{
"code": null,
"e": 1469,
"s": 1340,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1539,
"s": 1469,
"text": "Step 2 − Open build.gradle and add design support library dependency."
},
{
"code": null,
"e": 2493,
"s": 1539,
"text": "apply plugin: 'com.android.application'\nandroid {\n compileSdkVersion 28\n defaultConfig {\n applicationId \"com.example.andy.myapplication\"\n minSdkVersion 19\n targetSdkVersion 28\n versionCode 1\n versionName \"1.0\"\n testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\n }\n buildTypes {\n release {\n minifyEnabled false\n proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n }\n }\n}\ndependencies {\n implementation fileTree(dir: 'libs', include: ['*.jar'])\n implementation 'com.android.support:appcompat-v7:28.0.0'\n implementation 'com.android.support:design:28.0.0'\n implementation 'com.android.support.constraint:constraint-layout:1.1.3'\n testImplementation 'junit:junit:4.12'\n androidTestImplementation 'com.android.support.test:runner:1.0.2'\n androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'\n}"
},
{
"code": null,
"e": 2558,
"s": 2493,
"text": "Step 3 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 3071,
"s": 2558,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<android.support.design.widget.CoordinatorLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:id=\"@+id/layout\"\n android:layout_height=\"match_parent\">\n <Button\n android:id=\"@+id/button\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:text=\"Click here\" />\n</android.support.design.widget.CoordinatorLayout>"
},
{
"code": null,
"e": 3219,
"s": 3071,
"text": "In the above code, we have declare layout id because snackback required parent view. when user click on button it will open snackbar at the bottom."
},
{
"code": null,
"e": 3276,
"s": 3219,
"text": "Step 4 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 5117,
"s": 3276,
"text": "import android.annotation.TargetApi;\nimport android.content.Intent;\nimport android.graphics.Color;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.design.widget.CoordinatorLayout;\nimport android.support.design.widget.Snackbar;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n CoordinatorLayout coordinatorLayout;\n @TargetApi(Build.VERSION_CODES.O)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n coordinatorLayout=findViewById(R.id.layout);\n Button button=findViewById(R.id.button);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Snackbar snackbar = Snackbar\n .make(coordinatorLayout, \"Welcome to tutorialspoint.com\", Snackbar.LENGTH_LONG)\n .setAction(\"Click\", new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n String url = \"http://www.tutorialspoint.com\";\n Intent i = new Intent(Intent.ACTION_VIEW);\n i.setData(Uri.parse(url));\n startActivity(i);\n }\n });\n // Changing message text color\n snackbar.setActionTextColor(Color.RED);\n // Changing action button text color\n View sbView = snackbar.getView();\n TextView textView = (TextView) sbView.findViewById(\n android.support.design.R.id.snackbar_text);\n textView.setTextColor(Color.YELLOW);\n snackbar.show();\n }\n });\n }\n}"
},
{
"code": null,
"e": 5196,
"s": 5117,
"text": "In the above when user click on button, it will show snackbar as shown below -"
},
{
"code": null,
"e": 5861,
"s": 5196,
"text": "Snackbar snackbar = Snackbar\n.make(coordinatorLayout, \"Welcome to tutorialspoint.com\", Snackbar.LENGTH_LONG)\n.setAction(\"Click\", new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n String url = \"http://www.tutorialspoint.com\";\n Intent i = new Intent(Intent.ACTION_VIEW);\n i.setData(Uri.parse(url));\n startActivity(i);\n }\n});\n// Changing message text color\nsnackbar.setActionTextColor(Color.RED);\n// Changing action button text color\nView sbView = snackbar.getView();\nTextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);\ntextView.setTextColor(Color.YELLOW);\nsnackbar.show();"
},
{
"code": null,
"e": 6072,
"s": 5861,
"text": "In the above code, we have declare snackbar with message as welcome to tutorialspoint.com and a button as \"click\". when user clicks on click button it will open a tutorialspoint web site in the default browser."
},
{
"code": null,
"e": 6120,
"s": 6072,
"text": "Step 5 − Add the following code to manifest.xml"
},
{
"code": null,
"e": 6861,
"s": 6120,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.andy.myapplication\">\n <uses-permission android:name=\"android.permission.INTERNET\" />\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 6934,
"s": 6861,
"text": "In the above code, we have declare internet permission to show web site."
},
{
"code": null,
"e": 7284,
"s": 6934,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from an android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 7376,
"s": 7284,
"text": "When you click on a button, it will show snackbar message with click button as shown above."
},
{
"code": null,
"e": 7471,
"s": 7376,
"text": "When you click on \"click\" button it will open default browser with tutorialspoint.com website."
},
{
"code": null,
"e": 7511,
"s": 7471,
"text": "Click here to download the project code"
}
] |
WML - Quick Guide | The topmost layer in the WAP (Wireless Application Protocol) architecture is made up of WAE (Wireless Application Environment), which consists of WML and WML scripting language.
WML stands for Wireless Markup Language
WML stands for Wireless Markup Language
WML is an application of XML, which is defined in a document-type definition.
WML is an application of XML, which is defined in a document-type definition.
WML is based on HDML and is modified so that it can be compared with HTML.
WML is based on HDML and is modified so that it can be compared with HTML.
WML takes care of the small screen and the low bandwidth of transmission.
WML takes care of the small screen and the low bandwidth of transmission.
WML is the markup language defined in the WAP specification.
WML is the markup language defined in the WAP specification.
WAP sites are written in WML, while web sites are written in HTML.
WAP sites are written in WML, while web sites are written in HTML.
WML is very similar to HTML. Both of them use tags and are written in plain text format.
WML is very similar to HTML. Both of them use tags and are written in plain text format.
WML files have the extension ".wml". The MIME type of WML is "text/vnd.wap.wml".
WML files have the extension ".wml". The MIME type of WML is "text/vnd.wap.wml".
WML supports client-side scripting. The scripting language supported is called WMLScript.
WML supports client-side scripting. The scripting language supported is called WMLScript.
WAP Forum has released a latest version WAP 2.0. The markup language defined in WAP 2.0 is XHTML Mobile Profile (MP). The WML MP is a subset of the XHTML. A style sheet called WCSS (WAP CSS) has been introduced alongwith XHTML MP. The WCSS is a subset of the CSS2.
Most of the new mobile phone models released are WAP 2.0-enabled. Because WAP 2.0 is backward compatible to WAP 1.x, WAP 2.0-enabled mobile devices can display both XHTML MP and WML documents.
WML 1.x is an earlier technology. However, that does not mean it is of no use, since a lot of wireless devices that only supports WML 1.x are still being used. Latest version of WML is 2.0 and it is created for backward compatibility purposes. So WAP site developers need not to worry about WML 2.0.
A main difference between HTML and WML is that the basic unit of navigation in HTML is a page, while that in WML is a card. A WML file can contain multiple cards and they form a deck.
When a WML page is accessed from a mobile phone, all the cards in the page are downloaded from the WAP server. So if the user goes to another card of the same deck, the mobile browser does not have to send any requests to the server since the file that contains the deck is already stored in the wireless device.
You can put links, text, images, input fields, option boxes and many other elements in a card.
Following is the basic structure of a WML program:
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card id="one" title="First Card">
<p>
This is the first card in the deck
</p>
</card>
<card id="two" title="Second Card">
<p>
Ths is the second card in the deck
</p>
</card>
</wml>
The first line of this text says that this is an XML document and the version is 1.0. The second line selects
the document type and gives the URL of the document type definition (DTD).
One WML deck (i.e. page ) can have one or more cards as shown above. We will see complete details on WML document structure in subsequent chapter.
Unlike HTML 4.01 Transitional, text cannot be enclosed directly in the <card>...</card> tag pair. So you need to put a content inside <p>...</p> as shown above.
Wireless devices are limited by the size of their displays and keypads. It's therefore very important to take this into account when designing a WAP Site.
While designing a WAP site you must ensure that you keep things simple and easy to use. You should always keep in mind that there are no standard microbrowser behaviors and that the data link may be relatively slow, at around 10Kbps. However, with GPRS, EDGE, and UMTS, this may not be the case for long, depending on where you are located.
The following are general design tips that you should keep in mind when designing a service:
Keep the WML decks and images to less than 1.5KB.
Keep the WML decks and images to less than 1.5KB.
Keep text brief and meaningful, and as far as possible try to precode options to minimize the rather painful experience of user data entry.
Keep text brief and meaningful, and as far as possible try to precode options to minimize the rather painful experience of user data entry.
Keep URLs brief and easy to recall.
Keep URLs brief and easy to recall.
Minimize menu levels to prevent users from getting lost and the system from slowing down.
Minimize menu levels to prevent users from getting lost and the system from slowing down.
Use standard layout tags such as <big> and <b>, and logically structure your information.
Use standard layout tags such as <big> and <b>, and logically structure your information.
Don't go overboard with the use of graphics, as many target devices may not support them.
Don't go overboard with the use of graphics, as many target devices may not support them.
To develop WAP applications, you will need the following:
A WAP enabled Web Server: You can enable your Apache or Microsoft IIS to serve all the WAP client request.
A WAP enabled Web Server: You can enable your Apache or Microsoft IIS to serve all the WAP client request.
A WAP Gateway Simulator: This is required to interact to your WAP server.
A WAP Gateway Simulator: This is required to interact to your WAP server.
A WAP Phone Simulator: This is required to test your WAP Pages and to show all the WAP pages.
A WAP Phone Simulator: This is required to test your WAP Pages and to show all the WAP pages.
You can write your WAP pages using the following languages:
Wireless Markup Language(WML) to develop WAP application.
WML Script to enhance the functionality of WAP application.
In normal web applications, MIME type is set to text/html, designating normal HTML code. Images, on the other hand, could be specified as image/gif or image/jpeg, for instance. With this content type specification, the web browser knows the data type that the web server returns.
To make your Apache WAP compatible, you have nothing to do very much. You simply need to add support for the MIME types and extensions listed below.
Assuming you have Apache Web server installed on your machine. So now we will tell you how to enable WAP functionality in your Apache web server.
So locate Apache's file httpd.conf which is usually in /etc/httpd/conf, and add the following lines to the file and restart the server:
AddType text/vnd.wap.wml .wml
AddType text/vnd.wap.wmlscript .wmls
AddType application/vnd.wap.wmlc .wmlc
AddType application/vnd.wap.wmlscriptc .wmlsc
AddType image/vnd.wap.wbmp .wbmp
In dynamic applications, the MIME type must be set on the fly, whereas in static WAP applications the web server must be configured appropriately.
To configure a Microsoft IIS server to deliver WAP content, you need to perform the following:
Open the Internet Service Manager console and expand the tree to view your Web site entry. You can add the WAP MIME types to a whole server or individual directories.
Open the Properties dialog box by right-clicking the appropriate server or directory, then choose Properties from the menu.
From the Properties dialog, choose the HTTP Headers tab, then select the File Types button at the bottom right.
For each MIME type listed earlier in the above table, supply the extension with or without the dot (it will be automatically added for you), then click OK in the Properties dialog box to accept your changes.
Open the Internet Service Manager console and expand the tree to view your Web site entry. You can add the WAP MIME types to a whole server or individual directories.
Open the Properties dialog box by right-clicking the appropriate server or directory, then choose Properties from the menu.
From the Properties dialog, choose the HTTP Headers tab, then select the File Types button at the bottom right.
For each MIME type listed earlier in the above table, supply the extension with or without the dot (it will be automatically added for you), then click OK in the Properties dialog box to accept your changes.
There are many WAP Gateway Simulator available on the Internet so download any of them and install on your PC. You would need to run this gateway before starting WAP Mobile simulator.
WAP Gateway will take your request and will pass it to the Web Server and whatever response will be received from the Web server that will be passed to the Mobile Simulator.
You can download it from Nokia web site:
Nokia WAP Gateway simulator - Download Nokia WAP Gateway simulator.
Nokia WAP Gateway simulator - Download Nokia WAP Gateway simulator.
There are many WAP Simulator available on the Internet so download any of them and install on your PC which you will use as a WAP client. Here are popular links to download simulator:
Nokia WAP simulator - Download Nokia WAP simulator.
Nokia WAP simulator - Download Nokia WAP simulator.
WinWAP simulator - Download WinWAP browser from their official website.
WinWAP simulator - Download WinWAP browser from their official website.
NOTE: If you have WAP enabled phone then you do not need to install this simulator. But while doing development it is more convenient and economic to use a simulator.
I am giving this section just for your reference, if you are not interested then you can skip this section.
The figure below shows the WAP programming model. Note the similarities with the Internet model. Without the WAP Gateway/Proxy the two models would have been practically identical.
WAP Gateway/Proxy is the entity that connects the wireless domain with the Internet. You should make a note that the request that is sent from the wireless client to the WAP Gateway/Proxy uses the Wireless Session Protocol (WSP). In its essence, WSP is a binary version of HTTP.
A markup language - the Wireless Markup Language (WML) has been adapted to develop optimized WAP applications. In order to save valuable bandwidth in the wireless network, WML can be encoded into a compact binary format. Encoding WML is one of the tasks performed by the WAP Gateway/Proxy.
When it comes to actual use, WAP works like this:
The user selects an option on their mobile device that has a URL with Wireless Markup language (WML) content assigned to it.
The phone sends the URL request via the phone network to a WAP gateway, using the binary encoded WAP protocol.
The gateway translates this WAP request into a conventional HTTP request for the specified URL, and sends it on to the Internet.
The appropriate Web server picks up the HTTP request.
The server processes the request, just as it would any other request. If the URL refers to a static WML file, the server delivers it. If a CGI script is requested, it is processed and the content returned as usual.
The Web server adds the HTTP header to the WML content and returns it to the gateway.
The WAP gateway compiles the WML into binary form.
The gateway then sends the WML response back to the phone.
The phone receives the WML via the WAP protocol.
The micro-browser processes the WML and displays the content on the screen.
The user selects an option on their mobile device that has a URL with Wireless Markup language (WML) content assigned to it.
The user selects an option on their mobile device that has a URL with Wireless Markup language (WML) content assigned to it.
The phone sends the URL request via the phone network to a WAP gateway, using the binary encoded WAP protocol.
The phone sends the URL request via the phone network to a WAP gateway, using the binary encoded WAP protocol.
The gateway translates this WAP request into a conventional HTTP request for the specified URL, and sends it on to the Internet.
The gateway translates this WAP request into a conventional HTTP request for the specified URL, and sends it on to the Internet.
The appropriate Web server picks up the HTTP request.
The appropriate Web server picks up the HTTP request.
The server processes the request, just as it would any other request. If the URL refers to a static WML file, the server delivers it. If a CGI script is requested, it is processed and the content returned as usual.
The server processes the request, just as it would any other request. If the URL refers to a static WML file, the server delivers it. If a CGI script is requested, it is processed and the content returned as usual.
The Web server adds the HTTP header to the WML content and returns it to the gateway.
The Web server adds the HTTP header to the WML content and returns it to the gateway.
The WAP gateway compiles the WML into binary form.
The WAP gateway compiles the WML into binary form.
The gateway then sends the WML response back to the phone.
The gateway then sends the WML response back to the phone.
The phone receives the WML via the WAP protocol.
The phone receives the WML via the WAP protocol.
The micro-browser processes the WML and displays the content on the screen.
The micro-browser processes the WML and displays the content on the screen.
A WML program is typically divided into two parts: the document prolog and the body. Consider the following code:
Following is the basic structure of a WML program:
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card id="one" title="First Card">
<p>
This is the first card in the deck
</p>
</card>
<card id="two" title="Second Card">
<p>
Ths is the second card in the deck
</p>
</card>
</wml>
The first line of this text says that this is an XML document and the version is 1.0. The second line selects
the document type and gives the URL of the document type definition (DTD). The DTD referenced is defined in WAP 1.2, but this header changes with the versions of the WML. The header must be copied exactly so that the tool kits automatically generate this prolog.
The prolog components are not WML elements and they should not be closed, i.e. you should not give them an end tag or finish them with />.
The body is enclosed within a <wml> </wml> tag pair. The body of a WML document can consist of one or more of the following:
Deck
Deck
Card
Card
Content to be shown
Content to be shown
Navigation instructions
Navigation instructions
Unlike HTML 4.01 Transitional, text cannot be enclosed directly in the <card>...</card> tag pair. So you need to put a content inside <p>...</p> as shown above.
Put above code in a file called test.wml file, and put this WML file locally on your hard disk, then view it using an emulator.
This is by far the most efficient way of developing and testing WML files. Since your aim is, however, to develop a service that is going to be available to WAP phone users, you should upload your WML files onto a server once you have developed them locally and test them over a real Internet connection. As you start developing more complex WAP services, this is how you will identify and rectify performance problems, which could, if left alone, lose your site visitors.
In uploading the file test.wml to a server, you will be testing your WML emulator to see how it looks and behaves, and checking your Web server to see that it is set up correctly. Now start your emulator and use it to access the URL of test.wml. For example, the URL might look something like this:
http://websitename.com/wapstuff/test.wml
NOTE: Before accessing any URL, make sure WAP Gateway Simulator is running on your PC.
When you will download your WAP program, then you will see only first card at your mobile. Following is the output of the above example on Nokia Mobile Browser 4.0. This mobile supports horizontal scrolling. You can see the text off the screen by pressing the "Left" or "Right" button.
When you press right button, then second card will be visible as follows:
WML is defined by a set of elements that specify all markup and structural information for a WML
deck. Elements are identified by tags, which are each enclosed in a pair of angle brackets.
Unlike HTML, WML strictly adheres to the XML hierarchical structure, and thus, elements must contain a start tag; any content such as text and/or other elements; and an end tag. Elements have one of the following two structures:
<tag> content </tag> : This form is identical to HTML.
<tag> content </tag> : This form is identical to HTML.
<tag />: This is used when an element cannot contain visible content or is empty, such as a line break. WML document's prolog part does not have any element which has closing element.
<tag />: This is used when an element cannot contain visible content or is empty, such as a line break. WML document's prolog part does not have any element which has closing element.
Following table lists the majority of valid elements. A complete detail of all these elements is given in WML Tags Reference.
As with most programming languages, WML also provides a means of placing comment text within the code.
Comments are used by developers as a means of documenting programming decisions within the code to allow for easier code maintenance.
WML comments use the same format as HTML comments and use the following syntax:
<!-- This will be assumed as a comment -->
A multiline comment can be given as follows:
<!-- This is a multi-line
comment -->
The WML author can use comments anywhere, and they are not displayed to the user by the user agent. Some emulators may complain if comments are placed before the XML prolog.
Note that comments are not compiled or sent to the user agent, and thus have no effect on the size of the compiled deck.
Because multiple cards can be contained within one deck, some mechanism needs to be in place to hold data as the user traverses from card to card. This mechanism is provided via WML variables.
WML is case sensitive. No case folding is performed when parsing a WML deck. All enumerated attribute values are case sensitive. For example, the following attribute values are all different: id="Card1", id="card1", and id="CARD1".
Variables can be created and set using several different methods. Following are two examples:
The <setvar> element is used as a result of the user executing some task. The >setvar> element can be used to set a variable's state within the following elements: <go>, <prev>, and <refresh>.
This element supports the following attributes:
The following element would create a variable named a with a value of 1000:
<setvar name="a" value="1000"/>
Variables are also set through any input element like input,select, option, etc. A variable is automatically created that corresponds with the named attribute of an input element.
For example, the following element would create a variable named b:
<select name="b">
<option value="value1">Option 1</option>
<option value="value2">Option 2</option>
</select>
Variable expansion occurs at runtime, in the microbrowser or emulator. This means it can be concatenated with or embedded in other text.
Variables are referenced with a preceding dollar sign, and any single dollar sign in your WML deck is interpreted as a variable reference.
<p> Selected option value is $(b) </p>
This section will describe basic text formatting elements of WML.
The <br /> element defines a line break and almost all WAP browsers supports a line break tag.
The <br /> element supports the following attributes:
Following is the example showing usage of <br /> element.
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Line Break Example">
<p align="center">
This is a <br /> paragraph with a line break.
</p>
</card>
</wml>
This will produce the following result:
The <p> element defines a paragraph of text and WAP browsers always render a paragraph in a new line.
A <p> element is required to define any text, image or a table in WML.
The <p> element supports the following attributes:
left
right
center
wrap
nowrap
Following is the example showing usage of <p> element.
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Paragraph Example">
<p align="center">
This is first paragraph
</p>
<p align="right">
This is second paragraph
</p>
</card>
</wml>
This will produce the following result:
The <table> element along with <tr> and <td> is used to create a table in WML. WML does not allow the nesting of tables
A <table> element should be put with-in <p>...</p> elements.
The <table /> element supports the following attributes:
L
C
R
First table column -- Left-aligned
First table column -- Left-aligned
Second table column -- Center-aligned
Second table column -- Center-aligned
Third table column -- Right-aligned
Third table column -- Right-aligned
Then you should set the value of the align attribute to LCR.
Following is the example showing usage of <table> element.
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="WML Tables">
<p>
<table columns="3" align="LCR">
<tr>
<td>Col 1</td>
<td>Col 2</td>
<td>Col 3</td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
<tr>
<td>D</td>
<td>E</td>
<td>F</td>
</tr>
</table>
</p>
</card>
</wml>
This will produce the following result:
The <pre> element is used to specify preformatted text in WML. Preformatted text is text of which the format follows the way it is typed in the WML document.
This tag preserves all the white spaces enclosed inside this tag. Make sure you are not putting this tag inside <p>...</p>
The <pre> element supports following attributes:
Following is the example showing usage of <pre> element.
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Preformatted Text">
<pre>
This is preformatted
text and will appear
as it it.
</pre>
</card>
</wml>
This will produce the following result:
WML does not support <font> element, but there are other WML elements, which you can use to create different font effects like underlined text, bold text and italic text, etc.
These tags are given in the following table:
These elements support the following attributes:
Following is the example showing usage of these elements.
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Text Formatting">
<p>
<b>bold text</b><br/>
<big>big text</big><br/>
<em>emphasized text</em><br/>
<i>italic text</i><br/>
<small>small text</small><br/>
<strong>strong text</strong><br/>
<u>underlined text</u>
</p>
</card>
</wml>
This will produce the following result:
The <img> element is used to include an image in a WAP card. WAP-enabled wireless devices only supported the Wireless Bitmap (WBMP) image format.
WBMP images can only contain two colors: black and white. The file extension of WBMP is ".wbmp" and the MIME type of WBMP is "image/vnd.wap.wbmp".
The <img> element supports the following attributes:
top
middle
bottom
px
%
px
%
px
%
px
%
There are free tools available on the Internet to make ".wbmp" images.
The Nokia Mobile Internet Toolkit (NMIT) comes with a WBMP image editor that you can use. You can convert existing GIF or JPG image files into WBMP file using NMIT.
Another free tool is ImageMagick, which can help you to create WBMP images.
Following is the example showing usage of <img> element.
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="WML Images">
<p>
This is Thumb image
<img src="/images/thumb.wbmp" alt="Thumb Image"/>
</p>
<p>
This is Heart image
<img src="/images/heart.wbmp" alt="Heart Image"/>
</p>
</card>
</wml>
This will produce the following result:
The <table> element along with <tr> and <td> is used to create a table in WML. WML does not allow the nesting of tables
A <table> element should be put with-in <p>...</p> elements.
The <table /> element supports the following attributes:
L
C
R
First table column -- Left-aligned
First table column -- Left-aligned
Second table column -- Center-aligned
Second table column -- Center-aligned
Third table column -- Right-aligned
Third table column -- Right-aligned
Then you should set the value of the align attribute to LCR.
Following is the example showing usage of <table> element.
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="WML Tables">
<p>
<table columns="3" align="LCR">
<tr>
<td>Col 1</td>
<td>Col 2</td>
<td>Col 3</td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
<tr>
<td>D</td>
<td>E</td>
<td>F</td>
</tr>
</table>
</p>
</card>
</wml>
This will produce the following result:
WML provides you an option to link various cards using links and then navigate through different cards.
There are two WML elements, <anchor> and <a>, which can be used to create WML links.
The <anchor>...</anchor> tag pair is used to create an anchor link. It is used together with other WML elements called <go/>, <refresh> or <prev/>. These elements are called task elements and tell WAP browsers what to do when a user selects the anchor link
You can enclose Text or image along with a task tag inside <anchor>...</anchor> tag pair.
The <anchor> element supports the following attributes:
Following is the example showing usage of <anchor> element.
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Anchor Element">
<p>
<anchor>
<go href="nextpage.wml"/>
</anchor>
</p>
<p>
<anchor>
<prev/>
</anchor>
</p>
</card>
</wml>
This will produce the following result:
The <a>...</a> tag pair can also be used to create an anchor link and always a preferred way of creating links.
You can enclose Text or image inside <a>...</a> tags.
The <a> element supports the following attributes:
Following is the example showing usage of <a> element.
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="A Element">
<p> Link to Next Page:
<a href="nextpage.wml">Next Page</a>
</p>
</card>
</wml>
This will produce the following result:
A WML task is an element that specifies an action to be performed by the browser, rather than something to be displayed. For example, the action of changing to a new card is represented by a <go> task element, and the action of returning to the previous card visited is represented by a <prev> task element. Task elements encapsulate all the information required to perform the action.
WML provides following four elements to handle four WML tasks called go task, pre task, refresh task and noop taks.
As the name suggests, the <go> task represents the action of going to a new card.
The <go> element supports the following attributes:
get
post
When using method="get", the data is sent as an request with ? data appended to the url. The method has a disadvantage, that it can be used only for a limited amount of data, and if you send sensitive information it will be displayed on the screen and saved in the web server's logs. So do not use this method if you are sending password etc.
With method="post", the data is sent as an request with the data sent in the body of the request. This method has no limit, and sensitive information is not visible in the URL
true
false
Following is the example showing usage of <go> element.
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="GO Element">
<p>
<anchor>
Chapter 2 : <go href="chapter2.wml"/>
</anchor>
</p>
</card>
</wml>
Another example showing how to upload data using Get Method
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="GO Element">
<p>
<anchor>
Using Get Method
<go href="chapter2.wml?x=17&y=42" method="get"/>
</anchor>
</p>
</card>
</wml>
Another example showing how to upload data using <setvar> element.
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="GO Element">
<p>
<anchor>
Using setvar:
<go href="chapter2.wml">
<setvar name="x" value="17"/>
<setvar name="y" value="42"/>
</go>
</anchor>
</p>
</card>
</wml>
Another example showing how to upload data using <postfiled> element
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="GO Element">
<p>
<anchor>
Using setvar:
<go href="chapter2.wml" method="get">
<postfield name="x" value="17"/>
<postfield name="y" value="42"/>
</go>
</anchor>
</p>
</card>
</wml>
The <prev> task represents the action of returning to the previously visited card on the history stack. When this action is performed, the top entry is removed from the history stack, and that card is displayed again, after any <setvar> variable assignments in the <prev> task have taken effect.
If no previous URL exists, specifying <prev> has no effect.
The <prev> element supports the following attributes:
Following is the example showing usage of <prev> element.
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Prev Element">
<p>
<anchor>
Previous Page :<prev/>
</anchor>
</p>
</card>
</wml>
One situation where it can be useful to include variables in a <prev> task is a login page, which prompts for a username and password. In some situations, you may want to clear out the password field when returning to the login card, forcing the user to reenter it. This can be done with a construct such as:
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Prev Element">
<p>
<anchor>
<prev>
<setvar name="password" value=""/>
</prev>
</anchor>
</p>
</card>
</wml>
The <refresh> task is the simplest task that actually does something. Its effect is simply to perform the variable assignments specified by its <setvar> elements, then redisplay the current card with the new values. The <go> and <prev> tasks perform the same action just before displaying the new card.
The <refresh> task is most often used to perform some sort of "reset" action on the card.
The <refresh> element supports the following attributes:
Following is the example showing usage of <refresh> element.
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Referesh Element">
<p>
<anchor>
Refresh this page:
<go href="test.wml"/>
<refresh>
<setvar name="x" value="100"/>
</refresh>
</anchor>
</p>
</card>
</wml>
The purpose of the <noop> task is to do nothing (no operation).
The only real use for this task is in connection with templates
The <noop> element supports the following attributes:
Following is the example showing usage of <noop> element.
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Noop Element">
<p>
<do type="prev" label="Back">
<noop/>
</do>
</p>
</card>
</wml>
WML provides various options to let a user enter information through WAP application.
First of all, we are going to look at the different options for allowing the user to make straight choices between items. These are usually in the form of menus and submenus, allowing users to drill down to the exact data that they want.
The <select>...</select> WML elements are used to define a selection list and the <option>...</option> tags are used to define an item in a selection list. Items are presented as radiobuttons in some WAP browsers. The <option>...</option> tag pair should be enclosed within the <select>...</select> tags.
This element support the following attributes:
true
false
Following is the example showing usage of these two elements.
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Selectable List">
<p> Select a Tutorial :
<select>
<option value="htm">HTML Tutorial</option>
<option value="xml">XML Tutorial</option>
<option value="wap">WAP Tutorial</option>
</select>
</p>
</card>
</wml>
When you will load this program, it will show you the following screen:
Once you highlight and enter on the options, it will display the following screen:
You want to provide option to select multiple options, then set multiple attribute to true as follows:
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Selectable List">
<p> Select a Tutorial :
<select multiple="true">
<option value="htm">HTML Tutorial</option>
<option value="xml">XML Tutorial</option>
<option value="wap">WAP Tutorial</option>
</select>
</p>
</card>
</wml>
This will give you a screen to select multiple options as follows:
The <input/> element is used to create input fields and input fields are used to obtain alphanumeric data from users.
This element support the following attributes:
true
false
A = uppercase alphabetic or punctuation characters
a = lowercase alphabetic or punctuation characters
N = numeric characters
X = uppercase characters
x = lowercase characters
M = all characters
m = all characters
*f = Any number of characters. Replace the f with one of the letters above to specify what characters the user can enter
nf = Replace the n with a number from 1 to 9 to specify the number of characters the user can enter. Replace the f with one of the letters above to specify what characters the user can enter
text
password
Following is the example showing usage of this element.
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Input Fields">
<p> Enter Following Information:<br/>
Name: <input name="name" size="12"/>
Age : <input name="age" size="12" format="*N"/>
Sex : <input name="sex" size="12"/>
</p>
</card>
</wml>
This will provide you the following screen to enter required information:
The <fieldset/> element is used to group various input fields or selectable lists.
This element support the following attributes:
Following is the example showing usage of this element.
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Grouped Fields">
<p>
<fieldset title="Personal Info">
Name: <input name="name" size="12"/>
Age : <input name="age" size="12" format="*N"/>
Sex : <input name="sex" size="12"/>
</fieldset>
</p>
</card>
</wml>
This will provide you the following screen to enter required information. This result may differ browser to browser.
The <optgroup/> element is used to group various options together inside a selectable list.
This element support the following attributes:
Following is the example showing usage of this element.
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Selectable List">
<p>
<select>
<optgroup title="India">
<option value="delhi">Delhi</option>
<option value="mumbai">Mumbai</option>
<option value="hyderabad">Hyderabad</option>
</optgroup>
<optgroup title="USA">
<option value="ohio">Ohio</option>
<option value="maryland">Maryland</option>
<option value="washington">Washingtone</option>
</optgroup>
</select>
</p>
</card>
</wml>
When a user loads above code, then it will give two options to be selected:
When a user selects any of the options, then only it will give final options to be selected. So if user selects India, then it will show you following options to be selected:
Many times, you will want your users to submit some data to your server. Similar to HTML Form WML also provide a mechanism to submit user data to web server.
To submit data to the server in WML, you need the <go>...</go> along with <postfield/> tags. The <postfield/> tag should be enclosed in the <go>...</go> tag pair.
To submit data to a server, we collect all the set WML variables and use <postfield> elements to send them to the server. The <go>...</go> elements are used to set posting method to either POST or GET and to specify a server side script to handle uploaded data.
In previous chapters we have explained various ways of taking inputs form the users. These input elements sets WML variables to the entered values. We also know how to take values from WML variables. So now following example shows how to submit three fields name, age and sex to the server.
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card id="card1" title="WML Form">
<p>
Name: <input name="name" size="12"/>
Sex : <select name="sex">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
Age : <input name="age" size="12" format="*N"/>
<anchor>
<go method="get" href="process.php">
<postfield name="name" value="$(name)"/>
<postfield name="age" value="$(age)"/>
<postfield name="sex" value="$(sex)"/>
</go>
Submit Data
</anchor>
</p>
</card>
</wml>
When you download above code on your WAP device, it will provide you option to enter three fields name, age and sex and one link Submit Data. You will enter three fields and then finally you will select Submit Data link to send entered data to the server.
The method attribute of the <go> tag specifies which HTTP method should be used to send the form data.
If the HTTP POST method is used, the form data to be sent will be placed in the message body of the request. If the HTTP GET method is used, the form data to be sent will be appended to the URL. Since a URL can only contain a limited number of characters, the GET method has the disadvantage that there is a size limit for the data to be sent. If the user data contains non-ASCII characters, you should make use of the POST method to avoid encoding problems.
There is one major difference between HTML and WML. In HTML, the name attribute of the <input> and <select> tags is used to specify the name of the parameter to be sent, while in WML the name attribute of the <postfield> tag is used to do the same thing. In WML, the name attribute of <input> and <select> is used to specify the name of the variable for storing the form data.
Next chapter will teach you how to handle uploaded data at server end.
If you already know how to write server side scripts for Web Application, then for you this is very simple to write Server Side program for WML applications. You can use your favorite server-side technology to do the processing required by your mobile Internet application.
At the server side, the parameter name will be used to retrieve the form data.
Consider the following example from previous chapter to submit name, age and sex of a person:
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card id="card1" title="WML Form">
<p>
Name: <input name="name" size="12"/>
Sex : <select name="sex">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
Age : <input name="age" size="12" format="*N"/>
<anchor>
<go method="get" href="process.php">
<postfield name="name" value="$(name)"/>
<postfield name="age" value="$(age)"/>
<postfield name="sex" value="$(sex)"/>
</go>
Submit Data
</anchor>
</p>
</card>
</wml>
Now, we can write a server side script to handle this submitted data in using either PHP, PERL, ASP or JSP. I will show you a server side script written in PHP with HTTP GET method.
Put the following PHP code in process.php file in same directory where you have your WML file.
<?php echo 'Content-type: text/vnd.wap.wml'; ?>
<?php echo '<?xml version="1.0"?'.'>'; ?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card id="card1" title="WML Response">
<p>
Data received at the server:<br/>
Name: <?php echo $_GET["name"]; ?><br/>
Age: <?php echo $_GET["age"]; ?><br/>
Sex: <?php echo $_GET["sex"]; ?><br/>
</p>
</card>
</wml>
If you are using HTTP POST method, then you have to write PHP script accordingly to handle received data. While sending output back to the browser, remember to set the MIME type of the document to "text/vnd.wap.wml".
This way, you can write full fledged Web Application where lot of database transactions are involved.
You can use PERL CGI Concepts to write a dynamic WAP site.
Event in ordinary language can be defined as something happened. In programming, event is identical in meaning, but with one major difference. When something happens in a computer system, the system itself has to (1) detect that something has happened and (2) know what to do about it.
WML language also supports events and you can specify an action to be taken whenever an event occurs. This action could be in terms of WMLScript or simply in terms of WML.
WML supports following four event types:
onenterbackward: This event occurs when the user hits a card by normal backward navigational means. That is, user presses the Back key on a later card and arrives back at this card in the history stack.
onenterbackward: This event occurs when the user hits a card by normal backward navigational means. That is, user presses the Back key on a later card and arrives back at this card in the history stack.
onenterforward: This event occurs when the user hits a card by normal forward navigational means.
onenterforward: This event occurs when the user hits a card by normal forward navigational means.
onpick: This is more like an attribute but it is being used like an event. This event occurs when an item of a selection list is selected or deselected.
onpick: This is more like an attribute but it is being used like an event. This event occurs when an item of a selection list is selected or deselected.
ontimer: This event is used to trigger an event after a given time period.
ontimer: This event is used to trigger an event after a given time period.
These event names are case sensitive and they must be lowercase.
The <onevent>...</onevent> tags are used to create event handlers. Its usage takes the following form:
<onevent type="event_type">
A task to be performed.
</onevent>
You can use either go, prev or refresh task inside <onevent>...</onevent> tags against an event.
The <onevent> element supports the following attributes:
onenterbackward
onenterforward
onpick
ontimer
Following is the example showing usage of <onevent> element. In this example, whenever you try to go back from second card to first card then onenterbackward occurs which moves you to card number three. Copy and paste this program and try to play with it.
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<onevent type="onenterbackward">
<go href="#card3"/>
</onevent>
<card id="card1" title="Card 1">
<p>
<anchor>
<go href="#card2"/>
Go to card 2
</anchor>
</p>
</card>
<card id="card2" title="Card 2">
<p>
<anchor>
<prev/>
Going backwards
</anchor>
</p>
</card>
<card id="card3" title="Card 3">
<p>
Hello World!
</p>
</card>
</wml>
Previous chapter has described how events are triggered by the users and how do we handle them using event handlers.
Sometime, you may want something to happen without the user explicitly having to activate a control. Yes, WML provides you ontimer event to handle this.
The ontimer event is triggered when a card's timer counts down from one to zero, which means that it doesn't occur if the timer is initialized to a timeout of zero.
You can bind a task to this event with the <onevent> element. Here is the syntax:
<onevent type="ontimer">
A task to be performed.
</onevent>
Here, a task could be <go>, <prev> or <refresh>.
A timer is declared inside a WML card with the <timer> element. It must follow the <onevent> elements if they
are present. (If there are no <onevent> elements, the <timer> must be the first element inside the <card>.) No
more than one <timer> may be present in a card.
The <timer> element supports the following attributes:
Following is the example showing usage of <timer> element.
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card id="splash" title="splash">
<onevent type="ontimer">
<go href="#welcome"/>
</onevent>
<timer value="50"/>
<p>
<a href="#welcome">Enter</a>
</p>
</card>
<card id="welcome" title="Welcome">
<p>
Welcome to the main screen.
</p>
</card>
</wml>
When you load this program it shows you following screen:
If you do not select given Enter option then after 5 seconds, you will be directed to Welcome page and following screen will be displayed automatically.
The <template> is used to apply <do> and <onevent> elements to all cards in a deck. This element defines a template for all the cards in a deck and the code in the <template> tag is added to each card in the deck.
You can override a <do> element of a template by defining another <do> element with the same name attribute value in a WML card.
The <template> element supports the following attributes:
Following is the example showing usage of <go> element.
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.3//EN"
"http://www.wapforum.org/DTD/wml13.dtd">
<wml>
<template>
<do name="main_menu" type="accept" label="Chapters">
<go href="chapters"/>
</do>
<do name="menu_1" type="accept" label="Chapter 1">
<go href="#chapter1"/>
</do>
<do name="menu_2" type="accept" label="Chapter 2">
<go href="#chapter2"/>
</do>
<do name="menu_3" type="accept" label="Chapter 3">
<go href="#chapter3"/>
</do>
<do name="menu_4" type="accept" label="Chapter 4">
<go href="#chapter4"/>
</do>
</template>
<card id="chapters" title="WML Tutorial">
<p>
Select One Chapter:<br/>
<anchor>
<go href="#chapter1"/>
Chapter 1: WML Overview
</anchor><br />
<anchor>
<go href="#chapter2"/>
Chapter 2: WML Environment
</anchor><br />
<anchor>
<go href="#chapter3"/>
Chapter 3: WML Syntax
</anchor><br />
<anchor>
<go href="#chapter4"/>
Chapter 4: WML Elements
</anchor><br />
</p>
</card>
<card id="chapter1" title="WML Tutorial Ch1">
<p>
<em>Chapter 1: WML Introduction</em><br/>
...
</p>
</card>
<card id="chapter2" title="WML Tutorial Ch2">
<p>
<em>Chapter 2: WML Environment</em><br/>
...
</p>
</card>
<card id="chapter3" title="WML Tutorial Ch3">
<p>
<em>Chapter 3: WML Syntax</em><br/>
...
</p>
</card>
<card id="chapter4" title="WML Tutorial Ch4">
<p>
<em>Chapter 4: WML Elements</em><br/>
...
</p>
</card>
</wml>
This will produce the following menu and now you can navigate through all the chapters:
Here is the complete DTD taken from W3.org. For a latest DTD, please check WML Useful Resources section of this tutorial.
<!--
Wireless Markup Language (WML) Document Type Definition.
WML is an XML language. Typical usage:
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
...
</wml>
Terms and conditions of use are available from the WAP Forum
Ltd. web site at http://www.wapforum.org/docs/copyright.htm.
-->
<!ENTITY % length "CDATA">
<!-- [0-9]+ for pixels or [0-9]+"%" for
percentage length -->
<!ENTITY % vdata "CDATA">
<!-- attribute value possibly containing
variable references -->
<!ENTITY % HREF "%vdata;">
<!-- URI, URL or URN designating a hypertext
node. May contain variable references -->
<!ENTITY % boolean "(true|false)">
<!ENTITY % number "NMTOKEN">
<!-- a number, with format [0-9]+ -->
<!ENTITY % coreattrs "id ID #IMPLIED
class CDATA #IMPLIED">
<!ENTITY % ContentType "%vdata;">
<!-- media type. May contain variable references -->
<!ENTITY % emph "em | strong |b |i |u |big |small">
<!ENTITY % layout "br">
<!ENTITY % text "#PCDATA | %emph;">
<!-- flow covers "card-level" elements,
such as text and images -->
<!ENTITY % flow "%text; | %layout; | img | anchor |a |table">
<!-- Task types -->
<!ENTITY % task "go | prev | noop | refresh">
<!-- Navigation and event elements -->
<!ENTITY % navelmts "do | onevent">
<!--================ Decks and Cards ================-->
<!ELEMENT wml ( head?, template?, card+ )>
<!ATTLIST wml
xml:lang NMTOKEN #IMPLIED
%coreattrs;
>
<!-- card intrinsic events -->
<!ENTITY % cardev
"onenterforward %HREF; #IMPLIED
onenterbackward %HREF; #IMPLIED
ontimer %HREF; #IMPLIED"
>
<!-- card field types -->
<!ENTITY % fields "%flow; | input | select | fieldset">
<!ELEMENT card (onevent*, timer?, (do | p | pre)*)>
<!ATTLIST card
title %vdata; #IMPLIED
newcontext %boolean; "false"
ordered %boolean; "true"
xml:lang NMTOKEN #IMPLIED
%cardev;
%coreattrs;
>
<!--================ Event Bindings ================-->
<!ELEMENT do (%task;)>
<!ATTLIST do
type CDATA #REQUIRED
label %vdata; #IMPLIED
name NMTOKEN #IMPLIED
optional %boolean; "false"
xml:lang NMTOKEN #IMPLIED
%coreattrs;
>
<!ELEMENT onevent (%task;)>
<!ATTLIST onevent
type CDATA #REQUIRED
%coreattrs;
>
<!--================ Deck-level declarations ================-->
<!ELEMENT head ( access | meta )+>
<!ATTLIST head
%coreattrs;
>
<!ELEMENT template (%navelmts;)*>
<!ATTLIST template
%cardev;
%coreattrs;
>
<!ELEMENT access EMPTY>
<!ATTLIST access
domain CDATA #IMPLIED
path CDATA #IMPLIED
%coreattrs;
>
<!ELEMENT meta EMPTY>
<!ATTLIST meta
http-equiv CDATA #IMPLIED
name CDATA #IMPLIED
forua %boolean; "false"
content CDATA #REQUIRED
scheme CDATA #IMPLIED
%coreattrs;
>
<!--================ Tasks ================-->
<!ELEMENT go (postfield | setvar)*>
<!ATTLIST go
href %HREF; #REQUIRED
sendreferer %boolean; "false"
method (post|get) "get"
enctype %ContentType; "application/x-www-form-urlencoded"
accept-charset CDATA #IMPLIED
%coreattrs;
>
<!ELEMENT prev (setvar)*>
<!ATTLIST prev
%coreattrs;
>
<!ELEMENT refresh (setvar)*>
<!ATTLIST refresh
%coreattrs;
>
<!ELEMENT noop EMPTY>
<!ATTLIST noop
%coreattrs;
>
<!--================ postfield ================-->
<!ELEMENT postfield EMPTY>
<!ATTLIST postfield
name %vdata; #REQUIRED
value %vdata; #REQUIRED
%coreattrs;
>
<!--================ variables ================-->
<!ELEMENT setvar EMPTY>
<!ATTLIST setvar
name %vdata; #REQUIRED
value %vdata; #REQUIRED
%coreattrs;
>
<!--================ Card Fields ================-->
<!ELEMENT select (optgroup|option)+>
<!ATTLIST select
title %vdata; #IMPLIED
name NMTOKEN #IMPLIED
value %vdata; #IMPLIED
iname NMTOKEN #IMPLIED
ivalue %vdata; #IMPLIED
multiple %boolean; "false"
tabindex %number; #IMPLIED
xml:lang NMTOKEN #IMPLIED
%coreattrs;
>
<!ELEMENT optgroup (optgroup|option)+ >
<!ATTLIST optgroup
title %vdata; #IMPLIED
xml:lang NMTOKEN #IMPLIED
%coreattrs;
>
<!ELEMENT option (#PCDATA | onevent)*>
<!ATTLIST option
value %vdata; #IMPLIED
title %vdata; #IMPLIED
onpick %HREF; #IMPLIED
xml:lang NMTOKEN #IMPLIED
%coreattrs;
>
<!ELEMENT input EMPTY>
<!ATTLIST input
name NMTOKEN #REQUIRED
type (text|password) "text"
value %vdata; #IMPLIED
format CDATA #IMPLIED
emptyok %boolean; "false"
size %number; #IMPLIED
maxlength %number; #IMPLIED
tabindex %number; #IMPLIED
title %vdata; #IMPLIED
accesskey %vdata; #IMPLIED
xml:lang NMTOKEN #IMPLIED
%coreattrs;
>
<!ELEMENT fieldset (%fields; | do)* >
<!ATTLIST fieldset
title %vdata; #IMPLIED
xml:lang NMTOKEN #IMPLIED
%coreattrs;
>
<!ELEMENT timer EMPTY>
<!ATTLIST timer
name NMTOKEN #IMPLIED
value %vdata; #REQUIRED
%coreattrs;
>
<!--================ Images ================-->
<!ENTITY % IAlign "(top|middle|bottom)" >
<!ELEMENT img EMPTY>
<!ATTLIST img
alt %vdata; #REQUIRED
src %HREF; #REQUIRED
localsrc %vdata; #IMPLIED
vspace %length; "0"
hspace %length; "0"
align %IAlign; "bottom"
height %length; #IMPLIED
width %length; #IMPLIED
xml:lang NMTOKEN #IMPLIED
%coreattrs;
>
<!--================ Anchor ================-->
<!ELEMENT anchor ( #PCDATA | br | img | go | prev | refresh )*>
<!ATTLIST anchor
title %vdata; #IMPLIED
accesskey %vdata; #IMPLIED
xml:lang NMTOKEN #IMPLIED
%coreattrs;
>
<!ELEMENT a ( #PCDATA | br | img )*>
<!ATTLIST a
href %HREF; #REQUIRED
title %vdata; #IMPLIED
accesskey %vdata; #IMPLIED
xml:lang NMTOKEN #IMPLIED
%coreattrs;
>
<!--================ Tables ================-->
<!ELEMENT table (tr)+>
<!ATTLIST table
title %vdata; #IMPLIED
align CDATA #IMPLIED
columns %number; #REQUIRED
xml:lang NMTOKEN #IMPLIED
%coreattrs;
>
<!ELEMENT tr (td)+>
<!ATTLIST tr
%coreattrs;
>
<!ELEMENT td ( %text; | %layout; | img | anchor |a )*>
<!ATTLIST td
xml:lang NMTOKEN #IMPLIED
%coreattrs;
>
<!--============ Text layout and line breaks =============-->
<!ELEMENT em (%flow;)*>
<!ATTLIST em
xml:lang NMTOKEN #IMPLIED
%coreattrs;
>
<!ELEMENT strong (%flow;)*>
<!ATTLIST strong
xml:lang NMTOKEN #IMPLIED
%coreattrs;
>
<!ELEMENT b (%flow;)*>
<!ATTLIST b
xml:lang NMTOKEN #IMPLIED
%coreattrs;
>
<!ELEMENT i (%flow;)*>
<!ATTLIST i
xml:lang NMTOKEN #IMPLIED
%coreattrs;
>
<!ELEMENT u (%flow;)*>
<!ATTLIST u
xml:lang NMTOKEN #IMPLIED
%coreattrs;
>
<!ELEMENT big (%flow;)*>
<!ATTLIST big
xml:lang NMTOKEN #IMPLIED
%coreattrs;
>
<!ELEMENT small (%flow;)*>
<!ATTLIST small
xml:lang NMTOKEN #IMPLIED
%coreattrs;
>
<!ENTITY % TAlign "(left|right|center)">
<!ENTITY % WrapMode "(wrap|nowrap)" >
<!ELEMENT p (%fields; | do)*>
<!ATTLIST p
align %TAlign; "left"
mode %WrapMode; #IMPLIED
xml:lang NMTOKEN #IMPLIED
%coreattrs;
>
<!ELEMENT br EMPTY>
<!ATTLIST br
%coreattrs;
>
<!ELEMENT pre (#PCDATA | a | br | i | b | em | strong |
input | select )*>
<!ATTLIST pre
xml:space CDATA #FIXED "preserve"
%coreattrs;
>
<!ENTITY quot """> <!-- quotation mark -->
<!ENTITY amp "&"> <!-- ampersand -->
<!ENTITY apos "'"> <!-- apostrophe -->
<!ENTITY lt "<"> <!-- less than -->
<!ENTITY gt ">"> <!-- greater than -->
<!ENTITY nbsp " "> <!-- non-breaking space -->
<!ENTITY shy ""> <!-- soft hyphen (discretionary hyphen) -->
WML2 is a language, which extends the syntax and semantics of the followings:
XHTML Basic [ XHTMLBasic ]
CSS Mobile Profile [ CSSMP ]
Unique semantics of WML1.0 [ WML1.0 ]
WML2 is optimised for specifying presentation and user interaction on limited capability devices such as mobile phones and other wireless mobile terminals.
This tutorial gives detail of the Wireless Markup Language (WML) Version 2. This tutorial refers to version 2.0 of WML as WML2.
The XHTML Basic defined by the W3C is a proper subset of XHTML, which is a reformulation of HTML in XML.
There are five major goals for WML2:
Backward compatibility: WML2 application should be running on old devices as well.
Backward compatibility: WML2 application should be running on old devices as well.
Convergence with existing and evolving Internet standards: XHTML Basic [XHTMLBasic] and CSS Mobile Profile [CSSMP]
Convergence with existing and evolving Internet standards: XHTML Basic [XHTMLBasic] and CSS Mobile Profile [CSSMP]
Optimisation of access from small, limited devices: WAP-enabled devices are generally small and battery operated and they have relatively limited memory and CPU power. So WML2 should be optimized enough to run on these devices.
Optimisation of access from small, limited devices: WAP-enabled devices are generally small and battery operated and they have relatively limited memory and CPU power. So WML2 should be optimized enough to run on these devices.
Allowance for the creation of distinct user interfaces: WAP enables the creation of Man Machine Interfaces (MMIs) with maximum flexibility and ability for a vendor to enhance the user experience.
Allowance for the creation of distinct user interfaces: WAP enables the creation of Man Machine Interfaces (MMIs) with maximum flexibility and ability for a vendor to enhance the user experience.
Internationalisation of the architecture: WAP targets common character codes for international use. This includes international symbols and pictogram sets for end users, and local-use character encoding for content developers.
Internationalisation of the architecture: WAP targets common character codes for international use. This includes international symbols and pictogram sets for end users, and local-use character encoding for content developers.
The WML2 vision is to create a language that extends the syntax and semantics of XHTML Basic and CSS Mobile profile with the unique semantics of WML1. The user should not be aware of how WML1 compatibility is achieved.
WML2 is a new language with the following components:
This element group is for W3C convergence. For some of the elements, WML extension attributes are added in
order to achieve WML1 functionality.
a abbr acronym address base blockquote br caption cite code dd dfn div dl dt em form h1 h2 h3 h4 h5 h6 head kbd label li link object ol param pre q samp span strong table td th title tr ul var
body html img input meta option p select style textarea
This element group consists of select elements from those modules of XHTML not included in XHTML Basic. Most elements are included for WML1 compatibility. One element is included as an enhancement that fits limited handset capabilities.
b big i small (from Presentation Module) u (from Legacy Module) fieldset optgroup (from Forms Module)
hr
Some elements are brought from WML1, because the equivalent capabilities are not provided in XHTML Basic or XHTML Modularization. One element is included for enhancement of WML1 capabilities.
wml:access wml:anchor wml:card wml:do wml:getvar wml:go wml:noop wml:onevent wml:postfield wml:prev wml:refresh wml:setvar wml:timer
wml:widget
The following elements in the Structure Module are used to specify the structure of a WML2 document:
body
html
wml:card
head
title
The wml:newcontext attribute specifies whether the browser context is initialised to a well-defined state when the
document is loaded. If the wml:newcontext attribute value is "true", the browser MUST reinitialise the browser
context upon navigation to this card.
The xmlns:wml attribute refers to the WML namespace for example : http://www.wapforum.org/2001/wml.
The wml:use-xml-fragments attribute is used to specify how a fragment identifier is interpreted by the user agent. For details of use of wml:use-xml-fragments in the go task and the prev task.
The wml:card element specifies a fragment of the document body. Multiple wml:card elements may appear in a single document. Each wml:card element represents an individual presentation and/or interaction with the user.
If the wml:card element's newcontext attribute value is "true", the browser MUST reinitialise the browser context upon navigation to this card.
This element keeps header information of the document like meta element and style sheet etc.
This element is used to put a document title
NOTE: WML developers can use the XHTML document style, that is, body structure, or they can use a collection of cards. When the body structure is used, a document is constructed using a body element. The body element contains the content of the document. When a collection of cards is used, a document is constructed using one or more wml:card elements.
The following tasks are defined in WML2.0. These tasks are very similar to WML1.0
The go task
The prev task
The noop task
The refresh task
The following event types are defined in WML2:
Intrinsic event: An event generated by the user agent and includes the following events similar to WML1.0
ontimer
onenterforward
onenterbackward
onpick
Intrinsic event: An event generated by the user agent and includes the following events similar to WML1.0
ontimer
onenterforward
onenterbackward
onpick
Extrinsic event: An event sent to the user agent by some external agent. The WML 2 specification does not specify any classes of extrinsic events. One example of a WML extrinsic event class may be WTA events
Extrinsic event: An event sent to the user agent by some external agent. The WML 2 specification does not specify any classes of extrinsic events. One example of a WML extrinsic event class may be WTA events
WML2 documents are identified by the MIME media type "application/wml+xml". The type "application/xhtml+xml" can be used to identify documents from any of the XHTML-based markup languages, including XHTML Basic.
The DOCTYPE declaration may include the XHTML Basic Formal Public Identifier and may also include the URI of the XHTML Basic DTD as specified below:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.0//EN"
"http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd">
Style sheets can be used to style WML2 documents. Style information can be associated with a document in 3 ways:
An external style sheet can be associated with a document using a special XML processing instruction or the link
element. The use of the XML processing instruction can also be used.
In the following example, the XML processing instruction is used to associate the external style sheet "mobile.css".
<?xml-stylesheet href="mobile.css"
media="handheld" type="text/css" ?>
In the following example, the link element is used to associate the external style sheet "mystyle.css":
<html>
<head>
<link href="mystyle.css" type="text/css" rel="stylesheet"/>
...
</head>
...
</html>
Style information can be located within the document using the style element. This element, like link, must be located in the document header.
The following shows an example of an internal style sheet:
<html>
<head>
<style type="text/css">
p { text-align: center; }
</style>
...
</head>
...
</html>
You can specify style information for a single element using the style attribute. This is called inline style.
In the following example, inline styling information is applied to a specific paragraph element:
<p style="text-align: center">...</p>
Here is a sample style sheet for WML 2.0:
body, card, div, p, center, hr, h1, h2, h3, h4, h5, h6,
address, blockquote, pre, ol, ul, dl, dt, dd,
form, fieldset, object { display: block }
li { display: list-item }
head { display: none }
table { display: table }
tr { display: table-row }
td, th { display: table-cell }
caption { display: table-caption }
th { font-weight: bolder; text-align: center }
caption { text-align: center }
h1, h2, h3, h4, h5, h6, b, strong { font-weight: bolder }
i, cite, em, var,address { font-style: italic }
pre, code, kbd, pre { white-space: pre }
big { font-size: larger}
small { font-size: smaller}
hr { border: 1px inset }
ol { list-style-type: decimal }
u { text-decoration: underline }
Here is link to a complete list of all the WML2 elements. Most of the elements are available in XHTML specification except few elements starting with WML: These elements are specific to WML.
All the elements having same meaning here what they have in XHTML specification.
We can conclude that if you know XHTML and WML1.0 then you have nothing to do learn WML2.0
If you are interested for further reading then here you can find complete specification for WAP2.0 and WML2.0
WML entities are to represent symbols that either can't easily be typed in or that have a special meaning in WML.
For example, if you put a < character into your text normally, the browser thinks it's the start of a tag; the browser then complains when it can't find the matching > character to end the tag.
Following table displays the three forms of entities in WML. Named entities are something you may be familiar with from HTML: they look like & or <, and they represent a single named character via a mnemonic name. Entities can also be entered in one of two numeric forms (decimal or hexadecimal), allowing you to enter any Unicode character into your WML.
Note that all entities start with an ampersand ( &) and end with a semicolon ( ;). This semicolon is very important: some web pages forget this and cause problems for browsers that want correct HTML. WAP browsers also are likely to be stricter about errors like these.
Following table lists all the valid WML elements. Click over the links to know more detail of that element
Instead of installing an entire WAP SDK, you can install a WML emulator. An emulator simply lets you view the contents of your WML files as they would be seen on the screen of a WAP-enabled device.
While the emulators do a great job, they are not perfect. Try a few different ones, and you will quickly decide which you like the most. When the time comes to develop a real (commercial) WAP site, you will need to do a lot more testing, first with other SDKs/emulators and then with all the WAP-enabled devices you plan to support.
The following lists some of the WAP emulators that are freely available:
Klondike WAP Browser: This is produced by Apache Software. Klondike looks a lot like a Web browser and is therefore very easy to use for beginners. You can access local WML files easily. It also supports drag-anddrop, making local file use very easy.
Klondike WAP Browser: This is produced by Apache Software. Klondike looks a lot like a Web browser and is therefore very easy to use for beginners. You can access local WML files easily. It also supports drag-anddrop, making local file use very easy.
Yospace: This is produced by Yospace. WAP developers can use the desktop edition of the emulator to preview WAP applications from their desktop, safe with the knowledge that the emulator provides a reasonably faithful reproduction of the actual handset products.
Yospace: This is produced by Yospace. WAP developers can use the desktop edition of the emulator to preview WAP applications from their desktop, safe with the knowledge that the emulator provides a reasonably faithful reproduction of the actual handset products.
Ericsson R380 Emulator: This is produced by Ericsson. The R380 WAP emulator is intended to be used to test WML applications developed for the WAP browser in the Ericsson R380. The emulator contains the WAP browser and WAP settings functionality that can be found in the R380.
Ericsson R380 Emulator: This is produced by Ericsson. The R380 WAP emulator is intended to be used to test WML applications developed for the WAP browser in the Ericsson R380. The emulator contains the WAP browser and WAP settings functionality that can be found in the R380.
WinWAP : This is produced by Slob-Trot Software. WinWAP is a
WML browser that works on any computer with 32-bit Windows installed. You can browse WML files locally from your hard drive or the
Internet with HTTP (as with your normal Web browser).
WinWAP : This is produced by Slob-Trot Software. WinWAP is a
WML browser that works on any computer with 32-bit Windows installed. You can browse WML files locally from your hard drive or the
Internet with HTTP (as with your normal Web browser).
Nokia WAP simulator - This is produced by Nokia and fully loaded with almost all functionalities. Try this one.
Nokia WAP simulator - This is produced by Nokia and fully loaded with almost all functionalities. Try this one.
Copy and paste WML content in the following box and then click Validate WML to see the result at the bottom of this page:
Type your WML page URL and then click Validate WML to see the result at the bottom of this page:
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2117,
"s": 1939,
"text": "The topmost layer in the WAP (Wireless Application Protocol) architecture is made up of WAE (Wireless Application Environment), which consists of WML and WML scripting language."
},
{
"code": null,
"e": 2157,
"s": 2117,
"text": "WML stands for Wireless Markup Language"
},
{
"code": null,
"e": 2197,
"s": 2157,
"text": "WML stands for Wireless Markup Language"
},
{
"code": null,
"e": 2275,
"s": 2197,
"text": "WML is an application of XML, which is defined in a document-type definition."
},
{
"code": null,
"e": 2353,
"s": 2275,
"text": "WML is an application of XML, which is defined in a document-type definition."
},
{
"code": null,
"e": 2428,
"s": 2353,
"text": "WML is based on HDML and is modified so that it can be compared with HTML."
},
{
"code": null,
"e": 2503,
"s": 2428,
"text": "WML is based on HDML and is modified so that it can be compared with HTML."
},
{
"code": null,
"e": 2577,
"s": 2503,
"text": "WML takes care of the small screen and the low bandwidth of transmission."
},
{
"code": null,
"e": 2651,
"s": 2577,
"text": "WML takes care of the small screen and the low bandwidth of transmission."
},
{
"code": null,
"e": 2712,
"s": 2651,
"text": "WML is the markup language defined in the WAP specification."
},
{
"code": null,
"e": 2773,
"s": 2712,
"text": "WML is the markup language defined in the WAP specification."
},
{
"code": null,
"e": 2840,
"s": 2773,
"text": "WAP sites are written in WML, while web sites are written in HTML."
},
{
"code": null,
"e": 2907,
"s": 2840,
"text": "WAP sites are written in WML, while web sites are written in HTML."
},
{
"code": null,
"e": 2996,
"s": 2907,
"text": "WML is very similar to HTML. Both of them use tags and are written in plain text format."
},
{
"code": null,
"e": 3085,
"s": 2996,
"text": "WML is very similar to HTML. Both of them use tags and are written in plain text format."
},
{
"code": null,
"e": 3166,
"s": 3085,
"text": "WML files have the extension \".wml\". The MIME type of WML is \"text/vnd.wap.wml\"."
},
{
"code": null,
"e": 3247,
"s": 3166,
"text": "WML files have the extension \".wml\". The MIME type of WML is \"text/vnd.wap.wml\"."
},
{
"code": null,
"e": 3337,
"s": 3247,
"text": "WML supports client-side scripting. The scripting language supported is called WMLScript."
},
{
"code": null,
"e": 3427,
"s": 3337,
"text": "WML supports client-side scripting. The scripting language supported is called WMLScript."
},
{
"code": null,
"e": 3693,
"s": 3427,
"text": "WAP Forum has released a latest version WAP 2.0. The markup language defined in WAP 2.0 is XHTML Mobile Profile (MP). The WML MP is a subset of the XHTML. A style sheet called WCSS (WAP CSS) has been introduced alongwith XHTML MP. The WCSS is a subset of the CSS2."
},
{
"code": null,
"e": 3886,
"s": 3693,
"text": "Most of the new mobile phone models released are WAP 2.0-enabled. Because WAP 2.0 is backward compatible to WAP 1.x, WAP 2.0-enabled mobile devices can display both XHTML MP and WML documents."
},
{
"code": null,
"e": 4186,
"s": 3886,
"text": "WML 1.x is an earlier technology. However, that does not mean it is of no use, since a lot of wireless devices that only supports WML 1.x are still being used. Latest version of WML is 2.0 and it is created for backward compatibility purposes. So WAP site developers need not to worry about WML 2.0."
},
{
"code": null,
"e": 4370,
"s": 4186,
"text": "A main difference between HTML and WML is that the basic unit of navigation in HTML is a page, while that in WML is a card. A WML file can contain multiple cards and they form a deck."
},
{
"code": null,
"e": 4683,
"s": 4370,
"text": "When a WML page is accessed from a mobile phone, all the cards in the page are downloaded from the WAP server. So if the user goes to another card of the same deck, the mobile browser does not have to send any requests to the server since the file that contains the deck is already stored in the wireless device."
},
{
"code": null,
"e": 4778,
"s": 4683,
"text": "You can put links, text, images, input fields, option boxes and many other elements in a card."
},
{
"code": null,
"e": 4829,
"s": 4778,
"text": "Following is the basic structure of a WML program:"
},
{
"code": null,
"e": 5136,
"s": 4829,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card id=\"one\" title=\"First Card\">\n<p>\nThis is the first card in the deck\n</p>\n</card>\n\n<card id=\"two\" title=\"Second Card\">\n<p>\nThs is the second card in the deck\n</p>\n</card>\n\n</wml>"
},
{
"code": null,
"e": 5321,
"s": 5136,
"text": "The first line of this text says that this is an XML document and the version is 1.0. The second line selects\nthe document type and gives the URL of the document type definition (DTD)."
},
{
"code": null,
"e": 5468,
"s": 5321,
"text": "One WML deck (i.e. page ) can have one or more cards as shown above. We will see complete details on WML document structure in subsequent chapter."
},
{
"code": null,
"e": 5629,
"s": 5468,
"text": "Unlike HTML 4.01 Transitional, text cannot be enclosed directly in the <card>...</card> tag pair. So you need to put a content inside <p>...</p> as shown above."
},
{
"code": null,
"e": 5784,
"s": 5629,
"text": "Wireless devices are limited by the size of their displays and keypads. It's therefore very important to take this into account when designing a WAP Site."
},
{
"code": null,
"e": 6126,
"s": 5784,
"text": "While designing a WAP site you must ensure that you keep things simple and easy to use. You should always keep in mind that there are no standard microbrowser behaviors and that the data link may be relatively slow, at around 10Kbps. However, with GPRS, EDGE, and UMTS, this may not be the case for long, depending on where you are located."
},
{
"code": null,
"e": 6219,
"s": 6126,
"text": "The following are general design tips that you should keep in mind when designing a service:"
},
{
"code": null,
"e": 6269,
"s": 6219,
"text": "Keep the WML decks and images to less than 1.5KB."
},
{
"code": null,
"e": 6319,
"s": 6269,
"text": "Keep the WML decks and images to less than 1.5KB."
},
{
"code": null,
"e": 6459,
"s": 6319,
"text": "Keep text brief and meaningful, and as far as possible try to precode options to minimize the rather painful experience of user data entry."
},
{
"code": null,
"e": 6599,
"s": 6459,
"text": "Keep text brief and meaningful, and as far as possible try to precode options to minimize the rather painful experience of user data entry."
},
{
"code": null,
"e": 6635,
"s": 6599,
"text": "Keep URLs brief and easy to recall."
},
{
"code": null,
"e": 6671,
"s": 6635,
"text": "Keep URLs brief and easy to recall."
},
{
"code": null,
"e": 6761,
"s": 6671,
"text": "Minimize menu levels to prevent users from getting lost and the system from slowing down."
},
{
"code": null,
"e": 6851,
"s": 6761,
"text": "Minimize menu levels to prevent users from getting lost and the system from slowing down."
},
{
"code": null,
"e": 6941,
"s": 6851,
"text": "Use standard layout tags such as <big> and <b>, and logically structure your information."
},
{
"code": null,
"e": 7031,
"s": 6941,
"text": "Use standard layout tags such as <big> and <b>, and logically structure your information."
},
{
"code": null,
"e": 7121,
"s": 7031,
"text": "Don't go overboard with the use of graphics, as many target devices may not support them."
},
{
"code": null,
"e": 7211,
"s": 7121,
"text": "Don't go overboard with the use of graphics, as many target devices may not support them."
},
{
"code": null,
"e": 7269,
"s": 7211,
"text": "To develop WAP applications, you will need the following:"
},
{
"code": null,
"e": 7376,
"s": 7269,
"text": "A WAP enabled Web Server: You can enable your Apache or Microsoft IIS to serve all the WAP client request."
},
{
"code": null,
"e": 7483,
"s": 7376,
"text": "A WAP enabled Web Server: You can enable your Apache or Microsoft IIS to serve all the WAP client request."
},
{
"code": null,
"e": 7557,
"s": 7483,
"text": "A WAP Gateway Simulator: This is required to interact to your WAP server."
},
{
"code": null,
"e": 7631,
"s": 7557,
"text": "A WAP Gateway Simulator: This is required to interact to your WAP server."
},
{
"code": null,
"e": 7725,
"s": 7631,
"text": "A WAP Phone Simulator: This is required to test your WAP Pages and to show all the WAP pages."
},
{
"code": null,
"e": 7819,
"s": 7725,
"text": "A WAP Phone Simulator: This is required to test your WAP Pages and to show all the WAP pages."
},
{
"code": null,
"e": 7879,
"s": 7819,
"text": "You can write your WAP pages using the following languages:"
},
{
"code": null,
"e": 7937,
"s": 7879,
"text": "Wireless Markup Language(WML) to develop WAP application."
},
{
"code": null,
"e": 7997,
"s": 7937,
"text": "WML Script to enhance the functionality of WAP application."
},
{
"code": null,
"e": 8277,
"s": 7997,
"text": "In normal web applications, MIME type is set to text/html, designating normal HTML code. Images, on the other hand, could be specified as image/gif or image/jpeg, for instance. With this content type specification, the web browser knows the data type that the web server returns."
},
{
"code": null,
"e": 8426,
"s": 8277,
"text": "To make your Apache WAP compatible, you have nothing to do very much. You simply need to add support for the MIME types and extensions listed below."
},
{
"code": null,
"e": 8573,
"s": 8426,
"text": "Assuming you have Apache Web server installed on your machine. So now we will tell you how to enable WAP functionality in your Apache web server."
},
{
"code": null,
"e": 8709,
"s": 8573,
"text": "So locate Apache's file httpd.conf which is usually in /etc/httpd/conf, and add the following lines to the file and restart the server:"
},
{
"code": null,
"e": 8894,
"s": 8709,
"text": "AddType text/vnd.wap.wml .wml\nAddType text/vnd.wap.wmlscript .wmls\nAddType application/vnd.wap.wmlc .wmlc\nAddType application/vnd.wap.wmlscriptc .wmlsc\nAddType image/vnd.wap.wbmp .wbmp"
},
{
"code": null,
"e": 9041,
"s": 8894,
"text": "In dynamic applications, the MIME type must be set on the fly, whereas in static WAP applications the web server must be configured appropriately."
},
{
"code": null,
"e": 9136,
"s": 9041,
"text": "To configure a Microsoft IIS server to deliver WAP content, you need to perform the following:"
},
{
"code": null,
"e": 9749,
"s": 9136,
"text": "\nOpen the Internet Service Manager console and expand the tree to view your Web site entry. You can add the WAP MIME types to a whole server or individual directories.\nOpen the Properties dialog box by right-clicking the appropriate server or directory, then choose Properties from the menu.\nFrom the Properties dialog, choose the HTTP Headers tab, then select the File Types button at the bottom right.\nFor each MIME type listed earlier in the above table, supply the extension with or without the dot (it will be automatically added for you), then click OK in the Properties dialog box to accept your changes.\n"
},
{
"code": null,
"e": 9916,
"s": 9749,
"text": "Open the Internet Service Manager console and expand the tree to view your Web site entry. You can add the WAP MIME types to a whole server or individual directories."
},
{
"code": null,
"e": 10040,
"s": 9916,
"text": "Open the Properties dialog box by right-clicking the appropriate server or directory, then choose Properties from the menu."
},
{
"code": null,
"e": 10152,
"s": 10040,
"text": "From the Properties dialog, choose the HTTP Headers tab, then select the File Types button at the bottom right."
},
{
"code": null,
"e": 10360,
"s": 10152,
"text": "For each MIME type listed earlier in the above table, supply the extension with or without the dot (it will be automatically added for you), then click OK in the Properties dialog box to accept your changes."
},
{
"code": null,
"e": 10544,
"s": 10360,
"text": "There are many WAP Gateway Simulator available on the Internet so download any of them and install on your PC. You would need to run this gateway before starting WAP Mobile simulator."
},
{
"code": null,
"e": 10718,
"s": 10544,
"text": "WAP Gateway will take your request and will pass it to the Web Server and whatever response will be received from the Web server that will be passed to the Mobile Simulator."
},
{
"code": null,
"e": 10759,
"s": 10718,
"text": "You can download it from Nokia web site:"
},
{
"code": null,
"e": 10828,
"s": 10759,
"text": "Nokia WAP Gateway simulator - Download Nokia WAP Gateway simulator."
},
{
"code": null,
"e": 10897,
"s": 10828,
"text": "Nokia WAP Gateway simulator - Download Nokia WAP Gateway simulator."
},
{
"code": null,
"e": 11081,
"s": 10897,
"text": "There are many WAP Simulator available on the Internet so download any of them and install on your PC which you will use as a WAP client. Here are popular links to download simulator:"
},
{
"code": null,
"e": 11134,
"s": 11081,
"text": "Nokia WAP simulator - Download Nokia WAP simulator."
},
{
"code": null,
"e": 11187,
"s": 11134,
"text": "Nokia WAP simulator - Download Nokia WAP simulator."
},
{
"code": null,
"e": 11260,
"s": 11187,
"text": "WinWAP simulator - Download WinWAP browser from their official website."
},
{
"code": null,
"e": 11333,
"s": 11260,
"text": "WinWAP simulator - Download WinWAP browser from their official website."
},
{
"code": null,
"e": 11501,
"s": 11333,
"text": "NOTE: If you have WAP enabled phone then you do not need to install this simulator. But while doing development it is more convenient and economic to use a simulator."
},
{
"code": null,
"e": 11609,
"s": 11501,
"text": "I am giving this section just for your reference, if you are not interested then you can skip this section."
},
{
"code": null,
"e": 11790,
"s": 11609,
"text": "The figure below shows the WAP programming model. Note the similarities with the Internet model. Without the WAP Gateway/Proxy the two models would have been practically identical."
},
{
"code": null,
"e": 12069,
"s": 11790,
"text": "WAP Gateway/Proxy is the entity that connects the wireless domain with the Internet. You should make a note that the request that is sent from the wireless client to the WAP Gateway/Proxy uses the Wireless Session Protocol (WSP). In its essence, WSP is a binary version of HTTP."
},
{
"code": null,
"e": 12359,
"s": 12069,
"text": "A markup language - the Wireless Markup Language (WML) has been adapted to develop optimized WAP applications. In order to save valuable bandwidth in the wireless network, WML can be encoded into a compact binary format. Encoding WML is one of the tasks performed by the WAP Gateway/Proxy."
},
{
"code": null,
"e": 12409,
"s": 12359,
"text": "When it comes to actual use, WAP works like this:"
},
{
"code": null,
"e": 13366,
"s": 12409,
"text": "\nThe user selects an option on their mobile device that has a URL with Wireless Markup language (WML) content assigned to it.\nThe phone sends the URL request via the phone network to a WAP gateway, using the binary encoded WAP protocol.\nThe gateway translates this WAP request into a conventional HTTP request for the specified URL, and sends it on to the Internet.\nThe appropriate Web server picks up the HTTP request.\nThe server processes the request, just as it would any other request. If the URL refers to a static WML file, the server delivers it. If a CGI script is requested, it is processed and the content returned as usual.\nThe Web server adds the HTTP header to the WML content and returns it to the gateway.\nThe WAP gateway compiles the WML into binary form.\nThe gateway then sends the WML response back to the phone.\nThe phone receives the WML via the WAP protocol.\nThe micro-browser processes the WML and displays the content on the screen.\n"
},
{
"code": null,
"e": 13491,
"s": 13366,
"text": "The user selects an option on their mobile device that has a URL with Wireless Markup language (WML) content assigned to it."
},
{
"code": null,
"e": 13616,
"s": 13491,
"text": "The user selects an option on their mobile device that has a URL with Wireless Markup language (WML) content assigned to it."
},
{
"code": null,
"e": 13727,
"s": 13616,
"text": "The phone sends the URL request via the phone network to a WAP gateway, using the binary encoded WAP protocol."
},
{
"code": null,
"e": 13838,
"s": 13727,
"text": "The phone sends the URL request via the phone network to a WAP gateway, using the binary encoded WAP protocol."
},
{
"code": null,
"e": 13967,
"s": 13838,
"text": "The gateway translates this WAP request into a conventional HTTP request for the specified URL, and sends it on to the Internet."
},
{
"code": null,
"e": 14096,
"s": 13967,
"text": "The gateway translates this WAP request into a conventional HTTP request for the specified URL, and sends it on to the Internet."
},
{
"code": null,
"e": 14150,
"s": 14096,
"text": "The appropriate Web server picks up the HTTP request."
},
{
"code": null,
"e": 14204,
"s": 14150,
"text": "The appropriate Web server picks up the HTTP request."
},
{
"code": null,
"e": 14419,
"s": 14204,
"text": "The server processes the request, just as it would any other request. If the URL refers to a static WML file, the server delivers it. If a CGI script is requested, it is processed and the content returned as usual."
},
{
"code": null,
"e": 14634,
"s": 14419,
"text": "The server processes the request, just as it would any other request. If the URL refers to a static WML file, the server delivers it. If a CGI script is requested, it is processed and the content returned as usual."
},
{
"code": null,
"e": 14720,
"s": 14634,
"text": "The Web server adds the HTTP header to the WML content and returns it to the gateway."
},
{
"code": null,
"e": 14806,
"s": 14720,
"text": "The Web server adds the HTTP header to the WML content and returns it to the gateway."
},
{
"code": null,
"e": 14857,
"s": 14806,
"text": "The WAP gateway compiles the WML into binary form."
},
{
"code": null,
"e": 14908,
"s": 14857,
"text": "The WAP gateway compiles the WML into binary form."
},
{
"code": null,
"e": 14967,
"s": 14908,
"text": "The gateway then sends the WML response back to the phone."
},
{
"code": null,
"e": 15026,
"s": 14967,
"text": "The gateway then sends the WML response back to the phone."
},
{
"code": null,
"e": 15075,
"s": 15026,
"text": "The phone receives the WML via the WAP protocol."
},
{
"code": null,
"e": 15124,
"s": 15075,
"text": "The phone receives the WML via the WAP protocol."
},
{
"code": null,
"e": 15200,
"s": 15124,
"text": "The micro-browser processes the WML and displays the content on the screen."
},
{
"code": null,
"e": 15276,
"s": 15200,
"text": "The micro-browser processes the WML and displays the content on the screen."
},
{
"code": null,
"e": 15390,
"s": 15276,
"text": "A WML program is typically divided into two parts: the document prolog and the body. Consider the following code:"
},
{
"code": null,
"e": 15441,
"s": 15390,
"text": "Following is the basic structure of a WML program:"
},
{
"code": null,
"e": 15749,
"s": 15441,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card id=\"one\" title=\"First Card\">\n<p>\nThis is the first card in the deck\n\n</p>\n</card>\n\n<card id=\"two\" title=\"Second Card\">\n<p>\nThs is the second card in the deck\n</p>\n</card>\n\n</wml>"
},
{
"code": null,
"e": 16122,
"s": 15749,
"text": "The first line of this text says that this is an XML document and the version is 1.0. The second line selects\nthe document type and gives the URL of the document type definition (DTD). The DTD referenced is defined in WAP 1.2, but this header changes with the versions of the WML. The header must be copied exactly so that the tool kits automatically generate this prolog."
},
{
"code": null,
"e": 16261,
"s": 16122,
"text": "The prolog components are not WML elements and they should not be closed, i.e. you should not give them an end tag or finish them with />."
},
{
"code": null,
"e": 16386,
"s": 16261,
"text": "The body is enclosed within a <wml> </wml> tag pair. The body of a WML document can consist of one or more of the following:"
},
{
"code": null,
"e": 16391,
"s": 16386,
"text": "Deck"
},
{
"code": null,
"e": 16396,
"s": 16391,
"text": "Deck"
},
{
"code": null,
"e": 16401,
"s": 16396,
"text": "Card"
},
{
"code": null,
"e": 16406,
"s": 16401,
"text": "Card"
},
{
"code": null,
"e": 16426,
"s": 16406,
"text": "Content to be shown"
},
{
"code": null,
"e": 16446,
"s": 16426,
"text": "Content to be shown"
},
{
"code": null,
"e": 16470,
"s": 16446,
"text": "Navigation instructions"
},
{
"code": null,
"e": 16494,
"s": 16470,
"text": "Navigation instructions"
},
{
"code": null,
"e": 16655,
"s": 16494,
"text": "Unlike HTML 4.01 Transitional, text cannot be enclosed directly in the <card>...</card> tag pair. So you need to put a content inside <p>...</p> as shown above."
},
{
"code": null,
"e": 16783,
"s": 16655,
"text": "Put above code in a file called test.wml file, and put this WML file locally on your hard disk, then view it using an emulator."
},
{
"code": null,
"e": 17256,
"s": 16783,
"text": "This is by far the most efficient way of developing and testing WML files. Since your aim is, however, to develop a service that is going to be available to WAP phone users, you should upload your WML files onto a server once you have developed them locally and test them over a real Internet connection. As you start developing more complex WAP services, this is how you will identify and rectify performance problems, which could, if left alone, lose your site visitors."
},
{
"code": null,
"e": 17555,
"s": 17256,
"text": "In uploading the file test.wml to a server, you will be testing your WML emulator to see how it looks and behaves, and checking your Web server to see that it is set up correctly. Now start your emulator and use it to access the URL of test.wml. For example, the URL might look something like this:"
},
{
"code": null,
"e": 17596,
"s": 17555,
"text": "http://websitename.com/wapstuff/test.wml"
},
{
"code": null,
"e": 17683,
"s": 17596,
"text": "NOTE: Before accessing any URL, make sure WAP Gateway Simulator is running on your PC."
},
{
"code": null,
"e": 17969,
"s": 17683,
"text": "When you will download your WAP program, then you will see only first card at your mobile. Following is the output of the above example on Nokia Mobile Browser 4.0. This mobile supports horizontal scrolling. You can see the text off the screen by pressing the \"Left\" or \"Right\" button."
},
{
"code": null,
"e": 18043,
"s": 17969,
"text": "When you press right button, then second card will be visible as follows:"
},
{
"code": null,
"e": 18232,
"s": 18043,
"text": "WML is defined by a set of elements that specify all markup and structural information for a WML\ndeck. Elements are identified by tags, which are each enclosed in a pair of angle brackets."
},
{
"code": null,
"e": 18461,
"s": 18232,
"text": "Unlike HTML, WML strictly adheres to the XML hierarchical structure, and thus, elements must contain a start tag; any content such as text and/or other elements; and an end tag. Elements have one of the following two structures:"
},
{
"code": null,
"e": 18516,
"s": 18461,
"text": "<tag> content </tag> : This form is identical to HTML."
},
{
"code": null,
"e": 18571,
"s": 18516,
"text": "<tag> content </tag> : This form is identical to HTML."
},
{
"code": null,
"e": 18756,
"s": 18571,
"text": "<tag />: This is used when an element cannot contain visible content or is empty, such as a line break. WML document's prolog part does not have any element which has closing element."
},
{
"code": null,
"e": 18941,
"s": 18756,
"text": "<tag />: This is used when an element cannot contain visible content or is empty, such as a line break. WML document's prolog part does not have any element which has closing element."
},
{
"code": null,
"e": 19068,
"s": 18941,
"text": "Following table lists the majority of valid elements. A complete detail of all these elements is given in WML Tags Reference."
},
{
"code": null,
"e": 19171,
"s": 19068,
"text": "As with most programming languages, WML also provides a means of placing comment text within the code."
},
{
"code": null,
"e": 19305,
"s": 19171,
"text": "Comments are used by developers as a means of documenting programming decisions within the code to allow for easier code maintenance."
},
{
"code": null,
"e": 19385,
"s": 19305,
"text": "WML comments use the same format as HTML comments and use the following syntax:"
},
{
"code": null,
"e": 19428,
"s": 19385,
"text": "<!-- This will be assumed as a comment -->"
},
{
"code": null,
"e": 19473,
"s": 19428,
"text": "A multiline comment can be given as follows:"
},
{
"code": null,
"e": 19516,
"s": 19473,
"text": "<!-- This is a multi-line\n comment -->"
},
{
"code": null,
"e": 19690,
"s": 19516,
"text": "The WML author can use comments anywhere, and they are not displayed to the user by the user agent. Some emulators may complain if comments are placed before the XML prolog."
},
{
"code": null,
"e": 19811,
"s": 19690,
"text": "Note that comments are not compiled or sent to the user agent, and thus have no effect on the size of the compiled deck."
},
{
"code": null,
"e": 20004,
"s": 19811,
"text": "Because multiple cards can be contained within one deck, some mechanism needs to be in place to hold data as the user traverses from card to card. This mechanism is provided via WML variables."
},
{
"code": null,
"e": 20237,
"s": 20004,
"text": "WML is case sensitive. No case folding is performed when parsing a WML deck. All enumerated attribute values are case sensitive. For example, the following attribute values are all different: id=\"Card1\", id=\"card1\", and id=\"CARD1\"."
},
{
"code": null,
"e": 20331,
"s": 20237,
"text": "Variables can be created and set using several different methods. Following are two examples:"
},
{
"code": null,
"e": 20524,
"s": 20331,
"text": "The <setvar> element is used as a result of the user executing some task. The >setvar> element can be used to set a variable's state within the following elements: <go>, <prev>, and <refresh>."
},
{
"code": null,
"e": 20572,
"s": 20524,
"text": "This element supports the following attributes:"
},
{
"code": null,
"e": 20648,
"s": 20572,
"text": "The following element would create a variable named a with a value of 1000:"
},
{
"code": null,
"e": 20680,
"s": 20648,
"text": "<setvar name=\"a\" value=\"1000\"/>"
},
{
"code": null,
"e": 20860,
"s": 20680,
"text": "Variables are also set through any input element like input,select, option, etc. A variable is automatically created that corresponds with the named attribute of an input element."
},
{
"code": null,
"e": 20928,
"s": 20860,
"text": "For example, the following element would create a variable named b:"
},
{
"code": null,
"e": 21038,
"s": 20928,
"text": "<select name=\"b\">\n<option value=\"value1\">Option 1</option>\n<option value=\"value2\">Option 2</option>\n</select>"
},
{
"code": null,
"e": 21175,
"s": 21038,
"text": "Variable expansion occurs at runtime, in the microbrowser or emulator. This means it can be concatenated with or embedded in other text."
},
{
"code": null,
"e": 21314,
"s": 21175,
"text": "Variables are referenced with a preceding dollar sign, and any single dollar sign in your WML deck is interpreted as a variable reference."
},
{
"code": null,
"e": 21353,
"s": 21314,
"text": "<p> Selected option value is $(b) </p>"
},
{
"code": null,
"e": 21419,
"s": 21353,
"text": "This section will describe basic text formatting elements of WML."
},
{
"code": null,
"e": 21514,
"s": 21419,
"text": "The <br /> element defines a line break and almost all WAP browsers supports a line break tag."
},
{
"code": null,
"e": 21568,
"s": 21514,
"text": "The <br /> element supports the following attributes:"
},
{
"code": null,
"e": 21626,
"s": 21568,
"text": "Following is the example showing usage of <br /> element."
},
{
"code": null,
"e": 21869,
"s": 21626,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card title=\"Line Break Example\">\n<p align=\"center\">\nThis is a <br /> paragraph with a line break.\n</p>\n</card>\n\n</wml>"
},
{
"code": null,
"e": 21909,
"s": 21869,
"text": "This will produce the following result:"
},
{
"code": null,
"e": 22011,
"s": 21909,
"text": "The <p> element defines a paragraph of text and WAP browsers always render a paragraph in a new line."
},
{
"code": null,
"e": 22082,
"s": 22011,
"text": "A <p> element is required to define any text, image or a table in WML."
},
{
"code": null,
"e": 22133,
"s": 22082,
"text": "The <p> element supports the following attributes:"
},
{
"code": null,
"e": 22138,
"s": 22133,
"text": "left"
},
{
"code": null,
"e": 22144,
"s": 22138,
"text": "right"
},
{
"code": null,
"e": 22151,
"s": 22144,
"text": "center"
},
{
"code": null,
"e": 22156,
"s": 22151,
"text": "wrap"
},
{
"code": null,
"e": 22163,
"s": 22156,
"text": "nowrap"
},
{
"code": null,
"e": 22218,
"s": 22163,
"text": "Following is the example showing usage of <p> element."
},
{
"code": null,
"e": 22488,
"s": 22218,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card title=\"Paragraph Example\">\n<p align=\"center\">\nThis is first paragraph\n</p>\n<p align=\"right\">\nThis is second paragraph\n</p>\n</card>\n\n</wml>"
},
{
"code": null,
"e": 22528,
"s": 22488,
"text": "This will produce the following result:"
},
{
"code": null,
"e": 22649,
"s": 22528,
"text": "The <table> element along with <tr> and <td> is used to create a table in WML. WML does not allow the nesting of tables "
},
{
"code": null,
"e": 22710,
"s": 22649,
"text": "A <table> element should be put with-in <p>...</p> elements."
},
{
"code": null,
"e": 22767,
"s": 22710,
"text": "The <table /> element supports the following attributes:"
},
{
"code": null,
"e": 22769,
"s": 22767,
"text": "L"
},
{
"code": null,
"e": 22771,
"s": 22769,
"text": "C"
},
{
"code": null,
"e": 22773,
"s": 22771,
"text": "R"
},
{
"code": null,
"e": 22808,
"s": 22773,
"text": "First table column -- Left-aligned"
},
{
"code": null,
"e": 22843,
"s": 22808,
"text": "First table column -- Left-aligned"
},
{
"code": null,
"e": 22881,
"s": 22843,
"text": "Second table column -- Center-aligned"
},
{
"code": null,
"e": 22919,
"s": 22881,
"text": "Second table column -- Center-aligned"
},
{
"code": null,
"e": 22955,
"s": 22919,
"text": "Third table column -- Right-aligned"
},
{
"code": null,
"e": 22991,
"s": 22955,
"text": "Third table column -- Right-aligned"
},
{
"code": null,
"e": 23052,
"s": 22991,
"text": "Then you should set the value of the align attribute to LCR."
},
{
"code": null,
"e": 23111,
"s": 23052,
"text": "Following is the example showing usage of <table> element."
},
{
"code": null,
"e": 23505,
"s": 23111,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card title=\"WML Tables\">\n<p>\n<table columns=\"3\" align=\"LCR\">\n\t<tr>\n\t <td>Col 1</td>\n\t <td>Col 2</td>\n\t <td>Col 3</td>\n\t</tr>\n\n\t<tr>\n\t <td>A</td>\n\t <td>B</td>\n\t <td>C</td>\n\t</tr>\n\n\t<tr>\n\t <td>D</td>\n\t <td>E</td>\n\t <td>F</td>\n\t</tr>\n</table>\n</p>\n</card>\n\n</wml>"
},
{
"code": null,
"e": 23545,
"s": 23505,
"text": "This will produce the following result:"
},
{
"code": null,
"e": 23704,
"s": 23545,
"text": "The <pre> element is used to specify preformatted text in WML. Preformatted text is text of which the format follows the way it is typed in the WML document. "
},
{
"code": null,
"e": 23827,
"s": 23704,
"text": "This tag preserves all the white spaces enclosed inside this tag. Make sure you are not putting this tag inside <p>...</p>"
},
{
"code": null,
"e": 23876,
"s": 23827,
"text": "The <pre> element supports following attributes:"
},
{
"code": null,
"e": 23933,
"s": 23876,
"text": "Following is the example showing usage of <pre> element."
},
{
"code": null,
"e": 24189,
"s": 23933,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card title=\"Preformatted Text\">\n <pre>\n This is preformatted\n text and will appear\n as it it.\n</pre>\n</card>\n\n</wml>"
},
{
"code": null,
"e": 24229,
"s": 24189,
"text": "This will produce the following result:"
},
{
"code": null,
"e": 24405,
"s": 24229,
"text": "WML does not support <font> element, but there are other WML elements, which you can use to create different font effects like underlined text, bold text and italic text, etc."
},
{
"code": null,
"e": 24450,
"s": 24405,
"text": "These tags are given in the following table:"
},
{
"code": null,
"e": 24499,
"s": 24450,
"text": "These elements support the following attributes:"
},
{
"code": null,
"e": 24557,
"s": 24499,
"text": "Following is the example showing usage of these elements."
},
{
"code": null,
"e": 24939,
"s": 24557,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card title=\"Text Formatting\">\n<p>\n <b>bold text</b><br/>\n <big>big text</big><br/>\n <em>emphasized text</em><br/>\n <i>italic text</i><br/>\n <small>small text</small><br/>\n <strong>strong text</strong><br/>\n <u>underlined text</u>\n</p>\n</card>\n\n</wml>"
},
{
"code": null,
"e": 24979,
"s": 24939,
"text": "This will produce the following result:"
},
{
"code": null,
"e": 25126,
"s": 24979,
"text": "The <img> element is used to include an image in a WAP card. WAP-enabled wireless devices only supported the Wireless Bitmap (WBMP) image format. "
},
{
"code": null,
"e": 25274,
"s": 25126,
"text": "WBMP images can only contain two colors: black and white. The file extension of WBMP is \".wbmp\" and the MIME type of WBMP is \"image/vnd.wap.wbmp\"."
},
{
"code": null,
"e": 25327,
"s": 25274,
"text": "The <img> element supports the following attributes:"
},
{
"code": null,
"e": 25331,
"s": 25327,
"text": "top"
},
{
"code": null,
"e": 25338,
"s": 25331,
"text": "middle"
},
{
"code": null,
"e": 25345,
"s": 25338,
"text": "bottom"
},
{
"code": null,
"e": 25348,
"s": 25345,
"text": "px"
},
{
"code": null,
"e": 25350,
"s": 25348,
"text": "%"
},
{
"code": null,
"e": 25353,
"s": 25350,
"text": "px"
},
{
"code": null,
"e": 25355,
"s": 25353,
"text": "%"
},
{
"code": null,
"e": 25358,
"s": 25355,
"text": "px"
},
{
"code": null,
"e": 25360,
"s": 25358,
"text": "%"
},
{
"code": null,
"e": 25363,
"s": 25360,
"text": "px"
},
{
"code": null,
"e": 25365,
"s": 25363,
"text": "%"
},
{
"code": null,
"e": 25436,
"s": 25365,
"text": "There are free tools available on the Internet to make \".wbmp\" images."
},
{
"code": null,
"e": 25601,
"s": 25436,
"text": "The Nokia Mobile Internet Toolkit (NMIT) comes with a WBMP image editor that you can use. You can convert existing GIF or JPG image files into WBMP file using NMIT."
},
{
"code": null,
"e": 25677,
"s": 25601,
"text": "Another free tool is ImageMagick, which can help you to create WBMP images."
},
{
"code": null,
"e": 25734,
"s": 25677,
"text": "Following is the example showing usage of <img> element."
},
{
"code": null,
"e": 26059,
"s": 25734,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card title=\"WML Images\">\n<p>\nThis is Thumb image\n<img src=\"/images/thumb.wbmp\" alt=\"Thumb Image\"/>\n</p>\n\n<p>\nThis is Heart image\n<img src=\"/images/heart.wbmp\" alt=\"Heart Image\"/>\n</p>\n\n</card>\n\n</wml>"
},
{
"code": null,
"e": 26099,
"s": 26059,
"text": "This will produce the following result:"
},
{
"code": null,
"e": 26220,
"s": 26099,
"text": "The <table> element along with <tr> and <td> is used to create a table in WML. WML does not allow the nesting of tables "
},
{
"code": null,
"e": 26281,
"s": 26220,
"text": "A <table> element should be put with-in <p>...</p> elements."
},
{
"code": null,
"e": 26338,
"s": 26281,
"text": "The <table /> element supports the following attributes:"
},
{
"code": null,
"e": 26340,
"s": 26338,
"text": "L"
},
{
"code": null,
"e": 26342,
"s": 26340,
"text": "C"
},
{
"code": null,
"e": 26344,
"s": 26342,
"text": "R"
},
{
"code": null,
"e": 26379,
"s": 26344,
"text": "First table column -- Left-aligned"
},
{
"code": null,
"e": 26414,
"s": 26379,
"text": "First table column -- Left-aligned"
},
{
"code": null,
"e": 26452,
"s": 26414,
"text": "Second table column -- Center-aligned"
},
{
"code": null,
"e": 26490,
"s": 26452,
"text": "Second table column -- Center-aligned"
},
{
"code": null,
"e": 26526,
"s": 26490,
"text": "Third table column -- Right-aligned"
},
{
"code": null,
"e": 26562,
"s": 26526,
"text": "Third table column -- Right-aligned"
},
{
"code": null,
"e": 26623,
"s": 26562,
"text": "Then you should set the value of the align attribute to LCR."
},
{
"code": null,
"e": 26682,
"s": 26623,
"text": "Following is the example showing usage of <table> element."
},
{
"code": null,
"e": 27076,
"s": 26682,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card title=\"WML Tables\">\n<p>\n<table columns=\"3\" align=\"LCR\">\n\t<tr>\n\t <td>Col 1</td>\n\t <td>Col 2</td>\n\t <td>Col 3</td>\n\t</tr>\n\n\t<tr>\n\t <td>A</td>\n\t <td>B</td>\n\t <td>C</td>\n\t</tr>\n\n\t<tr>\n\t <td>D</td>\n\t <td>E</td>\n\t <td>F</td>\n\t</tr>\n</table>\n</p>\n</card>\n\n</wml>"
},
{
"code": null,
"e": 27116,
"s": 27076,
"text": "This will produce the following result:"
},
{
"code": null,
"e": 27221,
"s": 27116,
"text": "WML provides you an option to link various cards using links and then navigate through different cards."
},
{
"code": null,
"e": 27306,
"s": 27221,
"text": "There are two WML elements, <anchor> and <a>, which can be used to create WML links."
},
{
"code": null,
"e": 27563,
"s": 27306,
"text": "The <anchor>...</anchor> tag pair is used to create an anchor link. It is used together with other WML elements called <go/>, <refresh> or <prev/>. These elements are called task elements and tell WAP browsers what to do when a user selects the anchor link"
},
{
"code": null,
"e": 27653,
"s": 27563,
"text": "You can enclose Text or image along with a task tag inside <anchor>...</anchor> tag pair."
},
{
"code": null,
"e": 27709,
"s": 27653,
"text": "The <anchor> element supports the following attributes:"
},
{
"code": null,
"e": 27769,
"s": 27709,
"text": "Following is the example showing usage of <anchor> element."
},
{
"code": null,
"e": 28052,
"s": 27769,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card title=\"Anchor Element\">\n<p>\n <anchor>\n <go href=\"nextpage.wml\"/>\n </anchor>\n</p>\n<p>\n <anchor>\n <prev/>\n </anchor>\n</p>\n</card>\n\n</wml>"
},
{
"code": null,
"e": 28092,
"s": 28052,
"text": "This will produce the following result:"
},
{
"code": null,
"e": 28204,
"s": 28092,
"text": "The <a>...</a> tag pair can also be used to create an anchor link and always a preferred way of creating links."
},
{
"code": null,
"e": 28258,
"s": 28204,
"text": "You can enclose Text or image inside <a>...</a> tags."
},
{
"code": null,
"e": 28309,
"s": 28258,
"text": "The <a> element supports the following attributes:"
},
{
"code": null,
"e": 28364,
"s": 28309,
"text": "Following is the example showing usage of <a> element."
},
{
"code": null,
"e": 28597,
"s": 28364,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card title=\"A Element\">\n<p> Link to Next Page: \n <a href=\"nextpage.wml\">Next Page</a>\n</p>\n</card>\n\n</wml>"
},
{
"code": null,
"e": 28637,
"s": 28597,
"text": "This will produce the following result:"
},
{
"code": null,
"e": 29023,
"s": 28637,
"text": "A WML task is an element that specifies an action to be performed by the browser, rather than something to be displayed. For example, the action of changing to a new card is represented by a <go> task element, and the action of returning to the previous card visited is represented by a <prev> task element. Task elements encapsulate all the information required to perform the action."
},
{
"code": null,
"e": 29139,
"s": 29023,
"text": "WML provides following four elements to handle four WML tasks called go task, pre task, refresh task and noop taks."
},
{
"code": null,
"e": 29221,
"s": 29139,
"text": "As the name suggests, the <go> task represents the action of going to a new card."
},
{
"code": null,
"e": 29273,
"s": 29221,
"text": "The <go> element supports the following attributes:"
},
{
"code": null,
"e": 29277,
"s": 29273,
"text": "get"
},
{
"code": null,
"e": 29282,
"s": 29277,
"text": "post"
},
{
"code": null,
"e": 29625,
"s": 29282,
"text": "When using method=\"get\", the data is sent as an request with ? data appended to the url. The method has a disadvantage, that it can be used only for a limited amount of data, and if you send sensitive information it will be displayed on the screen and saved in the web server's logs. So do not use this method if you are sending password etc."
},
{
"code": null,
"e": 29801,
"s": 29625,
"text": "With method=\"post\", the data is sent as an request with the data sent in the body of the request. This method has no limit, and sensitive information is not visible in the URL"
},
{
"code": null,
"e": 29806,
"s": 29801,
"text": "true"
},
{
"code": null,
"e": 29812,
"s": 29806,
"text": "false"
},
{
"code": null,
"e": 29868,
"s": 29812,
"text": "Following is the example showing usage of <go> element."
},
{
"code": null,
"e": 30111,
"s": 29868,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card title=\"GO Element\">\n<p>\n <anchor>\n Chapter 2 : <go href=\"chapter2.wml\"/>\n </anchor>\n</p>\n</card>\n</wml>"
},
{
"code": null,
"e": 30171,
"s": 30111,
"text": "Another example showing how to upload data using Get Method"
},
{
"code": null,
"e": 30448,
"s": 30171,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card title=\"GO Element\">\n<p>\n <anchor>\n Using Get Method \n <go href=\"chapter2.wml?x=17&y=42\" method=\"get\"/>\n </anchor>\n</p>\n</card>\n</wml>"
},
{
"code": null,
"e": 30515,
"s": 30448,
"text": "Another example showing how to upload data using <setvar> element."
},
{
"code": null,
"e": 30849,
"s": 30515,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card title=\"GO Element\">\n<p>\n <anchor>\n Using setvar:\n\t <go href=\"chapter2.wml\"> \n\t <setvar name=\"x\" value=\"17\"/> \n \t <setvar name=\"y\" value=\"42\"/> \n\t </go>\n </anchor>\n</p>\n</card>\n</wml>"
},
{
"code": null,
"e": 30918,
"s": 30849,
"text": "Another example showing how to upload data using <postfiled> element"
},
{
"code": null,
"e": 31281,
"s": 30918,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card title=\"GO Element\">\n<p>\n <anchor>\n Using setvar:\n\t <go href=\"chapter2.wml\" method=\"get\"> \n <postfield name=\"x\" value=\"17\"/>\n <postfield name=\"y\" value=\"42\"/>\n\t </go>\n </anchor>\n</p>\n</card>\n</wml>"
},
{
"code": null,
"e": 31577,
"s": 31281,
"text": "The <prev> task represents the action of returning to the previously visited card on the history stack. When this action is performed, the top entry is removed from the history stack, and that card is displayed again, after any <setvar> variable assignments in the <prev> task have taken effect."
},
{
"code": null,
"e": 31637,
"s": 31577,
"text": "If no previous URL exists, specifying <prev> has no effect."
},
{
"code": null,
"e": 31691,
"s": 31637,
"text": "The <prev> element supports the following attributes:"
},
{
"code": null,
"e": 31749,
"s": 31691,
"text": "Following is the example showing usage of <prev> element."
},
{
"code": null,
"e": 31980,
"s": 31749,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card title=\"Prev Element\">\n<p>\n <anchor>\n Previous Page :<prev/>\n </anchor>\n</p>\n</card>\n</wml>"
},
{
"code": null,
"e": 32289,
"s": 31980,
"text": "One situation where it can be useful to include variables in a <prev> task is a login page, which prompts for a username and password. In some situations, you may want to clear out the password field when returning to the login card, forcing the user to reenter it. This can be done with a construct such as:"
},
{
"code": null,
"e": 32566,
"s": 32289,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card title=\"Prev Element\">\n<p>\n <anchor>\n <prev>\n <setvar name=\"password\" value=\"\"/>\n </prev>\n </anchor>\n</p>\n</card>\n</wml>"
},
{
"code": null,
"e": 32869,
"s": 32566,
"text": "The <refresh> task is the simplest task that actually does something. Its effect is simply to perform the variable assignments specified by its <setvar> elements, then redisplay the current card with the new values. The <go> and <prev> tasks perform the same action just before displaying the new card."
},
{
"code": null,
"e": 32959,
"s": 32869,
"text": "The <refresh> task is most often used to perform some sort of \"reset\" action on the card."
},
{
"code": null,
"e": 33016,
"s": 32959,
"text": "The <refresh> element supports the following attributes:"
},
{
"code": null,
"e": 33077,
"s": 33016,
"text": "Following is the example showing usage of <refresh> element."
},
{
"code": null,
"e": 33425,
"s": 33077,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card title=\"Referesh Element\">\n<p>\n <anchor>\n Refresh this page:\n <go href=\"test.wml\"/>\n <refresh>\n <setvar name=\"x\" value=\"100\"/>\n </refresh>\n </anchor>\n</p>\n</card>\n</wml>"
},
{
"code": null,
"e": 33489,
"s": 33425,
"text": "The purpose of the <noop> task is to do nothing (no operation)."
},
{
"code": null,
"e": 33553,
"s": 33489,
"text": "The only real use for this task is in connection with templates"
},
{
"code": null,
"e": 33607,
"s": 33553,
"text": "The <noop> element supports the following attributes:"
},
{
"code": null,
"e": 33665,
"s": 33607,
"text": "Following is the example showing usage of <noop> element."
},
{
"code": null,
"e": 33894,
"s": 33665,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card title=\"Noop Element\">\n<p>\n <do type=\"prev\" label=\"Back\">\n <noop/>\n </do>\n</p>\n</card>\n</wml>"
},
{
"code": null,
"e": 33980,
"s": 33894,
"text": "WML provides various options to let a user enter information through WAP application."
},
{
"code": null,
"e": 34218,
"s": 33980,
"text": "First of all, we are going to look at the different options for allowing the user to make straight choices between items. These are usually in the form of menus and submenus, allowing users to drill down to the exact data that they want."
},
{
"code": null,
"e": 34523,
"s": 34218,
"text": "The <select>...</select> WML elements are used to define a selection list and the <option>...</option> tags are used to define an item in a selection list. Items are presented as radiobuttons in some WAP browsers. The <option>...</option> tag pair should be enclosed within the <select>...</select> tags."
},
{
"code": null,
"e": 34570,
"s": 34523,
"text": "This element support the following attributes:"
},
{
"code": null,
"e": 34575,
"s": 34570,
"text": "true"
},
{
"code": null,
"e": 34581,
"s": 34575,
"text": "false"
},
{
"code": null,
"e": 34643,
"s": 34581,
"text": "Following is the example showing usage of these two elements."
},
{
"code": null,
"e": 34996,
"s": 34643,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card title=\"Selectable List\">\n<p> Select a Tutorial :\n <select>\n <option value=\"htm\">HTML Tutorial</option>\n <option value=\"xml\">XML Tutorial</option>\n <option value=\"wap\">WAP Tutorial</option>\n </select>\n</p>\n</card>\n\n</wml>"
},
{
"code": null,
"e": 35068,
"s": 34996,
"text": "When you will load this program, it will show you the following screen:"
},
{
"code": null,
"e": 35151,
"s": 35068,
"text": "Once you highlight and enter on the options, it will display the following screen:"
},
{
"code": null,
"e": 35254,
"s": 35151,
"text": "You want to provide option to select multiple options, then set multiple attribute to true as follows:"
},
{
"code": null,
"e": 35623,
"s": 35254,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card title=\"Selectable List\">\n<p> Select a Tutorial :\n <select multiple=\"true\">\n <option value=\"htm\">HTML Tutorial</option>\n <option value=\"xml\">XML Tutorial</option>\n <option value=\"wap\">WAP Tutorial</option>\n </select>\n</p>\n</card>\n\n</wml>"
},
{
"code": null,
"e": 35690,
"s": 35623,
"text": "This will give you a screen to select multiple options as follows:"
},
{
"code": null,
"e": 35808,
"s": 35690,
"text": "The <input/> element is used to create input fields and input fields are used to obtain alphanumeric data from users."
},
{
"code": null,
"e": 35855,
"s": 35808,
"text": "This element support the following attributes:"
},
{
"code": null,
"e": 35860,
"s": 35855,
"text": "true"
},
{
"code": null,
"e": 35866,
"s": 35860,
"text": "false"
},
{
"code": null,
"e": 36433,
"s": 35866,
"text": "A = uppercase alphabetic or punctuation characters\n a = lowercase alphabetic or punctuation characters\n N = numeric characters\n X = uppercase characters\n x = lowercase characters\n M = all characters\n m = all characters\n *f = Any number of characters. Replace the f with one of the letters above to specify what characters the user can enter\nnf = Replace the n with a number from 1 to 9 to specify the number of characters the user can enter. Replace the f with one of the letters above to specify what characters the user can enter"
},
{
"code": null,
"e": 36438,
"s": 36433,
"text": "text"
},
{
"code": null,
"e": 36447,
"s": 36438,
"text": "password"
},
{
"code": null,
"e": 36503,
"s": 36447,
"text": "Following is the example showing usage of this element."
},
{
"code": null,
"e": 36841,
"s": 36503,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card title=\"Input Fields\">\n<p> Enter Following Information:<br/> \n Name: <input name=\"name\" size=\"12\"/>\n Age : <input name=\"age\" size=\"12\" format=\"*N\"/>\n Sex : <input name=\"sex\" size=\"12\"/> \n</p>\n</card>\n\n</wml>"
},
{
"code": null,
"e": 36915,
"s": 36841,
"text": "This will provide you the following screen to enter required information:"
},
{
"code": null,
"e": 36998,
"s": 36915,
"text": "The <fieldset/> element is used to group various input fields or selectable lists."
},
{
"code": null,
"e": 37045,
"s": 36998,
"text": "This element support the following attributes:"
},
{
"code": null,
"e": 37101,
"s": 37045,
"text": "Following is the example showing usage of this element."
},
{
"code": null,
"e": 37452,
"s": 37101,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card title=\"Grouped Fields\">\n<p> \n<fieldset title=\"Personal Info\">\n Name: <input name=\"name\" size=\"12\"/>\n Age : <input name=\"age\" size=\"12\" format=\"*N\"/>\n Sex : <input name=\"sex\" size=\"12\"/> \n</fieldset>\n</p>\n</card>\n\n</wml>"
},
{
"code": null,
"e": 37569,
"s": 37452,
"text": "This will provide you the following screen to enter required information. This result may differ browser to browser."
},
{
"code": null,
"e": 37661,
"s": 37569,
"text": "The <optgroup/> element is used to group various options together inside a selectable list."
},
{
"code": null,
"e": 37708,
"s": 37661,
"text": "This element support the following attributes:"
},
{
"code": null,
"e": 37764,
"s": 37708,
"text": "Following is the example showing usage of this element."
},
{
"code": null,
"e": 38320,
"s": 37764,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card title=\"Selectable List\"> \n<p>\n <select>\n <optgroup title=\"India\">\n <option value=\"delhi\">Delhi</option>\n <option value=\"mumbai\">Mumbai</option>\n <option value=\"hyderabad\">Hyderabad</option>\n </optgroup>\n <optgroup title=\"USA\">\n <option value=\"ohio\">Ohio</option>\n <option value=\"maryland\">Maryland</option>\n <option value=\"washington\">Washingtone</option>\n </optgroup>\n </select>\n</p>\n</card>\n\n</wml>"
},
{
"code": null,
"e": 38396,
"s": 38320,
"text": "When a user loads above code, then it will give two options to be selected:"
},
{
"code": null,
"e": 38571,
"s": 38396,
"text": "When a user selects any of the options, then only it will give final options to be selected. So if user selects India, then it will show you following options to be selected:"
},
{
"code": null,
"e": 38729,
"s": 38571,
"text": "Many times, you will want your users to submit some data to your server. Similar to HTML Form WML also provide a mechanism to submit user data to web server."
},
{
"code": null,
"e": 38893,
"s": 38729,
"text": "To submit data to the server in WML, you need the <go>...</go> along with <postfield/> tags. The <postfield/> tag should be enclosed in the <go>...</go> tag pair. "
},
{
"code": null,
"e": 39155,
"s": 38893,
"text": "To submit data to a server, we collect all the set WML variables and use <postfield> elements to send them to the server. The <go>...</go> elements are used to set posting method to either POST or GET and to specify a server side script to handle uploaded data."
},
{
"code": null,
"e": 39446,
"s": 39155,
"text": "In previous chapters we have explained various ways of taking inputs form the users. These input elements sets WML variables to the entered values. We also know how to take values from WML variables. So now following example shows how to submit three fields name, age and sex to the server."
},
{
"code": null,
"e": 40100,
"s": 39446,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card id=\"card1\" title=\"WML Form\">\n<p>\n Name: <input name=\"name\" size=\"12\"/>\n Sex : <select name=\"sex\">\n <option value=\"male\">Male</option>\n <option value=\"female\">Female</option>\n </select>\n Age : <input name=\"age\" size=\"12\" format=\"*N\"/>\n <anchor>\n <go method=\"get\" href=\"process.php\">\n <postfield name=\"name\" value=\"$(name)\"/>\n <postfield name=\"age\" value=\"$(age)\"/>\n <postfield name=\"sex\" value=\"$(sex)\"/>\n </go>\n Submit Data\n </anchor>\n</p>\n</card>\n\n</wml>"
},
{
"code": null,
"e": 40356,
"s": 40100,
"text": "When you download above code on your WAP device, it will provide you option to enter three fields name, age and sex and one link Submit Data. You will enter three fields and then finally you will select Submit Data link to send entered data to the server."
},
{
"code": null,
"e": 40459,
"s": 40356,
"text": "The method attribute of the <go> tag specifies which HTTP method should be used to send the form data."
},
{
"code": null,
"e": 40918,
"s": 40459,
"text": "If the HTTP POST method is used, the form data to be sent will be placed in the message body of the request. If the HTTP GET method is used, the form data to be sent will be appended to the URL. Since a URL can only contain a limited number of characters, the GET method has the disadvantage that there is a size limit for the data to be sent. If the user data contains non-ASCII characters, you should make use of the POST method to avoid encoding problems."
},
{
"code": null,
"e": 41295,
"s": 40918,
"text": "There is one major difference between HTML and WML. In HTML, the name attribute of the <input> and <select> tags is used to specify the name of the parameter to be sent, while in WML the name attribute of the <postfield> tag is used to do the same thing. In WML, the name attribute of <input> and <select> is used to specify the name of the variable for storing the form data."
},
{
"code": null,
"e": 41366,
"s": 41295,
"text": "Next chapter will teach you how to handle uploaded data at server end."
},
{
"code": null,
"e": 41640,
"s": 41366,
"text": "If you already know how to write server side scripts for Web Application, then for you this is very simple to write Server Side program for WML applications. You can use your favorite server-side technology to do the processing required by your mobile Internet application."
},
{
"code": null,
"e": 41719,
"s": 41640,
"text": "At the server side, the parameter name will be used to retrieve the form data."
},
{
"code": null,
"e": 41813,
"s": 41719,
"text": "Consider the following example from previous chapter to submit name, age and sex of a person:"
},
{
"code": null,
"e": 42467,
"s": 41813,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card id=\"card1\" title=\"WML Form\">\n<p>\n Name: <input name=\"name\" size=\"12\"/>\n Sex : <select name=\"sex\">\n <option value=\"male\">Male</option>\n <option value=\"female\">Female</option>\n </select>\n Age : <input name=\"age\" size=\"12\" format=\"*N\"/>\n <anchor>\n <go method=\"get\" href=\"process.php\">\n <postfield name=\"name\" value=\"$(name)\"/>\n <postfield name=\"age\" value=\"$(age)\"/>\n <postfield name=\"sex\" value=\"$(sex)\"/>\n </go>\n Submit Data\n </anchor>\n</p>\n</card>\n\n</wml>"
},
{
"code": null,
"e": 42649,
"s": 42467,
"text": "Now, we can write a server side script to handle this submitted data in using either PHP, PERL, ASP or JSP. I will show you a server side script written in PHP with HTTP GET method."
},
{
"code": null,
"e": 42744,
"s": 42649,
"text": "Put the following PHP code in process.php file in same directory where you have your WML file."
},
{
"code": null,
"e": 43187,
"s": 42744,
"text": "<?php echo 'Content-type: text/vnd.wap.wml'; ?>\n<?php echo '<?xml version=\"1.0\"?'.'>'; ?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n \n <card id=\"card1\" title=\"WML Response\">\n <p>\n Data received at the server:<br/>\n Name: <?php echo $_GET[\"name\"]; ?><br/>\n Age: <?php echo $_GET[\"age\"]; ?><br/>\n Sex: <?php echo $_GET[\"sex\"]; ?><br/>\n </p>\n </card>\n\n</wml>"
},
{
"code": null,
"e": 43404,
"s": 43187,
"text": "If you are using HTTP POST method, then you have to write PHP script accordingly to handle received data. While sending output back to the browser, remember to set the MIME type of the document to \"text/vnd.wap.wml\"."
},
{
"code": null,
"e": 43506,
"s": 43404,
"text": "This way, you can write full fledged Web Application where lot of database transactions are involved."
},
{
"code": null,
"e": 43565,
"s": 43506,
"text": "You can use PERL CGI Concepts to write a dynamic WAP site."
},
{
"code": null,
"e": 43852,
"s": 43565,
"text": "Event in ordinary language can be defined as something happened. In programming, event is identical in meaning, but with one major difference. When something happens in a computer system, the system itself has to (1) detect that something has happened and (2) know what to do about it."
},
{
"code": null,
"e": 44025,
"s": 43852,
"text": "WML language also supports events and you can specify an action to be taken whenever an event occurs. This action could be in terms of WMLScript or simply in terms of WML. "
},
{
"code": null,
"e": 44066,
"s": 44025,
"text": "WML supports following four event types:"
},
{
"code": null,
"e": 44269,
"s": 44066,
"text": "onenterbackward: This event occurs when the user hits a card by normal backward navigational means. That is, user presses the Back key on a later card and arrives back at this card in the history stack."
},
{
"code": null,
"e": 44472,
"s": 44269,
"text": "onenterbackward: This event occurs when the user hits a card by normal backward navigational means. That is, user presses the Back key on a later card and arrives back at this card in the history stack."
},
{
"code": null,
"e": 44570,
"s": 44472,
"text": "onenterforward: This event occurs when the user hits a card by normal forward navigational means."
},
{
"code": null,
"e": 44668,
"s": 44570,
"text": "onenterforward: This event occurs when the user hits a card by normal forward navigational means."
},
{
"code": null,
"e": 44821,
"s": 44668,
"text": "onpick: This is more like an attribute but it is being used like an event. This event occurs when an item of a selection list is selected or deselected."
},
{
"code": null,
"e": 44974,
"s": 44821,
"text": "onpick: This is more like an attribute but it is being used like an event. This event occurs when an item of a selection list is selected or deselected."
},
{
"code": null,
"e": 45049,
"s": 44974,
"text": "ontimer: This event is used to trigger an event after a given time period."
},
{
"code": null,
"e": 45124,
"s": 45049,
"text": "ontimer: This event is used to trigger an event after a given time period."
},
{
"code": null,
"e": 45190,
"s": 45124,
"text": "These event names are case sensitive and they must be lowercase. "
},
{
"code": null,
"e": 45293,
"s": 45190,
"text": "The <onevent>...</onevent> tags are used to create event handlers. Its usage takes the following form:"
},
{
"code": null,
"e": 45359,
"s": 45293,
"text": "<onevent type=\"event_type\">\n A task to be performed.\n</onevent>"
},
{
"code": null,
"e": 45457,
"s": 45359,
"text": "You can use either go, prev or refresh task inside <onevent>...</onevent> tags against an event."
},
{
"code": null,
"e": 45514,
"s": 45457,
"text": "The <onevent> element supports the following attributes:"
},
{
"code": null,
"e": 45530,
"s": 45514,
"text": "onenterbackward"
},
{
"code": null,
"e": 45545,
"s": 45530,
"text": "onenterforward"
},
{
"code": null,
"e": 45552,
"s": 45545,
"text": "onpick"
},
{
"code": null,
"e": 45560,
"s": 45552,
"text": "ontimer"
},
{
"code": null,
"e": 45816,
"s": 45560,
"text": "Following is the example showing usage of <onevent> element. In this example, whenever you try to go back from second card to first card then onenterbackward occurs which moves you to card number three. Copy and paste this program and try to play with it."
},
{
"code": null,
"e": 46299,
"s": 45816,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n<onevent type=\"onenterbackward\">\n <go href=\"#card3\"/>\n</onevent>\n\n<card id=\"card1\" title=\"Card 1\">\n<p>\n <anchor>\n <go href=\"#card2\"/>\n Go to card 2\n </anchor>\n</p>\n</card>\n<card id=\"card2\" title=\"Card 2\">\n<p>\n <anchor>\n <prev/>\n Going backwards\n </anchor>\n</p>\n</card>\n<card id=\"card3\" title=\"Card 3\">\n<p>\nHello World!\n</p>\n</card>\n</wml>"
},
{
"code": null,
"e": 46416,
"s": 46299,
"text": "Previous chapter has described how events are triggered by the users and how do we handle them using event handlers."
},
{
"code": null,
"e": 46569,
"s": 46416,
"text": "Sometime, you may want something to happen without the user explicitly having to activate a control. Yes, WML provides you ontimer event to handle this."
},
{
"code": null,
"e": 46734,
"s": 46569,
"text": "The ontimer event is triggered when a card's timer counts down from one to zero, which means that it doesn't occur if the timer is initialized to a timeout of zero."
},
{
"code": null,
"e": 46816,
"s": 46734,
"text": "You can bind a task to this event with the <onevent> element. Here is the syntax:"
},
{
"code": null,
"e": 46879,
"s": 46816,
"text": "<onevent type=\"ontimer\">\n A task to be performed.\n</onevent>"
},
{
"code": null,
"e": 46928,
"s": 46879,
"text": "Here, a task could be <go>, <prev> or <refresh>."
},
{
"code": null,
"e": 47197,
"s": 46928,
"text": "A timer is declared inside a WML card with the <timer> element. It must follow the <onevent> elements if they\nare present. (If there are no <onevent> elements, the <timer> must be the first element inside the <card>.) No\nmore than one <timer> may be present in a card."
},
{
"code": null,
"e": 47252,
"s": 47197,
"text": "The <timer> element supports the following attributes:"
},
{
"code": null,
"e": 47311,
"s": 47252,
"text": "Following is the example showing usage of <timer> element."
},
{
"code": null,
"e": 47693,
"s": 47311,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card id=\"splash\" title=\"splash\">\n <onevent type=\"ontimer\">\n <go href=\"#welcome\"/>\n </onevent>\n <timer value=\"50\"/>\n<p>\n <a href=\"#welcome\">Enter</a>\n</p>\n</card>\n\n<card id=\"welcome\" title=\"Welcome\">\n<p>\nWelcome to the main screen.\n</p>\n</card>\n</wml>"
},
{
"code": null,
"e": 47752,
"s": 47693,
"text": "When you load this program it shows you following screen:"
},
{
"code": null,
"e": 47906,
"s": 47752,
"text": "If you do not select given Enter option then after 5 seconds, you will be directed to Welcome page and following screen will be displayed automatically."
},
{
"code": null,
"e": 48121,
"s": 47906,
"text": "The <template> is used to apply <do> and <onevent> elements to all cards in a deck. This element defines a template for all the cards in a deck and the code in the <template> tag is added to each card in the deck."
},
{
"code": null,
"e": 48250,
"s": 48121,
"text": "You can override a <do> element of a template by defining another <do> element with the same name attribute value in a WML card."
},
{
"code": null,
"e": 48308,
"s": 48250,
"text": "The <template> element supports the following attributes:"
},
{
"code": null,
"e": 48364,
"s": 48308,
"text": "Following is the example showing usage of <go> element."
},
{
"code": null,
"e": 50024,
"s": 48364,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.3//EN\" \n\"http://www.wapforum.org/DTD/wml13.dtd\">\n\n<wml>\n <template>\n <do name=\"main_menu\" type=\"accept\" label=\"Chapters\">\n <go href=\"chapters\"/>\n </do>\n <do name=\"menu_1\" type=\"accept\" label=\"Chapter 1\">\n <go href=\"#chapter1\"/>\n </do>\n <do name=\"menu_2\" type=\"accept\" label=\"Chapter 2\">\n <go href=\"#chapter2\"/>\n </do>\n <do name=\"menu_3\" type=\"accept\" label=\"Chapter 3\">\n <go href=\"#chapter3\"/>\n </do>\n <do name=\"menu_4\" type=\"accept\" label=\"Chapter 4\">\n <go href=\"#chapter4\"/>\n </do>\n </template>\n\n <card id=\"chapters\" title=\"WML Tutorial\">\n <p>\n Select One Chapter:<br/>\n <anchor>\n <go href=\"#chapter1\"/>\n Chapter 1: WML Overview\n </anchor><br />\n\n <anchor>\n <go href=\"#chapter2\"/>\n Chapter 2: WML Environment\n </anchor><br />\n\n <anchor>\n <go href=\"#chapter3\"/>\n Chapter 3: WML Syntax\n </anchor><br />\n\n <anchor>\n <go href=\"#chapter4\"/>\n Chapter 4: WML Elements\n </anchor><br />\n </p>\n </card>\n\n <card id=\"chapter1\" title=\"WML Tutorial Ch1\">\n <p>\n <em>Chapter 1: WML Introduction</em><br/>\n ...\n </p>\n </card>\n\n <card id=\"chapter2\" title=\"WML Tutorial Ch2\">\n <p>\n <em>Chapter 2: WML Environment</em><br/>\n ...\n </p>\n </card>\n\n <card id=\"chapter3\" title=\"WML Tutorial Ch3\">\n <p>\n <em>Chapter 3: WML Syntax</em><br/>\n ...\n </p>\n </card>\n\n <card id=\"chapter4\" title=\"WML Tutorial Ch4\">\n <p>\n <em>Chapter 4: WML Elements</em><br/>\n ...\n </p>\n </card>\n</wml>"
},
{
"code": null,
"e": 50112,
"s": 50024,
"text": "This will produce the following menu and now you can navigate through all the chapters:"
},
{
"code": null,
"e": 50235,
"s": 50112,
"text": "Here is the complete DTD taken from W3.org. For a latest DTD, please check WML Useful Resources section of this tutorial."
},
{
"code": null,
"e": 58979,
"s": 50235,
"text": "<!--\nWireless Markup Language (WML) Document Type Definition.\nWML is an XML language. Typical usage:\n <?xml version=\"1.0\"?>\n <!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n \"http://www.wapforum.org/DTD/wml12.dtd\">\n <wml>\n ...\n </wml>\n\n Terms and conditions of use are available from the WAP Forum\n Ltd. web site at http://www.wapforum.org/docs/copyright.htm.\n-->\n<!ENTITY % length \"CDATA\"> \n <!-- [0-9]+ for pixels or [0-9]+\"%\" for\n percentage length -->\n<!ENTITY % vdata \"CDATA\"> \n <!-- attribute value possibly containing\n variable references -->\n<!ENTITY % HREF \"%vdata;\"> \n <!-- URI, URL or URN designating a hypertext\n node. May contain variable references -->\n<!ENTITY % boolean \"(true|false)\">\n<!ENTITY % number \"NMTOKEN\"> \n <!-- a number, with format [0-9]+ -->\n<!ENTITY % coreattrs \"id ID #IMPLIED\n class CDATA #IMPLIED\">\n<!ENTITY % ContentType \"%vdata;\"> \n<!-- media type. May contain variable references -->\n\n<!ENTITY % emph \"em | strong |b |i |u |big |small\">\n<!ENTITY % layout \"br\">\n\n<!ENTITY % text \"#PCDATA | %emph;\">\n\n<!-- flow covers \"card-level\" elements, \n such as text and images -->\n<!ENTITY % flow \"%text; | %layout; | img | anchor |a |table\">\n\n<!-- Task types -->\n<!ENTITY % task \"go | prev | noop | refresh\">\n\n<!-- Navigation and event elements -->\n<!ENTITY % navelmts \"do | onevent\">\n\n<!--================ Decks and Cards ================-->\n\n<!ELEMENT wml ( head?, template?, card+ )>\n<!ATTLIST wml\n xml:lang NMTOKEN #IMPLIED\n %coreattrs;\n>\n\n<!-- card intrinsic events -->\n<!ENTITY % cardev\n \"onenterforward %HREF; #IMPLIED\n onenterbackward %HREF; #IMPLIED\n ontimer %HREF; #IMPLIED\"\n>\n\n<!-- card field types -->\n<!ENTITY % fields \"%flow; | input | select | fieldset\">\n<!ELEMENT card (onevent*, timer?, (do | p | pre)*)>\n<!ATTLIST card\n title %vdata; #IMPLIED\n newcontext %boolean; \"false\"\n ordered %boolean; \"true\"\n xml:lang NMTOKEN #IMPLIED\n %cardev;\n %coreattrs;\n>\n\n<!--================ Event Bindings ================-->\n\n<!ELEMENT do (%task;)>\n<!ATTLIST do\n type CDATA #REQUIRED\n label %vdata; #IMPLIED\n name NMTOKEN #IMPLIED\n optional %boolean; \"false\"\n xml:lang NMTOKEN #IMPLIED\n %coreattrs;\n>\n\n<!ELEMENT onevent (%task;)>\n<!ATTLIST onevent\n type CDATA #REQUIRED\n %coreattrs;\n>\n\n<!--================ Deck-level declarations ================-->\n\n<!ELEMENT head ( access | meta )+>\n<!ATTLIST head\n %coreattrs;\n>\n\n<!ELEMENT template (%navelmts;)*>\n<!ATTLIST template\n %cardev;\n %coreattrs;\n>\n\n<!ELEMENT access EMPTY>\n<!ATTLIST access\n domain CDATA #IMPLIED\n path CDATA #IMPLIED\n %coreattrs;\n>\n\n<!ELEMENT meta EMPTY>\n<!ATTLIST meta\n http-equiv CDATA #IMPLIED\n name CDATA #IMPLIED\n forua %boolean; \"false\"\n content CDATA #REQUIRED\n scheme CDATA #IMPLIED\n %coreattrs;\n>\n\n<!--================ Tasks ================-->\n\n<!ELEMENT go (postfield | setvar)*>\n<!ATTLIST go\n href %HREF; #REQUIRED\n sendreferer %boolean; \"false\"\n method (post|get) \"get\"\n enctype %ContentType; \"application/x-www-form-urlencoded\"\n accept-charset CDATA #IMPLIED\n %coreattrs;\n>\n\n<!ELEMENT prev (setvar)*>\n<!ATTLIST prev\n %coreattrs;\n>\n\n<!ELEMENT refresh (setvar)*>\n<!ATTLIST refresh\n %coreattrs;\n>\n\n<!ELEMENT noop EMPTY>\n<!ATTLIST noop\n %coreattrs;\n>\n\n<!--================ postfield ================-->\n\n<!ELEMENT postfield EMPTY>\n<!ATTLIST postfield\n name %vdata; #REQUIRED\n value %vdata; #REQUIRED\n %coreattrs;\n>\n\n<!--================ variables ================-->\n\n<!ELEMENT setvar EMPTY>\n<!ATTLIST setvar\n name %vdata; #REQUIRED\n value %vdata; #REQUIRED\n %coreattrs;\n>\n\n<!--================ Card Fields ================-->\n\n<!ELEMENT select (optgroup|option)+>\n<!ATTLIST select\n title %vdata; #IMPLIED\n name NMTOKEN #IMPLIED\n value %vdata; #IMPLIED\n iname NMTOKEN #IMPLIED\n ivalue %vdata; #IMPLIED\n multiple %boolean; \"false\"\n tabindex %number; #IMPLIED\n xml:lang NMTOKEN #IMPLIED\n %coreattrs;\n>\n\n<!ELEMENT optgroup (optgroup|option)+ >\n<!ATTLIST optgroup\n title %vdata; #IMPLIED\n xml:lang NMTOKEN #IMPLIED\n %coreattrs;\n>\n\n<!ELEMENT option (#PCDATA | onevent)*>\n<!ATTLIST option\n value %vdata; #IMPLIED\n title %vdata; #IMPLIED\n onpick %HREF; #IMPLIED\n xml:lang NMTOKEN #IMPLIED\n %coreattrs;\n>\n\n<!ELEMENT input EMPTY>\n<!ATTLIST input\n name NMTOKEN #REQUIRED\n type (text|password) \"text\"\n value %vdata; #IMPLIED\n format CDATA #IMPLIED\n emptyok %boolean; \"false\"\n size %number; #IMPLIED\n maxlength %number; #IMPLIED\n tabindex %number; #IMPLIED\n title %vdata; #IMPLIED\n accesskey %vdata; #IMPLIED\n xml:lang NMTOKEN #IMPLIED\n %coreattrs;\n>\n\n<!ELEMENT fieldset (%fields; | do)* >\n<!ATTLIST fieldset\n title %vdata; #IMPLIED\n xml:lang NMTOKEN #IMPLIED\n %coreattrs;\n>\n\n<!ELEMENT timer EMPTY>\n<!ATTLIST timer\n name NMTOKEN #IMPLIED\n value %vdata; #REQUIRED\n %coreattrs;\n>\n\n<!--================ Images ================-->\n\n<!ENTITY % IAlign \"(top|middle|bottom)\" >\n<!ELEMENT img EMPTY>\n<!ATTLIST img\n alt %vdata; #REQUIRED\n src %HREF; #REQUIRED\n localsrc %vdata; #IMPLIED\n vspace %length; \"0\"\n hspace %length; \"0\"\n align %IAlign; \"bottom\"\n height %length; #IMPLIED\n width %length; #IMPLIED\n xml:lang NMTOKEN #IMPLIED\n %coreattrs;\n>\n\n<!--================ Anchor ================-->\n\n<!ELEMENT anchor ( #PCDATA | br | img | go | prev | refresh )*>\n<!ATTLIST anchor\n title %vdata; #IMPLIED\n accesskey %vdata; #IMPLIED\n xml:lang NMTOKEN #IMPLIED\n %coreattrs;\n>\n<!ELEMENT a ( #PCDATA | br | img )*>\n<!ATTLIST a\n href %HREF; #REQUIRED\n title %vdata; #IMPLIED\n accesskey %vdata; #IMPLIED\n xml:lang NMTOKEN #IMPLIED\n %coreattrs;\n>\n\n<!--================ Tables ================-->\n\n<!ELEMENT table (tr)+>\n<!ATTLIST table\n title %vdata; #IMPLIED\n align CDATA #IMPLIED\n columns %number; #REQUIRED\n xml:lang NMTOKEN #IMPLIED\n %coreattrs;\n>\n\n<!ELEMENT tr (td)+>\n<!ATTLIST tr\n %coreattrs;\n>\n<!ELEMENT td ( %text; | %layout; | img | anchor |a )*>\n<!ATTLIST td\n xml:lang NMTOKEN #IMPLIED\n %coreattrs;\n>\n\n<!--============ Text layout and line breaks =============-->\n\n<!ELEMENT em (%flow;)*>\n<!ATTLIST em\n xml:lang NMTOKEN #IMPLIED\n %coreattrs;\n>\n\n<!ELEMENT strong (%flow;)*>\n<!ATTLIST strong\n xml:lang NMTOKEN #IMPLIED\n %coreattrs;\n>\n\n<!ELEMENT b (%flow;)*>\n<!ATTLIST b\n xml:lang NMTOKEN #IMPLIED\n %coreattrs;\n>\n\n<!ELEMENT i (%flow;)*>\n<!ATTLIST i\n xml:lang NMTOKEN #IMPLIED\n %coreattrs;\n>\n\n<!ELEMENT u (%flow;)*>\n<!ATTLIST u\n xml:lang NMTOKEN #IMPLIED\n %coreattrs;\n>\n\n<!ELEMENT big (%flow;)*>\n<!ATTLIST big\n xml:lang NMTOKEN #IMPLIED\n %coreattrs;\n>\n\n<!ELEMENT small (%flow;)*>\n<!ATTLIST small\n xml:lang NMTOKEN #IMPLIED\n %coreattrs;\n>\n\n<!ENTITY % TAlign \"(left|right|center)\">\n<!ENTITY % WrapMode \"(wrap|nowrap)\" >\n\n<!ELEMENT p (%fields; | do)*>\n<!ATTLIST p\n align %TAlign; \"left\"\n mode %WrapMode; #IMPLIED\n xml:lang NMTOKEN #IMPLIED\n %coreattrs;\n>\n\n<!ELEMENT br EMPTY>\n<!ATTLIST br\n %coreattrs;\n>\n\n<!ELEMENT pre (#PCDATA | a | br | i | b | em | strong | \n input | select )*>\n<!ATTLIST pre\n xml:space CDATA #FIXED \"preserve\"\n %coreattrs;\n>\n\n<!ENTITY quot \"\"\"> <!-- quotation mark -->\n<!ENTITY amp \"&\"> <!-- ampersand -->\n<!ENTITY apos \"'\"> <!-- apostrophe -->\n<!ENTITY lt \"<\"> <!-- less than -->\n<!ENTITY gt \">\"> <!-- greater than -->\n<!ENTITY nbsp \" \"> <!-- non-breaking space -->\n<!ENTITY shy \"\"> <!-- soft hyphen (discretionary hyphen) -->"
},
{
"code": null,
"e": 59057,
"s": 58979,
"text": "WML2 is a language, which extends the syntax and semantics of the followings:"
},
{
"code": null,
"e": 59084,
"s": 59057,
"text": "XHTML Basic [ XHTMLBasic ]"
},
{
"code": null,
"e": 59113,
"s": 59084,
"text": "CSS Mobile Profile [ CSSMP ]"
},
{
"code": null,
"e": 59151,
"s": 59113,
"text": "Unique semantics of WML1.0 [ WML1.0 ]"
},
{
"code": null,
"e": 59307,
"s": 59151,
"text": "WML2 is optimised for specifying presentation and user interaction on limited capability devices such as mobile phones and other wireless mobile terminals."
},
{
"code": null,
"e": 59435,
"s": 59307,
"text": "This tutorial gives detail of the Wireless Markup Language (WML) Version 2. This tutorial refers to version 2.0 of WML as WML2."
},
{
"code": null,
"e": 59540,
"s": 59435,
"text": "The XHTML Basic defined by the W3C is a proper subset of XHTML, which is a reformulation of HTML in XML."
},
{
"code": null,
"e": 59577,
"s": 59540,
"text": "There are five major goals for WML2:"
},
{
"code": null,
"e": 59660,
"s": 59577,
"text": "Backward compatibility: WML2 application should be running on old devices as well."
},
{
"code": null,
"e": 59743,
"s": 59660,
"text": "Backward compatibility: WML2 application should be running on old devices as well."
},
{
"code": null,
"e": 59858,
"s": 59743,
"text": "Convergence with existing and evolving Internet standards: XHTML Basic [XHTMLBasic] and CSS Mobile Profile [CSSMP]"
},
{
"code": null,
"e": 59973,
"s": 59858,
"text": "Convergence with existing and evolving Internet standards: XHTML Basic [XHTMLBasic] and CSS Mobile Profile [CSSMP]"
},
{
"code": null,
"e": 60201,
"s": 59973,
"text": "Optimisation of access from small, limited devices: WAP-enabled devices are generally small and battery operated and they have relatively limited memory and CPU power. So WML2 should be optimized enough to run on these devices."
},
{
"code": null,
"e": 60429,
"s": 60201,
"text": "Optimisation of access from small, limited devices: WAP-enabled devices are generally small and battery operated and they have relatively limited memory and CPU power. So WML2 should be optimized enough to run on these devices."
},
{
"code": null,
"e": 60625,
"s": 60429,
"text": "Allowance for the creation of distinct user interfaces: WAP enables the creation of Man Machine Interfaces (MMIs) with maximum flexibility and ability for a vendor to enhance the user experience."
},
{
"code": null,
"e": 60821,
"s": 60625,
"text": "Allowance for the creation of distinct user interfaces: WAP enables the creation of Man Machine Interfaces (MMIs) with maximum flexibility and ability for a vendor to enhance the user experience."
},
{
"code": null,
"e": 61048,
"s": 60821,
"text": "Internationalisation of the architecture: WAP targets common character codes for international use. This includes international symbols and pictogram sets for end users, and local-use character encoding for content developers."
},
{
"code": null,
"e": 61275,
"s": 61048,
"text": "Internationalisation of the architecture: WAP targets common character codes for international use. This includes international symbols and pictogram sets for end users, and local-use character encoding for content developers."
},
{
"code": null,
"e": 61494,
"s": 61275,
"text": "The WML2 vision is to create a language that extends the syntax and semantics of XHTML Basic and CSS Mobile profile with the unique semantics of WML1. The user should not be aware of how WML1 compatibility is achieved."
},
{
"code": null,
"e": 61548,
"s": 61494,
"text": "WML2 is a new language with the following components:"
},
{
"code": null,
"e": 61692,
"s": 61548,
"text": "This element group is for W3C convergence. For some of the elements, WML extension attributes are added in\norder to achieve WML1 functionality."
},
{
"code": null,
"e": 61885,
"s": 61692,
"text": "a abbr acronym address base blockquote br caption cite code dd dfn div dl dt em form h1 h2 h3 h4 h5 h6 head kbd label li link object ol param pre q samp span strong table td th title tr ul var"
},
{
"code": null,
"e": 61941,
"s": 61885,
"text": "body html img input meta option p select style textarea"
},
{
"code": null,
"e": 62178,
"s": 61941,
"text": "This element group consists of select elements from those modules of XHTML not included in XHTML Basic. Most elements are included for WML1 compatibility. One element is included as an enhancement that fits limited handset capabilities."
},
{
"code": null,
"e": 62280,
"s": 62178,
"text": "b big i small (from Presentation Module) u (from Legacy Module) fieldset optgroup (from Forms Module)"
},
{
"code": null,
"e": 62283,
"s": 62280,
"text": "hr"
},
{
"code": null,
"e": 62475,
"s": 62283,
"text": "Some elements are brought from WML1, because the equivalent capabilities are not provided in XHTML Basic or XHTML Modularization. One element is included for enhancement of WML1 capabilities."
},
{
"code": null,
"e": 62608,
"s": 62475,
"text": "wml:access wml:anchor wml:card wml:do wml:getvar wml:go wml:noop wml:onevent wml:postfield wml:prev wml:refresh wml:setvar wml:timer"
},
{
"code": null,
"e": 62619,
"s": 62608,
"text": "wml:widget"
},
{
"code": null,
"e": 62720,
"s": 62619,
"text": "The following elements in the Structure Module are used to specify the structure of a WML2 document:"
},
{
"code": null,
"e": 62726,
"s": 62720,
"text": "body "
},
{
"code": null,
"e": 62731,
"s": 62726,
"text": "html"
},
{
"code": null,
"e": 62740,
"s": 62731,
"text": "wml:card"
},
{
"code": null,
"e": 62745,
"s": 62740,
"text": "head"
},
{
"code": null,
"e": 62751,
"s": 62745,
"text": "title"
},
{
"code": null,
"e": 63015,
"s": 62751,
"text": "The wml:newcontext attribute specifies whether the browser context is initialised to a well-defined state when the\ndocument is loaded. If the wml:newcontext attribute value is \"true\", the browser MUST reinitialise the browser\ncontext upon navigation to this card."
},
{
"code": null,
"e": 63115,
"s": 63015,
"text": "The xmlns:wml attribute refers to the WML namespace for example : http://www.wapforum.org/2001/wml."
},
{
"code": null,
"e": 63308,
"s": 63115,
"text": "The wml:use-xml-fragments attribute is used to specify how a fragment identifier is interpreted by the user agent. For details of use of wml:use-xml-fragments in the go task and the prev task."
},
{
"code": null,
"e": 63526,
"s": 63308,
"text": "The wml:card element specifies a fragment of the document body. Multiple wml:card elements may appear in a single document. Each wml:card element represents an individual presentation and/or interaction with the user."
},
{
"code": null,
"e": 63670,
"s": 63526,
"text": "If the wml:card element's newcontext attribute value is \"true\", the browser MUST reinitialise the browser context upon navigation to this card."
},
{
"code": null,
"e": 63763,
"s": 63670,
"text": "This element keeps header information of the document like meta element and style sheet etc."
},
{
"code": null,
"e": 63808,
"s": 63763,
"text": "This element is used to put a document title"
},
{
"code": null,
"e": 64162,
"s": 63808,
"text": "NOTE: WML developers can use the XHTML document style, that is, body structure, or they can use a collection of cards. When the body structure is used, a document is constructed using a body element. The body element contains the content of the document. When a collection of cards is used, a document is constructed using one or more wml:card elements."
},
{
"code": null,
"e": 64244,
"s": 64162,
"text": "The following tasks are defined in WML2.0. These tasks are very similar to WML1.0"
},
{
"code": null,
"e": 64256,
"s": 64244,
"text": "The go task"
},
{
"code": null,
"e": 64270,
"s": 64256,
"text": "The prev task"
},
{
"code": null,
"e": 64284,
"s": 64270,
"text": "The noop task"
},
{
"code": null,
"e": 64301,
"s": 64284,
"text": "The refresh task"
},
{
"code": null,
"e": 64348,
"s": 64301,
"text": "The following event types are defined in WML2:"
},
{
"code": null,
"e": 64503,
"s": 64348,
"text": "Intrinsic event: An event generated by the user agent and includes the following events similar to WML1.0\n\nontimer\nonenterforward\nonenterbackward\nonpick\n\n"
},
{
"code": null,
"e": 64609,
"s": 64503,
"text": "Intrinsic event: An event generated by the user agent and includes the following events similar to WML1.0"
},
{
"code": null,
"e": 64617,
"s": 64609,
"text": "ontimer"
},
{
"code": null,
"e": 64632,
"s": 64617,
"text": "onenterforward"
},
{
"code": null,
"e": 64648,
"s": 64632,
"text": "onenterbackward"
},
{
"code": null,
"e": 64655,
"s": 64648,
"text": "onpick"
},
{
"code": null,
"e": 64863,
"s": 64655,
"text": "Extrinsic event: An event sent to the user agent by some external agent. The WML 2 specification does not specify any classes of extrinsic events. One example of a WML extrinsic event class may be WTA events"
},
{
"code": null,
"e": 65071,
"s": 64863,
"text": "Extrinsic event: An event sent to the user agent by some external agent. The WML 2 specification does not specify any classes of extrinsic events. One example of a WML extrinsic event class may be WTA events"
},
{
"code": null,
"e": 65284,
"s": 65071,
"text": "WML2 documents are identified by the MIME media type \"application/wml+xml\". The type \"application/xhtml+xml\" can be used to identify documents from any of the XHTML-based markup languages, including XHTML Basic."
},
{
"code": null,
"e": 65433,
"s": 65284,
"text": "The DOCTYPE declaration may include the XHTML Basic Formal Public Identifier and may also include the URI of the XHTML Basic DTD as specified below:"
},
{
"code": null,
"e": 65543,
"s": 65433,
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML Basic 1.0//EN\"\n\"http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd\">"
},
{
"code": null,
"e": 65656,
"s": 65543,
"text": "Style sheets can be used to style WML2 documents. Style information can be associated with a document in 3 ways:"
},
{
"code": null,
"e": 65838,
"s": 65656,
"text": "An external style sheet can be associated with a document using a special XML processing instruction or the link\nelement. The use of the XML processing instruction can also be used."
},
{
"code": null,
"e": 65955,
"s": 65838,
"text": "In the following example, the XML processing instruction is used to associate the external style sheet \"mobile.css\"."
},
{
"code": null,
"e": 66047,
"s": 65955,
"text": "<?xml-stylesheet href=\"mobile.css\" \n media=\"handheld\" type=\"text/css\" ?>"
},
{
"code": null,
"e": 66151,
"s": 66047,
"text": "In the following example, the link element is used to associate the external style sheet \"mystyle.css\":"
},
{
"code": null,
"e": 66249,
"s": 66151,
"text": "<html>\n<head>\n<link href=\"mystyle.css\" type=\"text/css\" rel=\"stylesheet\"/>\n...\n</head>\n...\n</html>"
},
{
"code": null,
"e": 66392,
"s": 66249,
"text": "Style information can be located within the document using the style element. This element, like link, must be located in the document header."
},
{
"code": null,
"e": 66451,
"s": 66392,
"text": "The following shows an example of an internal style sheet:"
},
{
"code": null,
"e": 66548,
"s": 66451,
"text": "<html>\n<head>\n<style type=\"text/css\">\np { text-align: center; }\n</style>\n...\n</head>\n...\n</html>"
},
{
"code": null,
"e": 66659,
"s": 66548,
"text": "You can specify style information for a single element using the style attribute. This is called inline style."
},
{
"code": null,
"e": 66756,
"s": 66659,
"text": "In the following example, inline styling information is applied to a specific paragraph element:"
},
{
"code": null,
"e": 66794,
"s": 66756,
"text": "<p style=\"text-align: center\">...</p>"
},
{
"code": null,
"e": 66836,
"s": 66794,
"text": "Here is a sample style sheet for WML 2.0:"
},
{
"code": null,
"e": 67557,
"s": 66836,
"text": "body, card, div, p, center, hr, h1, h2, h3, h4, h5, h6,\naddress, blockquote, pre, ol, ul, dl, dt, dd,\nform, fieldset, object { display: block }\nli { display: list-item }\nhead { display: none }\ntable { display: table }\ntr { display: table-row }\ntd, th { display: table-cell }\ncaption { display: table-caption }\nth { font-weight: bolder; text-align: center }\ncaption { text-align: center }\nh1, h2, h3, h4, h5, h6, b, strong { font-weight: bolder }\ni, cite, em, var,address { font-style: italic }\npre, code, kbd, pre { white-space: pre }\nbig { font-size: larger}\nsmall { font-size: smaller}\nhr { border: 1px inset }\nol { list-style-type: decimal }\nu { text-decoration: underline }"
},
{
"code": null,
"e": 67749,
"s": 67557,
"text": "Here is link to a complete list of all the WML2 elements. Most of the elements are available in XHTML specification except few elements starting with WML: These elements are specific to WML."
},
{
"code": null,
"e": 67830,
"s": 67749,
"text": "All the elements having same meaning here what they have in XHTML specification."
},
{
"code": null,
"e": 67922,
"s": 67830,
"text": "We can conclude that if you know XHTML and WML1.0 then you have nothing to do learn WML2.0"
},
{
"code": null,
"e": 68032,
"s": 67922,
"text": "If you are interested for further reading then here you can find complete specification for WAP2.0 and WML2.0"
},
{
"code": null,
"e": 68146,
"s": 68032,
"text": "WML entities are to represent symbols that either can't easily be typed in or that have a special meaning in WML."
},
{
"code": null,
"e": 68340,
"s": 68146,
"text": "For example, if you put a < character into your text normally, the browser thinks it's the start of a tag; the browser then complains when it can't find the matching > character to end the tag."
},
{
"code": null,
"e": 68703,
"s": 68340,
"text": "Following table displays the three forms of entities in WML. Named entities are something you may be familiar with from HTML: they look like & or <, and they represent a single named character via a mnemonic name. Entities can also be entered in one of two numeric forms (decimal or hexadecimal), allowing you to enter any Unicode character into your WML."
},
{
"code": null,
"e": 68972,
"s": 68703,
"text": "Note that all entities start with an ampersand ( &) and end with a semicolon ( ;). This semicolon is very important: some web pages forget this and cause problems for browsers that want correct HTML. WAP browsers also are likely to be stricter about errors like these."
},
{
"code": null,
"e": 69079,
"s": 68972,
"text": "Following table lists all the valid WML elements. Click over the links to know more detail of that element"
},
{
"code": null,
"e": 69277,
"s": 69079,
"text": "Instead of installing an entire WAP SDK, you can install a WML emulator. An emulator simply lets you view the contents of your WML files as they would be seen on the screen of a WAP-enabled device."
},
{
"code": null,
"e": 69610,
"s": 69277,
"text": "While the emulators do a great job, they are not perfect. Try a few different ones, and you will quickly decide which you like the most. When the time comes to develop a real (commercial) WAP site, you will need to do a lot more testing, first with other SDKs/emulators and then with all the WAP-enabled devices you plan to support."
},
{
"code": null,
"e": 69683,
"s": 69610,
"text": "The following lists some of the WAP emulators that are freely available:"
},
{
"code": null,
"e": 69935,
"s": 69683,
"text": "Klondike WAP Browser: This is produced by Apache Software. Klondike looks a lot like a Web browser and is therefore very easy to use for beginners. You can access local WML files easily. It also supports drag-anddrop, making local file use very easy."
},
{
"code": null,
"e": 70187,
"s": 69935,
"text": "Klondike WAP Browser: This is produced by Apache Software. Klondike looks a lot like a Web browser and is therefore very easy to use for beginners. You can access local WML files easily. It also supports drag-anddrop, making local file use very easy."
},
{
"code": null,
"e": 70450,
"s": 70187,
"text": "Yospace: This is produced by Yospace. WAP developers can use the desktop edition of the emulator to preview WAP applications from their desktop, safe with the knowledge that the emulator provides a reasonably faithful reproduction of the actual handset products."
},
{
"code": null,
"e": 70713,
"s": 70450,
"text": "Yospace: This is produced by Yospace. WAP developers can use the desktop edition of the emulator to preview WAP applications from their desktop, safe with the knowledge that the emulator provides a reasonably faithful reproduction of the actual handset products."
},
{
"code": null,
"e": 70989,
"s": 70713,
"text": "Ericsson R380 Emulator: This is produced by Ericsson. The R380 WAP emulator is intended to be used to test WML applications developed for the WAP browser in the Ericsson R380. The emulator contains the WAP browser and WAP settings functionality that can be found in the R380."
},
{
"code": null,
"e": 71265,
"s": 70989,
"text": "Ericsson R380 Emulator: This is produced by Ericsson. The R380 WAP emulator is intended to be used to test WML applications developed for the WAP browser in the Ericsson R380. The emulator contains the WAP browser and WAP settings functionality that can be found in the R380."
},
{
"code": null,
"e": 71511,
"s": 71265,
"text": "WinWAP : This is produced by Slob-Trot Software. WinWAP is a\nWML browser that works on any computer with 32-bit Windows installed. You can browse WML files locally from your hard drive or the\nInternet with HTTP (as with your normal Web browser)."
},
{
"code": null,
"e": 71757,
"s": 71511,
"text": "WinWAP : This is produced by Slob-Trot Software. WinWAP is a\nWML browser that works on any computer with 32-bit Windows installed. You can browse WML files locally from your hard drive or the\nInternet with HTTP (as with your normal Web browser)."
},
{
"code": null,
"e": 71869,
"s": 71757,
"text": "Nokia WAP simulator - This is produced by Nokia and fully loaded with almost all functionalities. Try this one."
},
{
"code": null,
"e": 71981,
"s": 71869,
"text": "Nokia WAP simulator - This is produced by Nokia and fully loaded with almost all functionalities. Try this one."
},
{
"code": null,
"e": 72103,
"s": 71981,
"text": "Copy and paste WML content in the following box and then click Validate WML to see the result at the bottom of this page:"
},
{
"code": null,
"e": 72200,
"s": 72103,
"text": "Type your WML page URL and then click Validate WML to see the result at the bottom of this page:"
},
{
"code": null,
"e": 72207,
"s": 72200,
"text": " Print"
},
{
"code": null,
"e": 72218,
"s": 72207,
"text": " Add Notes"
}
] |
Alien Dictionary | Practice | GeeksforGeeks | Given a sorted dictionary of an alien language having N words and k starting alphabets of standard dictionary. Find the order of characters in the alien language.
Note: Many orders may be possible for a particular test case, thus you may return any valid order and output will be 1 if the order of string returned by the function is correct else 0 denoting incorrect string returned.
Example 1:
Input:
N = 5, K = 4
dict = {"baa","abcd","abca","cab","cad"}
Output:
1
Explanation:
Here order of characters is
'b', 'd', 'a', 'c' Note that words are sorted
and in the given language "baa" comes before
"abcd", therefore 'b' is before 'a' in output.
Similarly we can find other orders.
Example 2:
Input:
N = 3, K = 3
dict = {"caa","aaa","aab"}
Output:
1
Explanation:
Here order of characters is
'c', 'a', 'b' Note that words are sorted
and in the given language "caa" comes before
"aaa", therefore 'c' is before 'a' in output.
Similarly we can find other orders.
Your Task:
You don't need to read or print anything. Your task is to complete the function findOrder() which takes the string array dict[], its size N and the integer K as input parameter and returns a string denoting the order of characters in the alien language.
Expected Time Complexity: O(N * |S| + K) , where |S| denotes maximum length.
Expected Space Compelxity: O(K)
Constraints:
1 ≤ N, M ≤ 300
1 ≤ K ≤ 26
1 ≤ Length of words ≤ 50
0
neeshumaini551 day ago
class Solution:
def findOrder(self,dict, N, K):
# adjacency list for storing the key-value pair
# of char in order of the list
adj = {c:set() for w in dict for c in w}
for i in range(len(dict)-1):
w1, w2 = dict[i], dict[i+1]
minLen = min(len(w1), len(w2))
if len(w1) > len(w2) and w1[:minLen] == w2[:minLen]:
return ""
for j in range(minLen):
if w1[j] != w2[j]:
adj[w1[j]].add(w2[j])
break
# postorder depth frist search
visit = {}
res = []
def dfs(c):
if c in visit:
return visit[c]
visit[c] = True
for nei in adj[c]:
if dfs(nei):
return True
visit[c] = False
res.append(c)
for c in adj:
if dfs(c):
return ""
#print(adj)
res.reverse()
return ''.join(res)
0
lindan1236 days ago
void dfs(int i,vector<int>adj[] , vector<int>&vis,stack<int>&st){
vis[i]=1;
for(auto x : adj[i]){
if(vis[x]==0){
dfs(x,adj,vis,st);
}
}
st.push(i);
}
string findOrder(string dict[], int n, int k) {
vector<int> vec[k];
for(int i=0;i<n-1;i++)
{
string s1 = dict[i];
string s2 = dict[i+1];
int m = min(s1.length(),s2.length());
for(int j=0;j<m;j++)
{
if(s1[j]!=s2[j])
{
vec[s1[j]-'a'].push_back(s2[j]-'a');
break;
}
}
}
string ans = "";
stack<int> st;
vector<int> visited(k,0);
for(int i=0;i<k;i++)
{
if(visited[i]==0)
{
dfs(i,vec,visited,st);
}
}
while(!st.empty())
{
char c = st.top() + 'a';
ans = ans + c;
st.pop();
}
return ans;
}
Time Taken : 0.29
Cpp
0
getkar1286 days ago
def findOrder(self,dict, N, K):
# code here
adj = {c:set() for w in dict for c in w}
for i in range(len(dict)-1):
w1, w2 = dict[i], dict[i+1]
minLen = min(len(w1), len(w2))
if len(w1) > len(w2) and w1[:minLen] == w2[:minLen]:
return ""
for j in range(minLen):
if w1[j] != w2[j]:
adj[w1[j]].add(w2[j])
break
visit = {}
res = []
def dfs(c):
if c in visit:
return visit[c]
visit[c] = True
for nei in adj[c]:
if dfs(nei):
return True
visit[c] = False
res.append(c)
for c in adj:
if dfs(c):
return ""
res.reverse()
return ''.join(res)
0
akashrajoria2501031 week ago
Can anyone tell me why my code isnt working?
class Solution{ public String findOrder(String [] dict, int n, int k) { ArrayList<Integer>[] adj = new ArrayList[n]; for (int i = 0; i < adj.length; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < n-1; i++) { String w1 = dict[i]; String w2 = dict[i+1]; for (int j = 0; j < Math.min(w1.length(),w2.length()); j++) { if(w1.charAt(j)!=w2.charAt(j)){ adj[w1.charAt(j)-'a'].add(w2.charAt(j)-'a'); break; } } } boolean[] visited = new boolean[n]; String ans = ""; Stack<Character> s = new Stack<>(); for (int i = 0; i < k; i++) { if(!visited[i]){ dfs(i,adj,visited,s); } } while(!s.isEmpty()){ ans+= (char)(s.pop() + 'a'); } return ans; } static void dfs(int cur,ArrayList<Integer>[] adj, boolean[] visited,Stack<Character> s){ visited[cur] = true; for( int i : adj[cur]){ if(!visited[i]){ dfs(i, adj, visited, s); } } s.push((char) (cur + 'a')); }}
0
joyrockok2 weeks ago
class Solution{ArrayList<Integer> linkedList[];Stack<Integer> stack;boolean visit[]; public String findOrder(String [] dict, int N, int K) { // Write your code here linkedList = new ArrayList[K]; stack = new Stack<Integer>(); visit = new boolean[K]; for(int i=0; i<K; i++) { linkedList[i] = new ArrayList<Integer>(); visit[i]=false; } for(int i=0; i<N-1; i++) { String str1 = dict[i]; String str2 = dict[i+1]; int min = Math.min(str1.length(), str2.length()); for(int j=0; j<min; j++) { if(str1.charAt(j) != str2.charAt(j)) { linkedList[str1.charAt(j)-'a'].add(str2.charAt(j)-'a'); break; } } } makeOrder(K); String str=""; while(stack.isEmpty() != true) { str = str + (char)(stack.pop()+'a'); } return str; } public void makeOrderWords(int alpha) { visit[alpha] = true; for(Integer al : linkedList[alpha]) { if(visit[al] == false) makeOrderWords(al); } stack.add(alpha); } public void makeOrder(int K) { for(int i=0; i<K; i++) { if(visit[i] == false) makeOrderWords(i); } }}
+1
shyamprakash8072 weeks ago
Python solution using Khan's Algorithm(Topology sort):
Time Taken : 0.78 / 2.61
from collections import dequeclass Solution: def findOrder(self,d, N, K): # code here g = [[] for i in range(K)] for i in range(n-1): s1 = d[i] s2 = d[i+1] j = 0 while j < len(s1) and j < len(s2): if s1[j] != s2[j]: g[ord(s1[j])-97].append(ord(s2[j])-97) break j += 1 indeg = [0 for i in range(K)] for i in range(K): for j in g[i]: indeg[j] += 1 q = deque() st = [] for i in range(K): if indeg[i] == 0: q.append(i) while len(q): curr = q.popleft() st.append(chr(curr+97)) for adj in g[curr]: indeg[adj] -= 1 if indeg[adj] == 0: q.append(adj) return st
0
rainx3 weeks ago
Simple Topla karna hai....
void DFSRec(list<int> adj[], int u, stack<int> &st, vector<bool> &visited){
visited[u] = true;
for(auto v: adj[u]){
if(visited[v]==false){
DFSRec(adj, v, st, visited);
}
}
st.push(u);
}
string topologicalSort(list<int> adj[], int V){
stack<int> st;
vector<bool> visited(V, false);
for(int v=0; v < V; v++){
if(visited[v]==false){
DFSRec(adj,v,st,visited);
}
}
string res;
while(st.empty() == false){
res += st.top() + 'a';
st.pop();
}
return res;
}
string findOrder(string words[], int N, int K) {
list<int> adj[K];
for(int i=0;i<N-1;i++){
string word1=words[i];
string word2=words[i+1];
for(int j=0;j<min(word1.size(),word2.size());j++){
if(word1[j]!=word2[j]){
int index1=word1[j]-'a';
int index2=word2[j]-'a';
adj[index1].push_back(index2);
break;
}
}
}
return topologicalSort(adj, K);
}
0
patildhiren443 weeks ago
JAVA - 1.4
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
void addEdge(int src, int tar) {
adj.get(src).add(tar);
}
void topo(int src, ArrayList<ArrayList<Integer>> adj, boolean[] visit, Stack<Integer> st) {
visit[src] = true;
for (int it : adj.get(src)) {
if (!visit[it]) {
topo(it, adj, visit, st);
}
}
st.push(src);
}
public String findOrder(String [] dic, int n, int k){
for (int i = 0; i < k; i++) {
adj.add(new ArrayList<>());
}
for (int i = 0; i < n - 1; i++) {
String s1 = dic[i];
String s2 = dic[i + 1];
for (int j = 0; j < Math.min(s1.length(), s2.length()); j++) {
if (s1.charAt(j) != s2.charAt(j)) {
addEdge(s1.charAt(j) - 'a', s2.charAt(j) - 'a');
break;
}
}
}
boolean[] visit = new boolean[k];
Stack<Integer> st = new Stack<>();
for (int i = 0; i < k; i++) {
if (!visit[i]) {
topo(i, adj, visit, st);
}
}
String s="";
while(!st.isEmpty()){
int temp = st.pop()+'a';
s += (char)temp;
}
// System.out.println(s);
return s;
}
+1
bhaskarmaheshwari83 weeks ago
class Graph{ int V; vector<int> *adj; public: Graph(int V) { this->V=V; adj=new vector<int>[V]; } void addEdge(int u,int v) { adj[u].push_back(v); } void dfs(int src,vector<int>&vis,stack<int> &s) { vis[src]=1; for(auto itr:adj[src]) { if(!vis[itr]) { dfs(itr,vis,s); } } s.push(src); }};class Solution{ public: string findOrder(string dict[], int n, int K) { //code here Graph g(K); for(int i=0;i<n-1;i++) { string str1=dict[i]; string str2=dict[i+1]; for(int j=0,k=0;j<str1.size()&&k<str2.size();j++,k++) { if(str1[j]==str2[k]) continue; else{ g.addEdge(str1[j]-'a',str2[k]-'a'); break; } } } vector<int> vis(K,0); stack<int> s; for (int i = 0; i < K; i++) if (!vis[i]) g.dfs(i,vis,s); string str=""; while(!s.empty()) { str+=s.top()+'a'; s.pop(); } // return str; // cout<<str; return str; }
0
milindprajapatmst193 weeks ago
0.3/1.8
class Solution{
public:
int cnt[26];
queue<int> q;
vector<int> edges[26];
string findOrder(string dict[], int n, int k) {
memset(cnt, 0, sizeof(cnt));
for (int i = 1; i < n; i++) {
int k1 = 0, k2 = 0;
while (k1 < dict[i - 1].length() && k2 < dict[i].length()) {
if (dict[i - 1][k1] != dict[i][k2]) {
k1 = dict[i - 1][k1] - 'a';
k2 = dict[i][k2] - 'a';
cnt[k2]++;
edges[k1].push_back(k2);
break;
}
k1++; k2++;
}
}
for (int u = 0; u < k; u++) {
if (cnt[u] == 0)
q.push(u);
}
string result = "";
while (!q.empty()) {
int u = q.front();
q.pop();
for (int v : edges[u]) {
cnt[v]--;
if (cnt[v] == 0)
q.push(v);
}
char ch = u + 'a';
result += ch;
}
return result;
}
};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 624,
"s": 238,
"text": "Given a sorted dictionary of an alien language having N words and k starting alphabets of standard dictionary. Find the order of characters in the alien language.\nNote: Many orders may be possible for a particular test case, thus you may return any valid order and output will be 1 if the order of string returned by the function is correct else 0 denoting incorrect string returned.\n "
},
{
"code": null,
"e": 635,
"s": 624,
"text": "Example 1:"
},
{
"code": null,
"e": 925,
"s": 635,
"text": "Input: \nN = 5, K = 4\ndict = {\"baa\",\"abcd\",\"abca\",\"cab\",\"cad\"}\nOutput:\n1\nExplanation:\nHere order of characters is \n'b', 'd', 'a', 'c' Note that words are sorted \nand in the given language \"baa\" comes before \n\"abcd\", therefore 'b' is before 'a' in output.\nSimilarly we can find other orders."
},
{
"code": null,
"e": 936,
"s": 925,
"text": "Example 2:"
},
{
"code": null,
"e": 1204,
"s": 936,
"text": "Input: \nN = 3, K = 3\ndict = {\"caa\",\"aaa\",\"aab\"}\nOutput:\n1\nExplanation:\nHere order of characters is\n'c', 'a', 'b' Note that words are sorted\nand in the given language \"caa\" comes before\n\"aaa\", therefore 'c' is before 'a' in output.\nSimilarly we can find other orders.\n"
},
{
"code": null,
"e": 1472,
"s": 1206,
"text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function findOrder() which takes the string array dict[], its size N and the integer K as input parameter and returns a string denoting the order of characters in the alien language."
},
{
"code": null,
"e": 1582,
"s": 1472,
"text": "\nExpected Time Complexity: O(N * |S| + K) , where |S| denotes maximum length.\nExpected Space Compelxity: O(K)"
},
{
"code": null,
"e": 1647,
"s": 1582,
"text": "\nConstraints:\n1 ≤ N, M ≤ 300\n1 ≤ K ≤ 26\n1 ≤ Length of words ≤ 50"
},
{
"code": null,
"e": 1649,
"s": 1647,
"text": "0"
},
{
"code": null,
"e": 1672,
"s": 1649,
"text": "neeshumaini551 day ago"
},
{
"code": null,
"e": 2658,
"s": 1672,
"text": "class Solution:\n \tdef findOrder(self,dict, N, K):\n # adjacency list for storing the key-value pair\n # of char in order of the list\n \tadj = {c:set() for w in dict for c in w}\n for i in range(len(dict)-1):\n w1, w2 = dict[i], dict[i+1]\n minLen = min(len(w1), len(w2))\n if len(w1) > len(w2) and w1[:minLen] == w2[:minLen]:\n \treturn \"\"\n for j in range(minLen):\n \tif w1[j] != w2[j]:\n \tadj[w1[j]].add(w2[j])\n \tbreak\n # postorder depth frist search\n \tvisit = {}\n \tres = []\n \tdef dfs(c):\n \tif c in visit:\n \treturn visit[c]\n \tvisit[c] = True\n \tfor nei in adj[c]:\n \tif dfs(nei):\n \treturn True\n \tvisit[c] = False\n \tres.append(c)\n \n \tfor c in adj:\n \tif dfs(c):\n \treturn \"\"\n \t#print(adj)\n \tres.reverse()\n \treturn ''.join(res)"
},
{
"code": null,
"e": 2660,
"s": 2658,
"text": "0"
},
{
"code": null,
"e": 2680,
"s": 2660,
"text": "lindan1236 days ago"
},
{
"code": null,
"e": 3862,
"s": 2680,
"text": "void dfs(int i,vector<int>adj[] , vector<int>&vis,stack<int>&st){\n vis[i]=1;\n \n for(auto x : adj[i]){\n if(vis[x]==0){\n dfs(x,adj,vis,st);\n }\n }\n \n st.push(i);\n \n }\n \n string findOrder(string dict[], int n, int k) {\n vector<int> vec[k];\n \n for(int i=0;i<n-1;i++)\n {\n string s1 = dict[i];\n string s2 = dict[i+1];\n \n int m = min(s1.length(),s2.length());\n for(int j=0;j<m;j++)\n {\n if(s1[j]!=s2[j])\n {\n vec[s1[j]-'a'].push_back(s2[j]-'a');\n \n break;\n }\n }\n }\n \n string ans = \"\";\n stack<int> st;\n vector<int> visited(k,0);\n for(int i=0;i<k;i++)\n {\n if(visited[i]==0)\n {\n dfs(i,vec,visited,st);\n }\n \n }\n \n while(!st.empty())\n {\n char c = st.top() + 'a';\n ans = ans + c;\n st.pop();\n }\n return ans;\n }"
},
{
"code": null,
"e": 3880,
"s": 3862,
"text": "Time Taken : 0.29"
},
{
"code": null,
"e": 3884,
"s": 3880,
"text": "Cpp"
},
{
"code": null,
"e": 3886,
"s": 3884,
"text": "0"
},
{
"code": null,
"e": 3906,
"s": 3886,
"text": "getkar1286 days ago"
},
{
"code": null,
"e": 4749,
"s": 3906,
"text": "def findOrder(self,dict, N, K):\n # code here\n adj = {c:set() for w in dict for c in w}\n for i in range(len(dict)-1):\n w1, w2 = dict[i], dict[i+1]\n minLen = min(len(w1), len(w2))\n if len(w1) > len(w2) and w1[:minLen] == w2[:minLen]:\n return \"\"\n for j in range(minLen):\n if w1[j] != w2[j]:\n adj[w1[j]].add(w2[j])\n break\n visit = {}\n res = []\n def dfs(c):\n if c in visit:\n return visit[c]\n visit[c] = True\n for nei in adj[c]:\n if dfs(nei):\n return True\n visit[c] = False\n res.append(c)\n \n for c in adj:\n if dfs(c):\n return \"\"\n res.reverse()\n return ''.join(res)\n "
},
{
"code": null,
"e": 4751,
"s": 4749,
"text": "0"
},
{
"code": null,
"e": 4780,
"s": 4751,
"text": "akashrajoria2501031 week ago"
},
{
"code": null,
"e": 4825,
"s": 4780,
"text": "Can anyone tell me why my code isnt working?"
},
{
"code": null,
"e": 5989,
"s": 4825,
"text": "class Solution{ public String findOrder(String [] dict, int n, int k) { ArrayList<Integer>[] adj = new ArrayList[n]; for (int i = 0; i < adj.length; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < n-1; i++) { String w1 = dict[i]; String w2 = dict[i+1]; for (int j = 0; j < Math.min(w1.length(),w2.length()); j++) { if(w1.charAt(j)!=w2.charAt(j)){ adj[w1.charAt(j)-'a'].add(w2.charAt(j)-'a'); break; } } } boolean[] visited = new boolean[n]; String ans = \"\"; Stack<Character> s = new Stack<>(); for (int i = 0; i < k; i++) { if(!visited[i]){ dfs(i,adj,visited,s); } } while(!s.isEmpty()){ ans+= (char)(s.pop() + 'a'); } return ans; } static void dfs(int cur,ArrayList<Integer>[] adj, boolean[] visited,Stack<Character> s){ visited[cur] = true; for( int i : adj[cur]){ if(!visited[i]){ dfs(i, adj, visited, s); } } s.push((char) (cur + 'a')); }}"
},
{
"code": null,
"e": 5991,
"s": 5989,
"text": "0"
},
{
"code": null,
"e": 6012,
"s": 5991,
"text": "joyrockok2 weeks ago"
},
{
"code": null,
"e": 7186,
"s": 6012,
"text": "class Solution{ArrayList<Integer> linkedList[];Stack<Integer> stack;boolean visit[]; public String findOrder(String [] dict, int N, int K) { // Write your code here linkedList = new ArrayList[K]; stack = new Stack<Integer>(); visit = new boolean[K]; for(int i=0; i<K; i++) { linkedList[i] = new ArrayList<Integer>(); visit[i]=false; } for(int i=0; i<N-1; i++) { String str1 = dict[i]; String str2 = dict[i+1]; int min = Math.min(str1.length(), str2.length()); for(int j=0; j<min; j++) { if(str1.charAt(j) != str2.charAt(j)) { linkedList[str1.charAt(j)-'a'].add(str2.charAt(j)-'a'); break; } } } makeOrder(K); String str=\"\"; while(stack.isEmpty() != true) { str = str + (char)(stack.pop()+'a'); } return str; } public void makeOrderWords(int alpha) { visit[alpha] = true; for(Integer al : linkedList[alpha]) { if(visit[al] == false) makeOrderWords(al); } stack.add(alpha); } public void makeOrder(int K) { for(int i=0; i<K; i++) { if(visit[i] == false) makeOrderWords(i); } }}"
},
{
"code": null,
"e": 7189,
"s": 7186,
"text": "+1"
},
{
"code": null,
"e": 7216,
"s": 7189,
"text": "shyamprakash8072 weeks ago"
},
{
"code": null,
"e": 7271,
"s": 7216,
"text": "Python solution using Khan's Algorithm(Topology sort):"
},
{
"code": null,
"e": 7296,
"s": 7271,
"text": "Time Taken : 0.78 / 2.61"
},
{
"code": null,
"e": 8139,
"s": 7298,
"text": "from collections import dequeclass Solution: def findOrder(self,d, N, K): # code here g = [[] for i in range(K)] for i in range(n-1): s1 = d[i] s2 = d[i+1] j = 0 while j < len(s1) and j < len(s2): if s1[j] != s2[j]: g[ord(s1[j])-97].append(ord(s2[j])-97) break j += 1 indeg = [0 for i in range(K)] for i in range(K): for j in g[i]: indeg[j] += 1 q = deque() st = [] for i in range(K): if indeg[i] == 0: q.append(i) while len(q): curr = q.popleft() st.append(chr(curr+97)) for adj in g[curr]: indeg[adj] -= 1 if indeg[adj] == 0: q.append(adj) return st "
},
{
"code": null,
"e": 8141,
"s": 8139,
"text": "0"
},
{
"code": null,
"e": 8158,
"s": 8141,
"text": "rainx3 weeks ago"
},
{
"code": null,
"e": 8185,
"s": 8158,
"text": "Simple Topla karna hai...."
},
{
"code": null,
"e": 9394,
"s": 8185,
"text": "void DFSRec(list<int> adj[], int u, stack<int> &st, vector<bool> &visited){\n visited[u] = true;\n for(auto v: adj[u]){\n if(visited[v]==false){\n DFSRec(adj, v, st, visited);\n }\n }\n st.push(u);\n }\n \n string topologicalSort(list<int> adj[], int V){\n stack<int> st;\n vector<bool> visited(V, false);\n for(int v=0; v < V; v++){\n if(visited[v]==false){\n DFSRec(adj,v,st,visited);\n }\n }\n string res;\n while(st.empty() == false){\n res += st.top() + 'a';\n st.pop();\n }\n return res;\n }\n \n string findOrder(string words[], int N, int K) {\n list<int> adj[K];\n for(int i=0;i<N-1;i++){\n string word1=words[i];\n string word2=words[i+1];\n for(int j=0;j<min(word1.size(),word2.size());j++){\n if(word1[j]!=word2[j]){\n int index1=word1[j]-'a';\n int index2=word2[j]-'a';\n adj[index1].push_back(index2);\n break;\n }\n }\n }\n return topologicalSort(adj, K);\n}"
},
{
"code": null,
"e": 9396,
"s": 9394,
"text": "0"
},
{
"code": null,
"e": 9421,
"s": 9396,
"text": "patildhiren443 weeks ago"
},
{
"code": null,
"e": 9432,
"s": 9421,
"text": "JAVA - 1.4"
},
{
"code": null,
"e": 10813,
"s": 9432,
"text": "ArrayList<ArrayList<Integer>> adj = new ArrayList<>();\n\n void addEdge(int src, int tar) {\n adj.get(src).add(tar);\n }\n\n void topo(int src, ArrayList<ArrayList<Integer>> adj, boolean[] visit, Stack<Integer> st) {\n visit[src] = true;\n\n for (int it : adj.get(src)) {\n if (!visit[it]) {\n topo(it, adj, visit, st);\n }\n }\n st.push(src);\n }\n\n \n public String findOrder(String [] dic, int n, int k){\n \n for (int i = 0; i < k; i++) {\n adj.add(new ArrayList<>());\n }\n \n for (int i = 0; i < n - 1; i++) {\n String s1 = dic[i];\n String s2 = dic[i + 1];\n\n for (int j = 0; j < Math.min(s1.length(), s2.length()); j++) {\n if (s1.charAt(j) != s2.charAt(j)) {\n addEdge(s1.charAt(j) - 'a', s2.charAt(j) - 'a');\n break;\n }\n }\n }\n\n boolean[] visit = new boolean[k];\n Stack<Integer> st = new Stack<>();\n\n for (int i = 0; i < k; i++) {\n if (!visit[i]) {\n topo(i, adj, visit, st);\n }\n }\n \n String s=\"\";\n while(!st.isEmpty()){\n int temp = st.pop()+'a';\n s += (char)temp;\n }\n // System.out.println(s);\n return s;\n }"
},
{
"code": null,
"e": 10816,
"s": 10813,
"text": "+1"
},
{
"code": null,
"e": 10846,
"s": 10816,
"text": "bhaskarmaheshwari83 weeks ago"
},
{
"code": null,
"e": 12143,
"s": 10846,
"text": "class Graph{ int V; vector<int> *adj; public: Graph(int V) { this->V=V; adj=new vector<int>[V]; } void addEdge(int u,int v) { adj[u].push_back(v); } void dfs(int src,vector<int>&vis,stack<int> &s) { vis[src]=1; for(auto itr:adj[src]) { if(!vis[itr]) { dfs(itr,vis,s); } } s.push(src); }};class Solution{ public: string findOrder(string dict[], int n, int K) { //code here Graph g(K); for(int i=0;i<n-1;i++) { string str1=dict[i]; string str2=dict[i+1]; for(int j=0,k=0;j<str1.size()&&k<str2.size();j++,k++) { if(str1[j]==str2[k]) continue; else{ g.addEdge(str1[j]-'a',str2[k]-'a'); break; } } } vector<int> vis(K,0); stack<int> s; for (int i = 0; i < K; i++) if (!vis[i]) g.dfs(i,vis,s); string str=\"\"; while(!s.empty()) { str+=s.top()+'a'; s.pop(); } // return str; // cout<<str; return str; }"
},
{
"code": null,
"e": 12145,
"s": 12143,
"text": "0"
},
{
"code": null,
"e": 12176,
"s": 12145,
"text": "milindprajapatmst193 weeks ago"
},
{
"code": null,
"e": 12184,
"s": 12176,
"text": "0.3/1.8"
},
{
"code": null,
"e": 13280,
"s": 12186,
"text": "class Solution{\n public:\n int cnt[26];\n queue<int> q;\n vector<int> edges[26];\n string findOrder(string dict[], int n, int k) {\n memset(cnt, 0, sizeof(cnt));\n for (int i = 1; i < n; i++) {\n int k1 = 0, k2 = 0;\n while (k1 < dict[i - 1].length() && k2 < dict[i].length()) {\n if (dict[i - 1][k1] != dict[i][k2]) {\n k1 = dict[i - 1][k1] - 'a';\n k2 = dict[i][k2] - 'a';\n cnt[k2]++;\n edges[k1].push_back(k2);\n break;\n }\n k1++; k2++;\n }\n }\n for (int u = 0; u < k; u++) {\n if (cnt[u] == 0)\n q.push(u);\n }\n string result = \"\";\n while (!q.empty()) {\n int u = q.front();\n q.pop();\n for (int v : edges[u]) {\n cnt[v]--;\n if (cnt[v] == 0)\n q.push(v);\n }\n char ch = u + 'a';\n result += ch;\n }\n return result;\n }\n};"
},
{
"code": null,
"e": 13426,
"s": 13280,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 13462,
"s": 13426,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 13472,
"s": 13462,
"text": "\nProblem\n"
},
{
"code": null,
"e": 13482,
"s": 13472,
"text": "\nContest\n"
},
{
"code": null,
"e": 13545,
"s": 13482,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 13693,
"s": 13545,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 13901,
"s": 13693,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 14007,
"s": 13901,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Log functions in Java | The log functions in Java are part of java.lang.Math. The functions include log, log10, log1p. Let us see an example of each of these log functions −
static double log(double a)
The java.lang.Math.log(double a) returns the natural logarithm (base e) of a double value. Let us see an example −
import java.io.*;
public class Main {
public static void main(String args[]) {
// get two double numbers
double x = 60984.1;
double y = -497.99;
// get the natural logarithm for x
System.out.println("Math.log(" + x + ")=" + Math.log(x));
// get the natural logarithm for y
System.out.println("Math.log(" + y + ")=" + Math.log(y));
}
}
Math.log(60984.1)=11.018368453441132
Math.log(-497.99)=NaN
static double log10(double a)
The java.lang.Math.log10(double a) returns the base 10 logarithm of a double value. Let us now see an example −
import java.io.*;
public class Main {
public static void main(String args[]) {
// get two double numbers
double x = 60984.1;
double y = 1000;
// get the base 10 logarithm for x
System.out.println("Math.log10(" + x + ")=" + Math.log10(x));
// get the base 10 logarithm for y
System.out.println("Math.log10(" + y + ")=" + Math.log10(y));
}
}
Math.log10(60984.1)=4.78521661890635
Math.log10(1000.0)=3.0
static double log1p(double x)
The java.lang.Math.log1p(double x) returns the natural logarithm of the sum of the argument and 1.
import java.io.*;
public class Main {
public static void main(String args[]) {
// get two double numbers
double x = 60984.1;
double y = 1000;
// call log1p and print the result
System.out.println("Math.log1p(" + x + ")=" + Math.log1p(x));
// call log1p and print the result
System.out.println("Math.log1p(" + y + ")=" + Math.log1p(y));
}
}
Math.log1p(60984.1)=11.018384851023473
Math.log1p(1000.0)=6.90875477931522 | [
{
"code": null,
"e": 1212,
"s": 1062,
"text": "The log functions in Java are part of java.lang.Math. The functions include log, log10, log1p. Let us see an example of each of these log functions −"
},
{
"code": null,
"e": 1240,
"s": 1212,
"text": "static double log(double a)"
},
{
"code": null,
"e": 1355,
"s": 1240,
"text": "The java.lang.Math.log(double a) returns the natural logarithm (base e) of a double value. Let us see an example −"
},
{
"code": null,
"e": 1738,
"s": 1355,
"text": "import java.io.*;\npublic class Main {\n public static void main(String args[]) {\n // get two double numbers\n double x = 60984.1;\n double y = -497.99;\n // get the natural logarithm for x\n System.out.println(\"Math.log(\" + x + \")=\" + Math.log(x));\n // get the natural logarithm for y\n System.out.println(\"Math.log(\" + y + \")=\" + Math.log(y));\n }\n}"
},
{
"code": null,
"e": 1797,
"s": 1738,
"text": "Math.log(60984.1)=11.018368453441132\nMath.log(-497.99)=NaN"
},
{
"code": null,
"e": 1827,
"s": 1797,
"text": "static double log10(double a)"
},
{
"code": null,
"e": 1939,
"s": 1827,
"text": "The java.lang.Math.log10(double a) returns the base 10 logarithm of a double value. Let us now see an example −"
},
{
"code": null,
"e": 2327,
"s": 1939,
"text": "import java.io.*;\npublic class Main {\n public static void main(String args[]) {\n // get two double numbers\n double x = 60984.1;\n double y = 1000;\n // get the base 10 logarithm for x\n System.out.println(\"Math.log10(\" + x + \")=\" + Math.log10(x));\n // get the base 10 logarithm for y\n System.out.println(\"Math.log10(\" + y + \")=\" + Math.log10(y));\n }\n}"
},
{
"code": null,
"e": 2387,
"s": 2327,
"text": "Math.log10(60984.1)=4.78521661890635\nMath.log10(1000.0)=3.0"
},
{
"code": null,
"e": 2417,
"s": 2387,
"text": "static double log1p(double x)"
},
{
"code": null,
"e": 2516,
"s": 2417,
"text": "The java.lang.Math.log1p(double x) returns the natural logarithm of the sum of the argument and 1."
},
{
"code": null,
"e": 2904,
"s": 2516,
"text": "import java.io.*;\npublic class Main {\n public static void main(String args[]) {\n // get two double numbers\n double x = 60984.1;\n double y = 1000;\n // call log1p and print the result\n System.out.println(\"Math.log1p(\" + x + \")=\" + Math.log1p(x));\n // call log1p and print the result\n System.out.println(\"Math.log1p(\" + y + \")=\" + Math.log1p(y));\n }\n}"
},
{
"code": null,
"e": 2979,
"s": 2904,
"text": "Math.log1p(60984.1)=11.018384851023473\nMath.log1p(1000.0)=6.90875477931522"
}
] |
Basic fault tolerant software techniques - GeeksforGeeks | 08 Oct, 2018
The study of software fault-tolerance is relatively new as compared with the study of fault-tolerant hardware. In general, fault-tolerant approaches can be classified into fault-removal and fault-masking approaches. Fault-removal techniques can be either forward error recovery or backward error recovery.
Forward error recovery aims to identify the error and, based on this knowledge, correct the system state containing the error. Exception handling in high-level languages, such as Ada and PL/1, provides a system structure that supports forward recovery. Backward error recovery corrects the system state by restoring the system to a state which occurred prior to the manifestation of the fault. The recovery block scheme provides such a system structure. Another fault-tolerant software technique commonly used is error masking. The NVP scheme uses several independently developed versions of an algorithm. A final voting system is applied to the results of these N-versions and a correct result is generated.
A fundamental way of improving the reliability of software systems depends on the principle of design diversity where different versions of the functions are implemented. In order to prevent software failure caused by unpredicted conditions, different programs (alternative programs) are developed separately, preferably based on different programming logic, algorithm, computer language, etc. This diversity is normally applied under the form of recovery blocks or N-version programming.
Fault-tolerant software assures system reliability by using protective redundancy at the software level. There are two basic techniques for obtaining fault-tolerant software: RB scheme and NVP. Both schemes are based on software redundancy assuming that the events of coincidental software failures are rare.
Recovery Block Scheme –The recovery block scheme consists of three elements: primary module, acceptance tests, and alternate modules for a given task. The simplest scheme of the recovery block is as follows:Ensure T
By P
Else by Q1
Else by Q2
.
.
.
Else by Qn-1
Else Error Where T is an acceptance test condition that is expected to be met by successful execution of either the primary module P or the alternate modules Q1, Q2, . . ., Qn-1.The process begins when the output of the primary module is tested for acceptability. If the acceptance test determines that the output of the primary module is not acceptable, it recovers or rolls back the state of the system before the primary module is executed. It allows the second module Q1, to execute. The acceptance test is repeated to check the successful execution of module Q1. If it fails, then module Q2 is executed, etc.The alternate modules are identified by the keywords “else by” When all alternate modules are exhausted, the recovery block itself is considered to have failed and the final keywords “else error” declares the fact. In other words, when all modules execute and none produce acceptable outputs, then the system falls. A reliability optimization model has been studied by Pham (1989b) to determine the optimal number of modules in a recovery block scheme that minimizes the total system cost given the reliability of the individual modules.In a recovery block, a programming function is realized by n alternative programs, P1, P2, . . . ., Pn. The computational result generated by each alternative program is checked by an acceptance test, T. If the result is rejected, another alternative program is then executed. The program will be repeated until an acceptable result is generated by one of the n alternatives or until all the alternative programs fail.The probability of failure of the RB scheme, , is as follows: where = probability of failure for version Pi = probability that acceptance test i judges an incorrect result as correctt = probability that acceptance test i judges a correct result as incorrect.The above equation corresponds to the case when all versions fall the acceptance test. The second term corresponds to the probability that acceptance test i judges an incorrect result as correct at the ith trial of the n versions.N-version Programming –NVP is used for providing fault-tolerance in software. In concept, the NVP scheme is similar to the N-modular redundancy scheme used to provide tolerance against hardware faults.The NVP is defined as the independent generation of functionally equivalent programs, called versions, from the same initial specification. Independent generation of programs means that the programming efforts are carried out by N individuals or groups that do not interact with respect to the programming process. Whenever possible, different algorithms, techniques, programming languages, environments, and tools are used in each effort. In this technique, N program versions are executed in parallel on identical input and the results are obtained by voting on the outputs from the individual programs. The advantage of NVP is that when a version failure occurs, no additional time is required for reconfiguring the system and redoing the computation.Consider an NVP scheme consists of n programs and a voting mechanism, V. As opposed to the RB approach, all n alternative programs are usually executed simultaneously and their results are sent to a decision mechanism which selects the final result. The decision mechanism is normally a voter when there are more than two versions (or, more than k versions, in general), and it is a comparator when there are only two versions (k versions). The syntactic structure of NVP is as follows:seq
par
P1(version 1)
P2(version 2)
.
.
.
Pn(version n)
decision V Assume that a correct result is expected where there are at least two correct results.The probability of failure of the NVP scheme, Pn, can be expressed as The first term of this equation is the probability that all versions fail. The second term is the probability that only one version is correct. The third term, d, is the probability that there are at least two correct results but the decision algorithm fails to deliver the correct result.It is worthwhile to note that the goal of the NVP approach is to ensure that multiple versions will be unlikely to fail on the same inputs. With each version independently developed by a different programming team, design approach, etc., the goal is that the versions will be different enough in order that they will not fail too often on the same inputs. However, multiversion programming is still a controversial topic.
Recovery Block Scheme –The recovery block scheme consists of three elements: primary module, acceptance tests, and alternate modules for a given task. The simplest scheme of the recovery block is as follows:Ensure T
By P
Else by Q1
Else by Q2
.
.
.
Else by Qn-1
Else Error Where T is an acceptance test condition that is expected to be met by successful execution of either the primary module P or the alternate modules Q1, Q2, . . ., Qn-1.The process begins when the output of the primary module is tested for acceptability. If the acceptance test determines that the output of the primary module is not acceptable, it recovers or rolls back the state of the system before the primary module is executed. It allows the second module Q1, to execute. The acceptance test is repeated to check the successful execution of module Q1. If it fails, then module Q2 is executed, etc.The alternate modules are identified by the keywords “else by” When all alternate modules are exhausted, the recovery block itself is considered to have failed and the final keywords “else error” declares the fact. In other words, when all modules execute and none produce acceptable outputs, then the system falls. A reliability optimization model has been studied by Pham (1989b) to determine the optimal number of modules in a recovery block scheme that minimizes the total system cost given the reliability of the individual modules.In a recovery block, a programming function is realized by n alternative programs, P1, P2, . . . ., Pn. The computational result generated by each alternative program is checked by an acceptance test, T. If the result is rejected, another alternative program is then executed. The program will be repeated until an acceptable result is generated by one of the n alternatives or until all the alternative programs fail.The probability of failure of the RB scheme, , is as follows: where = probability of failure for version Pi = probability that acceptance test i judges an incorrect result as correctt = probability that acceptance test i judges a correct result as incorrect.The above equation corresponds to the case when all versions fall the acceptance test. The second term corresponds to the probability that acceptance test i judges an incorrect result as correct at the ith trial of the n versions.
Ensure T
By P
Else by Q1
Else by Q2
.
.
.
Else by Qn-1
Else Error
Where T is an acceptance test condition that is expected to be met by successful execution of either the primary module P or the alternate modules Q1, Q2, . . ., Qn-1.The process begins when the output of the primary module is tested for acceptability. If the acceptance test determines that the output of the primary module is not acceptable, it recovers or rolls back the state of the system before the primary module is executed. It allows the second module Q1, to execute. The acceptance test is repeated to check the successful execution of module Q1. If it fails, then module Q2 is executed, etc.
The alternate modules are identified by the keywords “else by” When all alternate modules are exhausted, the recovery block itself is considered to have failed and the final keywords “else error” declares the fact. In other words, when all modules execute and none produce acceptable outputs, then the system falls. A reliability optimization model has been studied by Pham (1989b) to determine the optimal number of modules in a recovery block scheme that minimizes the total system cost given the reliability of the individual modules.
In a recovery block, a programming function is realized by n alternative programs, P1, P2, . . . ., Pn. The computational result generated by each alternative program is checked by an acceptance test, T. If the result is rejected, another alternative program is then executed. The program will be repeated until an acceptable result is generated by one of the n alternatives or until all the alternative programs fail.
The probability of failure of the RB scheme, , is as follows:
where = probability of failure for version Pi = probability that acceptance test i judges an incorrect result as correctt = probability that acceptance test i judges a correct result as incorrect.
The above equation corresponds to the case when all versions fall the acceptance test. The second term corresponds to the probability that acceptance test i judges an incorrect result as correct at the ith trial of the n versions.
N-version Programming –NVP is used for providing fault-tolerance in software. In concept, the NVP scheme is similar to the N-modular redundancy scheme used to provide tolerance against hardware faults.The NVP is defined as the independent generation of functionally equivalent programs, called versions, from the same initial specification. Independent generation of programs means that the programming efforts are carried out by N individuals or groups that do not interact with respect to the programming process. Whenever possible, different algorithms, techniques, programming languages, environments, and tools are used in each effort. In this technique, N program versions are executed in parallel on identical input and the results are obtained by voting on the outputs from the individual programs. The advantage of NVP is that when a version failure occurs, no additional time is required for reconfiguring the system and redoing the computation.Consider an NVP scheme consists of n programs and a voting mechanism, V. As opposed to the RB approach, all n alternative programs are usually executed simultaneously and their results are sent to a decision mechanism which selects the final result. The decision mechanism is normally a voter when there are more than two versions (or, more than k versions, in general), and it is a comparator when there are only two versions (k versions). The syntactic structure of NVP is as follows:seq
par
P1(version 1)
P2(version 2)
.
.
.
Pn(version n)
decision V Assume that a correct result is expected where there are at least two correct results.The probability of failure of the NVP scheme, Pn, can be expressed as The first term of this equation is the probability that all versions fail. The second term is the probability that only one version is correct. The third term, d, is the probability that there are at least two correct results but the decision algorithm fails to deliver the correct result.It is worthwhile to note that the goal of the NVP approach is to ensure that multiple versions will be unlikely to fail on the same inputs. With each version independently developed by a different programming team, design approach, etc., the goal is that the versions will be different enough in order that they will not fail too often on the same inputs. However, multiversion programming is still a controversial topic.
The NVP is defined as the independent generation of functionally equivalent programs, called versions, from the same initial specification. Independent generation of programs means that the programming efforts are carried out by N individuals or groups that do not interact with respect to the programming process. Whenever possible, different algorithms, techniques, programming languages, environments, and tools are used in each effort. In this technique, N program versions are executed in parallel on identical input and the results are obtained by voting on the outputs from the individual programs. The advantage of NVP is that when a version failure occurs, no additional time is required for reconfiguring the system and redoing the computation.
Consider an NVP scheme consists of n programs and a voting mechanism, V. As opposed to the RB approach, all n alternative programs are usually executed simultaneously and their results are sent to a decision mechanism which selects the final result. The decision mechanism is normally a voter when there are more than two versions (or, more than k versions, in general), and it is a comparator when there are only two versions (k versions). The syntactic structure of NVP is as follows:
seq
par
P1(version 1)
P2(version 2)
.
.
.
Pn(version n)
decision V
Assume that a correct result is expected where there are at least two correct results.
The probability of failure of the NVP scheme, Pn, can be expressed as
The first term of this equation is the probability that all versions fail. The second term is the probability that only one version is correct. The third term, d, is the probability that there are at least two correct results but the decision algorithm fails to deliver the correct result.
It is worthwhile to note that the goal of the NVP approach is to ensure that multiple versions will be unlikely to fail on the same inputs. With each version independently developed by a different programming team, design approach, etc., the goal is that the versions will be different enough in order that they will not fail too often on the same inputs. However, multiversion programming is still a controversial topic.
The main difference between the recovery block scheme and the N-version programming is that the modules are executed sequentially in the former. The recovery block generally is not applicable to critical systems where real-time response is of great concern.
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Types of Software Testing
Differences between Black Box Testing vs White Box Testing
Functional vs Non Functional Requirements
Software Requirement Specification (SRS) Format
Levels in Data Flow Diagrams (DFD)
Differences between Verification and Validation
DFD for Library Management System
Software Testing | Basics
What is DFD(Data Flow Diagram)?
Difference between IAAS, PAAS and SAAS | [
{
"code": null,
"e": 27300,
"s": 27272,
"text": "\n08 Oct, 2018"
},
{
"code": null,
"e": 27606,
"s": 27300,
"text": "The study of software fault-tolerance is relatively new as compared with the study of fault-tolerant hardware. In general, fault-tolerant approaches can be classified into fault-removal and fault-masking approaches. Fault-removal techniques can be either forward error recovery or backward error recovery."
},
{
"code": null,
"e": 28315,
"s": 27606,
"text": "Forward error recovery aims to identify the error and, based on this knowledge, correct the system state containing the error. Exception handling in high-level languages, such as Ada and PL/1, provides a system structure that supports forward recovery. Backward error recovery corrects the system state by restoring the system to a state which occurred prior to the manifestation of the fault. The recovery block scheme provides such a system structure. Another fault-tolerant software technique commonly used is error masking. The NVP scheme uses several independently developed versions of an algorithm. A final voting system is applied to the results of these N-versions and a correct result is generated."
},
{
"code": null,
"e": 28804,
"s": 28315,
"text": "A fundamental way of improving the reliability of software systems depends on the principle of design diversity where different versions of the functions are implemented. In order to prevent software failure caused by unpredicted conditions, different programs (alternative programs) are developed separately, preferably based on different programming logic, algorithm, computer language, etc. This diversity is normally applied under the form of recovery blocks or N-version programming."
},
{
"code": null,
"e": 29113,
"s": 28804,
"text": "Fault-tolerant software assures system reliability by using protective redundancy at the software level. There are two basic techniques for obtaining fault-tolerant software: RB scheme and NVP. Both schemes are based on software redundancy assuming that the events of coincidental software failures are rare."
},
{
"code": null,
"e": 33878,
"s": 29113,
"text": "Recovery Block Scheme –The recovery block scheme consists of three elements: primary module, acceptance tests, and alternate modules for a given task. The simplest scheme of the recovery block is as follows:Ensure T\n By P\n Else by Q1\n Else by Q2\n .\n .\n .\n Else by Qn-1\n Else Error Where T is an acceptance test condition that is expected to be met by successful execution of either the primary module P or the alternate modules Q1, Q2, . . ., Qn-1.The process begins when the output of the primary module is tested for acceptability. If the acceptance test determines that the output of the primary module is not acceptable, it recovers or rolls back the state of the system before the primary module is executed. It allows the second module Q1, to execute. The acceptance test is repeated to check the successful execution of module Q1. If it fails, then module Q2 is executed, etc.The alternate modules are identified by the keywords “else by” When all alternate modules are exhausted, the recovery block itself is considered to have failed and the final keywords “else error” declares the fact. In other words, when all modules execute and none produce acceptable outputs, then the system falls. A reliability optimization model has been studied by Pham (1989b) to determine the optimal number of modules in a recovery block scheme that minimizes the total system cost given the reliability of the individual modules.In a recovery block, a programming function is realized by n alternative programs, P1, P2, . . . ., Pn. The computational result generated by each alternative program is checked by an acceptance test, T. If the result is rejected, another alternative program is then executed. The program will be repeated until an acceptable result is generated by one of the n alternatives or until all the alternative programs fail.The probability of failure of the RB scheme, , is as follows: where = probability of failure for version Pi = probability that acceptance test i judges an incorrect result as correctt = probability that acceptance test i judges a correct result as incorrect.The above equation corresponds to the case when all versions fall the acceptance test. The second term corresponds to the probability that acceptance test i judges an incorrect result as correct at the ith trial of the n versions.N-version Programming –NVP is used for providing fault-tolerance in software. In concept, the NVP scheme is similar to the N-modular redundancy scheme used to provide tolerance against hardware faults.The NVP is defined as the independent generation of functionally equivalent programs, called versions, from the same initial specification. Independent generation of programs means that the programming efforts are carried out by N individuals or groups that do not interact with respect to the programming process. Whenever possible, different algorithms, techniques, programming languages, environments, and tools are used in each effort. In this technique, N program versions are executed in parallel on identical input and the results are obtained by voting on the outputs from the individual programs. The advantage of NVP is that when a version failure occurs, no additional time is required for reconfiguring the system and redoing the computation.Consider an NVP scheme consists of n programs and a voting mechanism, V. As opposed to the RB approach, all n alternative programs are usually executed simultaneously and their results are sent to a decision mechanism which selects the final result. The decision mechanism is normally a voter when there are more than two versions (or, more than k versions, in general), and it is a comparator when there are only two versions (k versions). The syntactic structure of NVP is as follows:seq\n par\n P1(version 1)\n P2(version 2)\n .\n .\n .\n Pn(version n)\n decision V Assume that a correct result is expected where there are at least two correct results.The probability of failure of the NVP scheme, Pn, can be expressed as The first term of this equation is the probability that all versions fail. The second term is the probability that only one version is correct. The third term, d, is the probability that there are at least two correct results but the decision algorithm fails to deliver the correct result.It is worthwhile to note that the goal of the NVP approach is to ensure that multiple versions will be unlikely to fail on the same inputs. With each version independently developed by a different programming team, design approach, etc., the goal is that the versions will be different enough in order that they will not fail too often on the same inputs. However, multiversion programming is still a controversial topic."
},
{
"code": null,
"e": 36250,
"s": 33878,
"text": "Recovery Block Scheme –The recovery block scheme consists of three elements: primary module, acceptance tests, and alternate modules for a given task. The simplest scheme of the recovery block is as follows:Ensure T\n By P\n Else by Q1\n Else by Q2\n .\n .\n .\n Else by Qn-1\n Else Error Where T is an acceptance test condition that is expected to be met by successful execution of either the primary module P or the alternate modules Q1, Q2, . . ., Qn-1.The process begins when the output of the primary module is tested for acceptability. If the acceptance test determines that the output of the primary module is not acceptable, it recovers or rolls back the state of the system before the primary module is executed. It allows the second module Q1, to execute. The acceptance test is repeated to check the successful execution of module Q1. If it fails, then module Q2 is executed, etc.The alternate modules are identified by the keywords “else by” When all alternate modules are exhausted, the recovery block itself is considered to have failed and the final keywords “else error” declares the fact. In other words, when all modules execute and none produce acceptable outputs, then the system falls. A reliability optimization model has been studied by Pham (1989b) to determine the optimal number of modules in a recovery block scheme that minimizes the total system cost given the reliability of the individual modules.In a recovery block, a programming function is realized by n alternative programs, P1, P2, . . . ., Pn. The computational result generated by each alternative program is checked by an acceptance test, T. If the result is rejected, another alternative program is then executed. The program will be repeated until an acceptable result is generated by one of the n alternatives or until all the alternative programs fail.The probability of failure of the RB scheme, , is as follows: where = probability of failure for version Pi = probability that acceptance test i judges an incorrect result as correctt = probability that acceptance test i judges a correct result as incorrect.The above equation corresponds to the case when all versions fall the acceptance test. The second term corresponds to the probability that acceptance test i judges an incorrect result as correct at the ith trial of the n versions."
},
{
"code": null,
"e": 36367,
"s": 36250,
"text": "Ensure T\n By P\n Else by Q1\n Else by Q2\n .\n .\n .\n Else by Qn-1\n Else Error "
},
{
"code": null,
"e": 36970,
"s": 36367,
"text": "Where T is an acceptance test condition that is expected to be met by successful execution of either the primary module P or the alternate modules Q1, Q2, . . ., Qn-1.The process begins when the output of the primary module is tested for acceptability. If the acceptance test determines that the output of the primary module is not acceptable, it recovers or rolls back the state of the system before the primary module is executed. It allows the second module Q1, to execute. The acceptance test is repeated to check the successful execution of module Q1. If it fails, then module Q2 is executed, etc."
},
{
"code": null,
"e": 37508,
"s": 36970,
"text": "The alternate modules are identified by the keywords “else by” When all alternate modules are exhausted, the recovery block itself is considered to have failed and the final keywords “else error” declares the fact. In other words, when all modules execute and none produce acceptable outputs, then the system falls. A reliability optimization model has been studied by Pham (1989b) to determine the optimal number of modules in a recovery block scheme that minimizes the total system cost given the reliability of the individual modules."
},
{
"code": null,
"e": 37927,
"s": 37508,
"text": "In a recovery block, a programming function is realized by n alternative programs, P1, P2, . . . ., Pn. The computational result generated by each alternative program is checked by an acceptance test, T. If the result is rejected, another alternative program is then executed. The program will be repeated until an acceptable result is generated by one of the n alternatives or until all the alternative programs fail."
},
{
"code": null,
"e": 37989,
"s": 37927,
"text": "The probability of failure of the RB scheme, , is as follows:"
},
{
"code": null,
"e": 38191,
"s": 37994,
"text": "where = probability of failure for version Pi = probability that acceptance test i judges an incorrect result as correctt = probability that acceptance test i judges a correct result as incorrect."
},
{
"code": null,
"e": 38422,
"s": 38191,
"text": "The above equation corresponds to the case when all versions fall the acceptance test. The second term corresponds to the probability that acceptance test i judges an incorrect result as correct at the ith trial of the n versions."
},
{
"code": null,
"e": 40816,
"s": 38422,
"text": "N-version Programming –NVP is used for providing fault-tolerance in software. In concept, the NVP scheme is similar to the N-modular redundancy scheme used to provide tolerance against hardware faults.The NVP is defined as the independent generation of functionally equivalent programs, called versions, from the same initial specification. Independent generation of programs means that the programming efforts are carried out by N individuals or groups that do not interact with respect to the programming process. Whenever possible, different algorithms, techniques, programming languages, environments, and tools are used in each effort. In this technique, N program versions are executed in parallel on identical input and the results are obtained by voting on the outputs from the individual programs. The advantage of NVP is that when a version failure occurs, no additional time is required for reconfiguring the system and redoing the computation.Consider an NVP scheme consists of n programs and a voting mechanism, V. As opposed to the RB approach, all n alternative programs are usually executed simultaneously and their results are sent to a decision mechanism which selects the final result. The decision mechanism is normally a voter when there are more than two versions (or, more than k versions, in general), and it is a comparator when there are only two versions (k versions). The syntactic structure of NVP is as follows:seq\n par\n P1(version 1)\n P2(version 2)\n .\n .\n .\n Pn(version n)\n decision V Assume that a correct result is expected where there are at least two correct results.The probability of failure of the NVP scheme, Pn, can be expressed as The first term of this equation is the probability that all versions fail. The second term is the probability that only one version is correct. The third term, d, is the probability that there are at least two correct results but the decision algorithm fails to deliver the correct result.It is worthwhile to note that the goal of the NVP approach is to ensure that multiple versions will be unlikely to fail on the same inputs. With each version independently developed by a different programming team, design approach, etc., the goal is that the versions will be different enough in order that they will not fail too often on the same inputs. However, multiversion programming is still a controversial topic."
},
{
"code": null,
"e": 41572,
"s": 40816,
"text": "The NVP is defined as the independent generation of functionally equivalent programs, called versions, from the same initial specification. Independent generation of programs means that the programming efforts are carried out by N individuals or groups that do not interact with respect to the programming process. Whenever possible, different algorithms, techniques, programming languages, environments, and tools are used in each effort. In this technique, N program versions are executed in parallel on identical input and the results are obtained by voting on the outputs from the individual programs. The advantage of NVP is that when a version failure occurs, no additional time is required for reconfiguring the system and redoing the computation."
},
{
"code": null,
"e": 42059,
"s": 41572,
"text": "Consider an NVP scheme consists of n programs and a voting mechanism, V. As opposed to the RB approach, all n alternative programs are usually executed simultaneously and their results are sent to a decision mechanism which selects the final result. The decision mechanism is normally a voter when there are more than two versions (or, more than k versions, in general), and it is a comparator when there are only two versions (k versions). The syntactic structure of NVP is as follows:"
},
{
"code": null,
"e": 42142,
"s": 42059,
"text": "seq\n par\n P1(version 1)\n P2(version 2)\n .\n .\n .\n Pn(version n)\n decision V "
},
{
"code": null,
"e": 42229,
"s": 42142,
"text": "Assume that a correct result is expected where there are at least two correct results."
},
{
"code": null,
"e": 42299,
"s": 42229,
"text": "The probability of failure of the NVP scheme, Pn, can be expressed as"
},
{
"code": null,
"e": 42594,
"s": 42304,
"text": "The first term of this equation is the probability that all versions fail. The second term is the probability that only one version is correct. The third term, d, is the probability that there are at least two correct results but the decision algorithm fails to deliver the correct result."
},
{
"code": null,
"e": 43016,
"s": 42594,
"text": "It is worthwhile to note that the goal of the NVP approach is to ensure that multiple versions will be unlikely to fail on the same inputs. With each version independently developed by a different programming team, design approach, etc., the goal is that the versions will be different enough in order that they will not fail too often on the same inputs. However, multiversion programming is still a controversial topic."
},
{
"code": null,
"e": 43274,
"s": 43016,
"text": "The main difference between the recovery block scheme and the N-version programming is that the modules are executed sequentially in the former. The recovery block generally is not applicable to critical systems where real-time response is of great concern."
},
{
"code": null,
"e": 43295,
"s": 43274,
"text": "Software Engineering"
},
{
"code": null,
"e": 43393,
"s": 43295,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43402,
"s": 43393,
"text": "Comments"
},
{
"code": null,
"e": 43415,
"s": 43402,
"text": "Old Comments"
},
{
"code": null,
"e": 43441,
"s": 43415,
"text": "Types of Software Testing"
},
{
"code": null,
"e": 43500,
"s": 43441,
"text": "Differences between Black Box Testing vs White Box Testing"
},
{
"code": null,
"e": 43542,
"s": 43500,
"text": "Functional vs Non Functional Requirements"
},
{
"code": null,
"e": 43590,
"s": 43542,
"text": "Software Requirement Specification (SRS) Format"
},
{
"code": null,
"e": 43625,
"s": 43590,
"text": "Levels in Data Flow Diagrams (DFD)"
},
{
"code": null,
"e": 43673,
"s": 43625,
"text": "Differences between Verification and Validation"
},
{
"code": null,
"e": 43707,
"s": 43673,
"text": "DFD for Library Management System"
},
{
"code": null,
"e": 43733,
"s": 43707,
"text": "Software Testing | Basics"
},
{
"code": null,
"e": 43765,
"s": 43733,
"text": "What is DFD(Data Flow Diagram)?"
}
] |
Java Cryptography - Encrypting Data | You can encrypt given data using the Cipher class of the javax.crypto package. Follow the steps given below to encrypt given data using Java.
The KeyPairGenerator class provides getInstance() method which accepts a String variable representing the required key-generating algorithm and returns a KeyPairGenerator object that generates keys.
Create KeyPairGenerator object using the getInstance() method as shown below.
//Creating KeyPair generator object
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA");
The KeyPairGenerator class provides a method named initialize() this method is used to initialize the key pair generator. This method accepts an integer value representing the key size.
Initialize the KeyPairGenerator object created in the previous step using the initialize() method as shown below.
//Initializing the KeyPairGenerator
keyPairGen.initialize(2048);
You can generate the KeyPair using the generateKeyPair() method of the KeyPairGenerator class. Generate the key pair using this method as shown below.
//Generate the pair of keys
KeyPair pair = keyPairGen.generateKeyPair();
You can get the public key from the generated KeyPair object using the getPublic() method as shown below.
Get the public key using this method as shown below.
//Getting the public key from the key pair
PublicKey publicKey = pair.getPublic();
The getInstance() method of Cipher class accepts a String variable representing the required transformation and returns a Cipher object that implements the given transformation.
Create the Cipher object using the getInstance() method as shown below.
//Creating a Cipher object
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
The init() method of the Cipher class accepts two parameters an integer parameter representing the operation mode (encrypt/decrypt) and, a Key object representing the public key.
Initialize the Cypher object using the init() method as shown below.
//Initializing a Cipher object
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
The update() method of the Cipher class accepts a byte array representing the data to be encrypted and updates the current object with the data given.
Update the initialized Cipher object by passing the data to the update() method in the form of byte array as shown below.
//Adding data to the cipher
byte[] input = "Welcome to Tutorialspoint".getBytes();
cipher.update(input);
The doFinal() method of the Cipher class completes the encryption operation. Therefore, finish the encryption using this method as shown below.
//Encrypting the data
byte[] cipherText = cipher.doFinal();
Following Java program accepts text from user, encrypts it using RSA algorithm and, prints the encrypted format of the given text.
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Signature;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
public class CipherSample {
public static void main(String args[]) throws Exception{
//Creating a Signature object
Signature sign = Signature.getInstance("SHA256withRSA");
//Creating KeyPair generator object
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
//Initializing the key pair generator
keyPairGen.initialize(2048);
//Generating the pair of keys
KeyPair pair = keyPairGen.generateKeyPair();
//Creating a Cipher object
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
//Initializing a Cipher object
cipher.init(Cipher.ENCRYPT_MODE, pair.getPublic());
//Adding data to the cipher
byte[] input = "Welcome to Tutorialspoint".getBytes();
cipher.update(input);
//encrypting the data
byte[] cipherText = cipher.doFinal();
System.out.println(new String(cipherText, "UTF8"));
}
}
The above program generates the following output −
Encrypted Text:
"???:]J_?]???;Xl??????*@??u???r??=T&???_?_??.??i?????(?$_f?zD??????ZGH??g???
g?E:_??bz^??f?~o???t?}??u=uzp\UI????Z??l[?G?3??Y?UAEfKT?f?O??N_?d__?????a_?15%?^?
'p?_?$,9"{??^??y??_?t???,?W?PCW??~??[?$??????e????f?Y-Zi__??_??w?_?&QT??`?`~?[?K_??_???
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2195,
"s": 2053,
"text": "You can encrypt given data using the Cipher class of the javax.crypto package. Follow the steps given below to encrypt given data using Java."
},
{
"code": null,
"e": 2394,
"s": 2195,
"text": "The KeyPairGenerator class provides getInstance() method which accepts a String variable representing the required key-generating algorithm and returns a KeyPairGenerator object that generates keys."
},
{
"code": null,
"e": 2472,
"s": 2394,
"text": "Create KeyPairGenerator object using the getInstance() method as shown below."
},
{
"code": null,
"e": 2576,
"s": 2472,
"text": "//Creating KeyPair generator object\nKeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(\"DSA\");\n"
},
{
"code": null,
"e": 2762,
"s": 2576,
"text": "The KeyPairGenerator class provides a method named initialize() this method is used to initialize the key pair generator. This method accepts an integer value representing the key size."
},
{
"code": null,
"e": 2876,
"s": 2762,
"text": "Initialize the KeyPairGenerator object created in the previous step using the initialize() method as shown below."
},
{
"code": null,
"e": 2942,
"s": 2876,
"text": "//Initializing the KeyPairGenerator\nkeyPairGen.initialize(2048);\n"
},
{
"code": null,
"e": 3093,
"s": 2942,
"text": "You can generate the KeyPair using the generateKeyPair() method of the KeyPairGenerator class. Generate the key pair using this method as shown below."
},
{
"code": null,
"e": 3167,
"s": 3093,
"text": "//Generate the pair of keys\nKeyPair pair = keyPairGen.generateKeyPair();\n"
},
{
"code": null,
"e": 3273,
"s": 3167,
"text": "You can get the public key from the generated KeyPair object using the getPublic() method as shown below."
},
{
"code": null,
"e": 3326,
"s": 3273,
"text": "Get the public key using this method as shown below."
},
{
"code": null,
"e": 3410,
"s": 3326,
"text": "//Getting the public key from the key pair\nPublicKey publicKey = pair.getPublic();\n"
},
{
"code": null,
"e": 3588,
"s": 3410,
"text": "The getInstance() method of Cipher class accepts a String variable representing the required transformation and returns a Cipher object that implements the given transformation."
},
{
"code": null,
"e": 3660,
"s": 3588,
"text": "Create the Cipher object using the getInstance() method as shown below."
},
{
"code": null,
"e": 3748,
"s": 3660,
"text": "//Creating a Cipher object\nCipher cipher = Cipher.getInstance(\"RSA/ECB/PKCS1Padding\");\n"
},
{
"code": null,
"e": 3927,
"s": 3748,
"text": "The init() method of the Cipher class accepts two parameters an integer parameter representing the operation mode (encrypt/decrypt) and, a Key object representing the public key."
},
{
"code": null,
"e": 3996,
"s": 3927,
"text": "Initialize the Cypher object using the init() method as shown below."
},
{
"code": null,
"e": 4073,
"s": 3996,
"text": "//Initializing a Cipher object\ncipher.init(Cipher.ENCRYPT_MODE, publicKey);\n"
},
{
"code": null,
"e": 4224,
"s": 4073,
"text": "The update() method of the Cipher class accepts a byte array representing the data to be encrypted and updates the current object with the data given."
},
{
"code": null,
"e": 4346,
"s": 4224,
"text": "Update the initialized Cipher object by passing the data to the update() method in the form of byte array as shown below."
},
{
"code": null,
"e": 4455,
"s": 4346,
"text": "//Adding data to the cipher\nbyte[] input = \"Welcome to Tutorialspoint\".getBytes();\t \ncipher.update(input);\n"
},
{
"code": null,
"e": 4599,
"s": 4455,
"text": "The doFinal() method of the Cipher class completes the encryption operation. Therefore, finish the encryption using this method as shown below."
},
{
"code": null,
"e": 4660,
"s": 4599,
"text": "//Encrypting the data\nbyte[] cipherText = cipher.doFinal();\n"
},
{
"code": null,
"e": 4791,
"s": 4660,
"text": "Following Java program accepts text from user, encrypts it using RSA algorithm and, prints the encrypted format of the given text."
},
{
"code": null,
"e": 5936,
"s": 4791,
"text": "import java.security.KeyPair;\nimport java.security.KeyPairGenerator;\nimport java.security.Signature;\n\nimport javax.crypto.BadPaddingException;\nimport javax.crypto.Cipher;\n\npublic class CipherSample {\n public static void main(String args[]) throws Exception{\n //Creating a Signature object\n Signature sign = Signature.getInstance(\"SHA256withRSA\");\n \n //Creating KeyPair generator object\n KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(\"RSA\");\n \n //Initializing the key pair generator\n keyPairGen.initialize(2048);\n \n //Generating the pair of keys\n KeyPair pair = keyPairGen.generateKeyPair(); \n\t\n //Creating a Cipher object\n Cipher cipher = Cipher.getInstance(\"RSA/ECB/PKCS1Padding\");\n \n //Initializing a Cipher object\n cipher.init(Cipher.ENCRYPT_MODE, pair.getPublic());\n\t \n //Adding data to the cipher\n byte[] input = \"Welcome to Tutorialspoint\".getBytes();\t \n cipher.update(input);\n\t \n //encrypting the data\n byte[] cipherText = cipher.doFinal();\t \n System.out.println(new String(cipherText, \"UTF8\"));\n }\n}"
},
{
"code": null,
"e": 5987,
"s": 5936,
"text": "The above program generates the following output −"
},
{
"code": null,
"e": 6254,
"s": 5987,
"text": "Encrypted Text: \n\"???:]J_?]???;Xl??????*@??u???r??=T&???_?_??.??i?????(?$_f?zD??????ZGH??g???\ng?E:_??bz^??f?~o???t?}??u=uzp\\UI????Z??l[?G?3??Y?UAEfKT?f?O??N_?d__?????a_?15%?^?\n'p?_?$,9\"{??^??y??_?t???,?W?PCW??~??[?$??????e????f?Y-Zi__??_??w?_?&QT??`?`~?[?K_??_???\n"
},
{
"code": null,
"e": 6287,
"s": 6254,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6303,
"s": 6287,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6336,
"s": 6303,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6352,
"s": 6336,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6387,
"s": 6352,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6401,
"s": 6387,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6435,
"s": 6401,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6449,
"s": 6435,
"text": " Tushar Kale"
},
{
"code": null,
"e": 6486,
"s": 6449,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 6501,
"s": 6486,
"text": " Monica Mittal"
},
{
"code": null,
"e": 6534,
"s": 6501,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6553,
"s": 6534,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6560,
"s": 6553,
"text": " Print"
},
{
"code": null,
"e": 6571,
"s": 6560,
"text": " Add Notes"
}
] |
How to get Spinner value in Kotlin? | This example demonstrates how to get Spinner value in Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Tutorials Point"
android:textAlignment="center"
android:textColor="@android:color/holo_green_dark"
android:textSize="32sp"
android:textStyle="bold" />
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/spinner"
android:layout_centerInParent="true"
android:layout_marginTop="25dp"
android:textColor="@android:color/holo_purple"
android:textSize="16sp"
android:textStyle="italic|bold" />
</RelativeLayout>
Step 3 − Open res/strings.xml and add the following code −
<resources>
<string name="app_name">Q39</string>
<string-array name="birds">
<item>crane</item>
<item>Cuckoo</item>
<item>Pigeon</item>
<item>Eagle</item>
<item>Owl</item>
<item>Vulture</item>
<item>WoodPecker</item>
</string-array>
</resources>
Step 4 − Add the following code to MainActivity.kt
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Spinner
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity(), AdapterView.OnItemSelectedListener {
lateinit var spinner: Spinner
lateinit var textView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
textView = findViewById(R.id.textView)
spinner = findViewById(R.id.spinner)
val adapter = ArrayAdapter.createFromResource(
this,
R.array.birds,
android.R.layout.simple_spinner_item
)
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner.adapter = adapter
spinner.onItemSelectedListener = this
}
override fun onNothingSelected(parent: AdapterView<*>?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
val text: String = parent?.getItemAtPosition(position).toString()
textView.text = text
}
}
Step 5 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.q36">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code. | [
{
"code": null,
"e": 1124,
"s": 1062,
"text": "This example demonstrates how to get Spinner value in Kotlin."
},
{
"code": null,
"e": 1253,
"s": 1124,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1318,
"s": 1253,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2541,
"s": 1318,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:text=\"Tutorials Point\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/holo_green_dark\"\n android:textSize=\"32sp\"\n android:textStyle=\"bold\" />\n <Spinner\n android:id=\"@+id/spinner\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\" />\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/spinner\"\n android:layout_centerInParent=\"true\"\n android:layout_marginTop=\"25dp\"\n android:textColor=\"@android:color/holo_purple\"\n android:textSize=\"16sp\"\n android:textStyle=\"italic|bold\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2600,
"s": 2541,
"text": "Step 3 − Open res/strings.xml and add the following code −"
},
{
"code": null,
"e": 2897,
"s": 2600,
"text": "<resources>\n <string name=\"app_name\">Q39</string>\n <string-array name=\"birds\">\n <item>crane</item>\n <item>Cuckoo</item>\n <item>Pigeon</item>\n <item>Eagle</item>\n <item>Owl</item>\n <item>Vulture</item>\n <item>WoodPecker</item>\n </string-array>\n</resources>"
},
{
"code": null,
"e": 2948,
"s": 2897,
"text": "Step 4 − Add the following code to MainActivity.kt"
},
{
"code": null,
"e": 4265,
"s": 2948,
"text": "import android.os.Bundle\nimport android.view.View\nimport android.widget.AdapterView\nimport android.widget.ArrayAdapter\nimport android.widget.Spinner\nimport android.widget.TextView\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity(), AdapterView.OnItemSelectedListener {\n lateinit var spinner: Spinner\n lateinit var textView: TextView\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n textView = findViewById(R.id.textView)\n spinner = findViewById(R.id.spinner)\n val adapter = ArrayAdapter.createFromResource(\n this,\n R.array.birds,\n android.R.layout.simple_spinner_item\n )\n adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)\n spinner.adapter = adapter\n spinner.onItemSelectedListener = this\n }\n override fun onNothingSelected(parent: AdapterView<*>?) {\n TODO(\"not implemented\") //To change body of created functions use File | Settings | File Templates.\n }\n override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {\n val text: String = parent?.getItemAtPosition(position).toString()\n textView.text = text\n }\n}"
},
{
"code": null,
"e": 4320,
"s": 4265,
"text": "Step 5 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4990,
"s": 4320,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.q36\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 5341,
"s": 4990,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 5382,
"s": 5341,
"text": "Click here to download the project code."
}
] |
Using Codex to translate Keras to fastai | by Mark Ryan | Towards Data Science | OpenAI’s Codex provides a set of computer language-specific operations that can be used to generate code from English language descriptions, automatically document code, and translate between coding languages. Over the last few months I have been exporing Codex’s capabilities, including its ability to generate web applications from English-language prompts and its ability to generate modern code from COBOL. I was curious to see how Codex would handle translating between two different deep learning frameworks.
I have had the privilege of writing two books, one on deep learning with structured data that featured deep learning examples written in Keras (the high-level deep learning framework for TensorFlow), and another on deep learning with the fastai, a high-level framework built on top of PyTorch. In the course of writing the second book I needed to create a fastai implementation of an existing Keras application. When I wrote the book I created the fastai application “by hand” through trial and error until I got working code was roughly equivalent to the Keras code. What if I had had access to Codex when I was writing the book— would I have been able to take advantage of it to generate fastai automatically from Keras? In this article I’ll describe an experiment to answer this question.
The simplest deep learning problem you can tackle is using the MNIST dataset of hand-written digits to train a model that predict the number depicted in an image of hand-written digits.
You could say that creating a model for MNIST is the “hello world” of deep learning.
My book on fastai includes a side-by-side comparison of Keras and fastai implementations of MNIST models. This comparison illustrates the differences between these two frameworks and sets the stage for developers who are familiar with Keras to explore fastai.
To exercise Codex’s ability to translate from Keras to fastai I decided to take the same Keras MNIST implementation that I had hand-converted into fastai for my book and see if Codex could accomplish the translation correctly.
Here is the starting point Keras MNIST implementation, adapted from https://github.com/tensorflow/docs/blob/master/site/en/tutorials/quickstart/beginner.ipynb:
To get Codex to translate this to fastai, I used the following prompt pattern:
// Rewrite this as a fastai model[ Keras code goes here ]// fastai version:
The result that Codex generated looked reasonably plausible as fastai:
I copied this code into a Colab notebook, but it wouldn’t work as is. I needed to make two changes to get it to run correctly in Colab:
Replace the include statements with include statements for a notebook:
#import fastai#from fastai.vision.all import * !pip install -Uqq fastbookfrom fastbook import *from fastai.vision.all import *
Comment out the compile statement:
#hello_world_model.compile(optimizer=optim.Adam,# loss_func=nn.CrossEntropyLoss(),# metrics=[accuracy])
With these changes I was able to successfully run the fastai code in Colab and get a working MNIST deep learning model:
While the fastai code that Codex generated worked with a couple of minor fixes, it wasn’t 100% equivalent to the Keras input code. In particular, the input Keras code included statements to show the model’s loss and accuracy for the test dataset:
test_scores = hello_world_model.evaluate(x_test, y_test, verbose=2) print('Loss for test dataset:', test_scores[0])print('Accuracy for test dataset:', test_scores[1])
The fastai code that Codex generated includes the following statement to exercise the trained model on the test set, but it doesn’t show the aggregated results the way that the original Keras code does:
test_dl = dls.test_dl(get_image_files(path/'testing'))preds,_ = learn.get_preds(dl=test_dl)
Given Keras code for an MNIST deep learning model as input, Codex was able to produce fastai code as output that (after a couple of minor changes) successfully trained an MNIST deep learning model. Here are my key observations:
On one hand, this is impressive. Code that uses the Keras framework is quite different from code that uses fastai, and as a human being it took me a few tries to get working fastai code for MNIST with the Keras code as as starting point. Codex produced (almost) working fastai code on its first try. I didn’t have to fiddle with the prompts or make any changes to the in put Keras code.
On the other hand, I have to wonder whether Codex had simply “memorized” Keras and fastai MNIST implementations that were part of the github corpus on which it had been trained. For example, the code for my Deep Learning with fastai book (including this hand-written fastai MNIST application and its companion Keras MNIST application) has been in github since mid 2021, so it’s possible that the training set for Codex included the examples from my book, and all Codex was doing was “looking up” the fastai statements from the hand-written MNIST application that it had seen in its training set.
On balance, I have to say that I am impressed that Codex was able to generate (just about) working fastai code from Keras code. Even translating “hello world” from one framework to another automatically is an accomplishment. I look forward to testing Codex with more challenging Keras to fastai translations.
Video covering the same topic as this article: https://youtu.be/xUMBiMP4xNw | [
{
"code": null,
"e": 686,
"s": 171,
"text": "OpenAI’s Codex provides a set of computer language-specific operations that can be used to generate code from English language descriptions, automatically document code, and translate between coding languages. Over the last few months I have been exporing Codex’s capabilities, including its ability to generate web applications from English-language prompts and its ability to generate modern code from COBOL. I was curious to see how Codex would handle translating between two different deep learning frameworks."
},
{
"code": null,
"e": 1478,
"s": 686,
"text": "I have had the privilege of writing two books, one on deep learning with structured data that featured deep learning examples written in Keras (the high-level deep learning framework for TensorFlow), and another on deep learning with the fastai, a high-level framework built on top of PyTorch. In the course of writing the second book I needed to create a fastai implementation of an existing Keras application. When I wrote the book I created the fastai application “by hand” through trial and error until I got working code was roughly equivalent to the Keras code. What if I had had access to Codex when I was writing the book— would I have been able to take advantage of it to generate fastai automatically from Keras? In this article I’ll describe an experiment to answer this question."
},
{
"code": null,
"e": 1664,
"s": 1478,
"text": "The simplest deep learning problem you can tackle is using the MNIST dataset of hand-written digits to train a model that predict the number depicted in an image of hand-written digits."
},
{
"code": null,
"e": 1749,
"s": 1664,
"text": "You could say that creating a model for MNIST is the “hello world” of deep learning."
},
{
"code": null,
"e": 2009,
"s": 1749,
"text": "My book on fastai includes a side-by-side comparison of Keras and fastai implementations of MNIST models. This comparison illustrates the differences between these two frameworks and sets the stage for developers who are familiar with Keras to explore fastai."
},
{
"code": null,
"e": 2236,
"s": 2009,
"text": "To exercise Codex’s ability to translate from Keras to fastai I decided to take the same Keras MNIST implementation that I had hand-converted into fastai for my book and see if Codex could accomplish the translation correctly."
},
{
"code": null,
"e": 2396,
"s": 2236,
"text": "Here is the starting point Keras MNIST implementation, adapted from https://github.com/tensorflow/docs/blob/master/site/en/tutorials/quickstart/beginner.ipynb:"
},
{
"code": null,
"e": 2475,
"s": 2396,
"text": "To get Codex to translate this to fastai, I used the following prompt pattern:"
},
{
"code": null,
"e": 2551,
"s": 2475,
"text": "// Rewrite this as a fastai model[ Keras code goes here ]// fastai version:"
},
{
"code": null,
"e": 2622,
"s": 2551,
"text": "The result that Codex generated looked reasonably plausible as fastai:"
},
{
"code": null,
"e": 2758,
"s": 2622,
"text": "I copied this code into a Colab notebook, but it wouldn’t work as is. I needed to make two changes to get it to run correctly in Colab:"
},
{
"code": null,
"e": 2829,
"s": 2758,
"text": "Replace the include statements with include statements for a notebook:"
},
{
"code": null,
"e": 2956,
"s": 2829,
"text": "#import fastai#from fastai.vision.all import * !pip install -Uqq fastbookfrom fastbook import *from fastai.vision.all import *"
},
{
"code": null,
"e": 2991,
"s": 2956,
"text": "Comment out the compile statement:"
},
{
"code": null,
"e": 3121,
"s": 2991,
"text": "#hello_world_model.compile(optimizer=optim.Adam,# loss_func=nn.CrossEntropyLoss(),# metrics=[accuracy])"
},
{
"code": null,
"e": 3241,
"s": 3121,
"text": "With these changes I was able to successfully run the fastai code in Colab and get a working MNIST deep learning model:"
},
{
"code": null,
"e": 3488,
"s": 3241,
"text": "While the fastai code that Codex generated worked with a couple of minor fixes, it wasn’t 100% equivalent to the Keras input code. In particular, the input Keras code included statements to show the model’s loss and accuracy for the test dataset:"
},
{
"code": null,
"e": 3656,
"s": 3488,
"text": "test_scores = hello_world_model.evaluate(x_test, y_test, verbose=2) print('Loss for test dataset:', test_scores[0])print('Accuracy for test dataset:', test_scores[1])"
},
{
"code": null,
"e": 3859,
"s": 3656,
"text": "The fastai code that Codex generated includes the following statement to exercise the trained model on the test set, but it doesn’t show the aggregated results the way that the original Keras code does:"
},
{
"code": null,
"e": 3951,
"s": 3859,
"text": "test_dl = dls.test_dl(get_image_files(path/'testing'))preds,_ = learn.get_preds(dl=test_dl)"
},
{
"code": null,
"e": 4179,
"s": 3951,
"text": "Given Keras code for an MNIST deep learning model as input, Codex was able to produce fastai code as output that (after a couple of minor changes) successfully trained an MNIST deep learning model. Here are my key observations:"
},
{
"code": null,
"e": 4566,
"s": 4179,
"text": "On one hand, this is impressive. Code that uses the Keras framework is quite different from code that uses fastai, and as a human being it took me a few tries to get working fastai code for MNIST with the Keras code as as starting point. Codex produced (almost) working fastai code on its first try. I didn’t have to fiddle with the prompts or make any changes to the in put Keras code."
},
{
"code": null,
"e": 5162,
"s": 4566,
"text": "On the other hand, I have to wonder whether Codex had simply “memorized” Keras and fastai MNIST implementations that were part of the github corpus on which it had been trained. For example, the code for my Deep Learning with fastai book (including this hand-written fastai MNIST application and its companion Keras MNIST application) has been in github since mid 2021, so it’s possible that the training set for Codex included the examples from my book, and all Codex was doing was “looking up” the fastai statements from the hand-written MNIST application that it had seen in its training set."
},
{
"code": null,
"e": 5471,
"s": 5162,
"text": "On balance, I have to say that I am impressed that Codex was able to generate (just about) working fastai code from Keras code. Even translating “hello world” from one framework to another automatically is an accomplishment. I look forward to testing Codex with more challenging Keras to fastai translations."
}
] |
Insider Threat Detection with AI Using Tensorflow and RapidMiner Studio | by Dennis Chow | Towards Data Science | This technical article will teach you how to pre-process data, create your own neural networks, and train and evaluate models using the US-CERT’s simulated insider threat dataset. The methods and solutions are designed for non-domain experts; particularly cyber security professionals. We will start our journey with the raw data provided by the dataset and provide examples of different pre-processing methods to get it “ready” for the AI solution to ingest. We will ultimately create models that can be re-used for additional predictions based on security events. Throughout the article, I will also point out the applicability and return on investment depending on your existing Information Security program in the enterprise.
Note: To use and replicate the pre-processed data and steps we use, prepare to spend 1–2 hours on this page. Stay with me and try not to fall asleep during the data pre-processing portion. What many tutorials don’t state is that if you’re starting from scratch; data pre-processing takes up to 90% of your time when doing projects like these.
At the end of this hybrid article and tutorial, you should be able to:
Pre-process the data provided from US-CERT into an AI solution ready format (Tensorflow in particular)
Use RapidMiner Studio and Tensorflow 2.0 + Keras to create and train a model using a pre-processed sample CSV dataset
Perform basic analysis of your data, chosen fields for AI evaluation, and understand the practicality for your organization using the methods described
The author provides these methods, insights, and recommendations *as is* and makes no claim of warranty. Please do not use the models you create in this tutorial in a production environment without sufficient tuning and analysis before making them a part of your security program.
If you wish to follow along and perform these activities yourself, please download and install the following tools from their respective locations:
Choose: To be hands on from scratch and experiment with your own variations of data: download the full dataset: ftp://ftp.sei.cmu.edu/pub/cert-data: *Caution: it is very large. Please plan to have several hundred gigs of free space
Choose: If you just want to follow along execute what I’ve done, you can download the pre-processed data, Python, and solution files from my Github (click repositories and find tensorflow-insiderthreat) https://github.com/dc401/tensorflow-insiderthreat
Optional: if you want a nice IDE for Python: Visual Studio 2019 Community Edition with the applicable Python extensions install
Required: Rapidminer Studio Trial (or educational license if it applies to you)
Required: Python environment , use the Python 3.8.3 x64 bit release
Required: Install python packages: (numpy, pandas, tensorflow, sklearn via “pip install <packagename>” from the command line
It’s important for newcomers to any data science discipline to know that the majority of your time spent will be in data pre-processing and analyzing what you have which includes cleaning up the data, normalizing, extracting any additional meta insights, and then encoding the data so that it is ready for an AI solution to ingest it.
We need to extract and process the dataset in such a way where it is structured with fields that we may need as ‘features’ which is just to be inclusive in the AI model we create. We will need to ensure all the text strings are encoded into numbers so the engine we use can ingest it. We will also have to mark which are insider threat and non-threat rows (true positives, and true negatives).Next, after data pre-processing we’ll need select, setup, and create the functions we will use to create the model and create the neural network layers itselfGenerate the model; and examine the accuracy, applicability, and identify additional modifications or tuning needed in any of part of the data pipeline
We need to extract and process the dataset in such a way where it is structured with fields that we may need as ‘features’ which is just to be inclusive in the AI model we create. We will need to ensure all the text strings are encoded into numbers so the engine we use can ingest it. We will also have to mark which are insider threat and non-threat rows (true positives, and true negatives).
Next, after data pre-processing we’ll need select, setup, and create the functions we will use to create the model and create the neural network layers itself
Generate the model; and examine the accuracy, applicability, and identify additional modifications or tuning needed in any of part of the data pipeline
Examining the raw US-CERT data requires you to download compressed files that must be extracted. Note just how large the sets are compared to how much we will use and reduce at the end of the data pre-processing.
In our article, we saved a bunch of time by going directly to the answers.tar.bz2 that has the insiders.csv file for matching which datasets and individual extracted records of are value. Now, it is worth stating that in the index provided there has correlated record numbers in extended data such as the file, and psychometric related data. We didn’t use the extended meta in this tutorial brief because of the extra time to correlate and consolidate all of it into a single CSV in our case.
To see a more comprehensive set of feature sets extracted from this same data, consider checking out this research paper called “Image-Based Feature Representation for Insider Threat Classification.” We’ll be referring to that paper later in the article when we examine our model accuracy.
Before getting the data encoded and ready for a function to read it; we need to get the data extracted and categorized into columns that we need to predict one. Let’s use good old Excel to insert a column into the CSV. Prior to the screenshot we took and added all the rows from the referenced datasets in “insiders.csv” for scenario 2.
Insiders.csv index of true positives
The scenario (2) is described in scenarios.txt: “User begins surfing job websites and soliciting employment from a competitor. Before leaving the company, they use a thumb drive (at markedly higher rates than their previous activity) to steal data.”
Examine our pre-processed data that includes its intermediary and final forms as shown in the following below:
Intermediate composite true positive records for scenario 2
In the above photo, this is a snippet of all the different record types essentially appended to each other and properly sorted by date. Note that different vectors (http vs. email vs. device) do not all align easily have different contexts in the columns. This is not optimal by any means but since the insider threat scenario includes multiple event types; this is what we’ll have to work with for now. This is the usual case with data that you’ll get trying to correlate based on time and multiple events tied to a specific attribute or user like a SIEM does.
Comparison of different data types that have to be consolidated
In the aggregation set; we combined the relevant CSV’s after moving all of the items mentioned from the insiders.csv for scenario 2 into the same folder. To formulate the entire ‘true positive’ only dataset portion; we’ve used powershell as shown below:
Using powershell to merge the CSV’s together
Right now we have a completely imbalanced dataset where we only have true positives. We’ll also have to add true negatives and the best approach is to have an equal amount of record types representing in a 50/50 scenario of non-threat activity. This is almost never the case with security data so we’ll do what we can as you’ll find below. I also want to point out, that if you’re doing manual data processing in an OS shell — whatever you import into a variable is in memory and does not get released or garbage collected by itself as you can see from my PowerShell memory consumption after a bunch of data manipulation and CSV wrangling, I’ve bumped up my usage to 5.6 GB.
Memory isn’t released automatically. We also count the lines in each CSV file.
Let’s look at the R1 dataset files. We’ll need to pull from that we know are confirmed true negatives (non-threats) for each of the 3 types from filenames we used in the true positive dataset extracts (again, it’s from the R1 dataset which have benign events).
We’ll merge a number of records from all 3 of the R1 true negative data sets from logon, http, and device files. Note, that in the R1 true negative set, we did not find an emails CSV which adds to the imbalance for our aggregate data set.
Using PowerShell we count the length of lines in each file. Since we had about ~14K of rows from the true positive side, I arbitrarily took from the true negative side the first 4500 applicable rows from each subsequent file and appended them to the training dataset so that we have both true positives, and true negatives mixed in. We’ll have to add a column to mark which is a insider threat and which aren’t.
Extracting records of true negatives from 3 complementing CSV’s
In pre-processing our data we’ve already added all the records of interest below and selected various other true-negative non-threat records from the R1 dataset. Now we have our baseline of threats and non-threats concatenated in a single CSV. To the left, we’ve added a new column to denote a true/false or (1 or 0) in a find and replace scenario.
Label encoding the insider threat True/False Column
Above, you can also see we started changing true/false strings to numerical categories. This is us beginning on our path to encode the data through manual pre-processing which we could save ourselves the hassle as we see in future steps in RapidMiner Studio and using the Pandas Dataframe library in Python for Tensorflow. We just wanted to illustrate some of the steps and considerations you’ll have to perform. Following this, we will continue processing our data for a bit. Let’s highlight what we can do using excel functions before going the fully automated route.
Calculating Unix Epoch Time from the Date and Time Provided
We’re also manually going to convert the date field into Unix Epoch Time for the sake of demonstration and as you seen it becomes a large integer with a new column. To remove the old column in excel for rename, create a new sheet such as ‘scratch’ and cut the old date (non epoch timestamp) values into that sheet. Reference the sheet along with the formula you see in the cell to achieve this effect. This formula is: “=(C2-DATE(1970,1,1))*86400” without quotes.
Encoding the vector column and feature set column map
In our last manual pre-processing work example you need to format the CSV in is to ‘categorize’ by label encoding the data. You can automate this as one-hot encoding methods via a data dictionary in a script or in our case we show you the manual method of mapping this in excel since we have a finite set of vectors of the records of interest (http is 0, email is 1, and device is 2).
You’ll notice that we have not done the user, source, or action columns as it has a very large number of unique values that need label encoding and it’s just impractical by hand. We were able to accomplish this without all the manual wrangling above using the ‘turbo prep’ feature of RapidMiner Studio and likewise for the remaining columns via Python’s Panda in our script snippet below. Don’t worry about this for now, we will show case the steps in each different AI tool and up doing the same thing the easy way.
#print(pd.unique(dataframe['user']))#https://pbpython.com/categorical-encoding.htmldataframe["user"] = dataframe["user"].astype('category')dataframe["source"] = dataframe["source"].astype('category')dataframe["action"] = dataframe["action"].astype('category')dataframe["user_cat"] = dataframe["user"].cat.codesdataframe["source_cat"] = dataframe["source"].cat.codesdataframe["action_cat"] = dataframe["action"].cat.codes#print(dataframe.info())#print(dataframe.head())#save dataframe with new columns for future datmappingdataframe.to_csv('dataframe-export-allcolumns.csv')#remove old columnsdel dataframe["user"]del dataframe["source"]del dataframe["action"]#restore original names of columnsdataframe.rename(columns={"user_cat": "user", "source_cat": "source", "action_cat": "action"}, inplace=True)
The above snippet is the using python’s panda library example of manipulating and label encoding the columns into numerical values unique to each string value in the original data set. Try not to get caught up in this yet. We’re going to show you the easy and comprehensive approach of all this data science work in Rapidminer Studio
Important step for defenders: Given that we’re using the pre-simulated dataset that has been formatted from US-CERT, not every SOC is going to have access to the same uniform data for their own security events. Many times your SOC will have only raw logs to export. From an ROI perspective — before pursuing your own DIY project like this, consider the level of effort and if you can automate exporting meta of your logs into a CSV format, an enterprise solution as Splunk or another SIEM might be able to do this for you. You would have to correlate your events and add as many columns as possible for enriched data formatting. You would also have to examine how consistent and how you can automate exporting this data in a format that US-CERT has to use similar methods for pre-processing or ingestion. Make use of your SIEM’s API features to export reports into a CSV format whenever possible.
It’s time use to some GUI based and streamlined approaches. The desktop edition of RapidMiner is Studio and the latest editions as of 9.6.x have turbo prep and auto modeling built in as part of your workflows. Since we’re not domain experts, we are definitely going to take advantage of using this. Let’s dig right in.
Note: If your trial expired before getting to this tutorial and use community edition, you will be limited to 10,000 rows. Further pre-processing is required to limit your datasets to 5K of true positives, and 5K of true negatives including the header. If applicable, use an educational license which is unlimited and renewable each year that you enrolled in a qualifying institution with a .edu email.
RapidMiner Studio
Upon starting we’re going to start a new project and utilize the Turbo Prep feature. You can use other methods or the manual way of selecting operators via the GUI in the bottom left for the community edition. However, we’re going to use the enterprise trial because it’s easy to walk through for first-time users.
Import the Non-Processed CSV Aggregate File
We’ll import our aggregate CSV of true positive only data non-processed; and also remove the first row headers and use our own because the original row relates to the HTTP vector and does not apply to subsequent USB device connection and Email related records also in the dataset as shown below.
Note: Unlike our pre-processing steps which includes label encodings and reduction, we did not do this yet on RapidMiner Studio to show the full extent of what we can easily do in the ‘turbo prep’ feature. We’re going to enable the use of quotes as well and leave the other defaults for proper string escapes.
Next, we set our column header types to their appropriate data types.
Stepping through the wizard we arrive at the turbo prep tab for review and it shows us distribution and any errors such as missing values that need to be adjusted and which columns might be problematic. Let’s start with making sure we identify all of these true positives as insider threats to begin with. Click on generate and we’re going to transform this dataset by inserting a new column in all the rows with a logical ‘true’ statement like so below
We’ll save the column details and export it for further processing later or we’ll use it as a base template set for when we begin to pre-process for the Tensorflow method following this to make things a little easier.
After the export as you can see above, don’t forget we need to balance the data with true negatives. We’ll repeat the same process of importing the true negatives. Now we should see multiple datasets in our turbo prep screen.
In the above, even though we’ve only imported 2 datasets, remember transformed the true positive by adding a column called insiderthreat which is a true/false boolean logic. We do the same with true negatives and you’ll eventually end up with 4 of these listings.
We’ll need to merge the true positives and true negatives into a ‘training set’ before we get to do anything fun with it. But first, we also need to drop columns that we don’t think are relevant our useful such as the transaction ID and the description column of the website keywords scraped as none of the other row data have these; and and would contain a bunch of empty (null) values that aren’t useful for calculation weights.
Important thought: As we’ve mentioned regarding other research papers, choosing columns for calculation aka ‘feature sets’ that include complex strings have to be tokenized using natural language processing (NLP). This adds to your pre-processing requirements in additional to label encoding in which in the Tensorflow + Pandas Python method would usually require wrangling multiple data frames and merging them together based on column keys for each record. While this is automated for you in RapidMiner, in Tensorflow you’ll have to include this in your pre-processing script. More documentation about this can be found here.
Take note that we did not do this in our datasets because you’ll see much later in an optimized RapidMiner Studio recommendation that heavier weight and emphasis on the date and time are were more efficient feature sets with less complexity. You on other hand on different datasets and applications may need to NLP for sentiment analysis to add to the insider threat modeling.
Finishing your training set: Although we do not illustrate this, after you have imported both true negatives and true positives within the Turbo prep menu click on the “merge” button and select both transformed datasets and select the “Append” option since both have been pre-sorted by date.
Within RapidMiner Studio we continue to the ‘Auto Model’ tab and utilize our selected aggregate ‘training’ data (remember training data includes true positives and true negatives) to predict on the insiderthreat column (true or false)
We also notice what our actual balance is. We are still imbalanced with only 9,001 records of non-threats vs. threats of ~14K. It’s imbalanced and that can always be padded with additional records should you choose. For now, we’ll live with it and see what we can accomplish with not-so-perfect data.
Here the auto modeler recommends different feature columns in green and yellow and their respective correlation. The interesting thing is that it is estimating date is of high correlation but less stability than action and vector.
Important thought: In our head, we would think as defenders all of the feature set applies in each column as we’ve already reduced what we could as far as relevance and complexities. It’s also worth mentioning that this is based off a single event. Remember insider threats often take multiple events as we saw in the answers portion of the insiders.csv . What the green indicators are showing us are unique record single event identification.
We’re going to use all the columns anyways because we think it’s all relevant columns to use. We also move to the next screen on model types, and because we’re not domain experts we’re going to try almost all of them and we want the computer to re-run each model multiple times finding the optimized set of inputs and feature columns.
Remember that feature sets can include meta information based on insights from existing columns. We leave the default values of tokenization and we want to extract date and text information. Obviously the items with the free-form text are the ‘Action’ column with all the different URLs, and event activity that we want NLP to be applied. And we want to correlate between columns, the importance of columns, and explain predictions as well.
Note that in the above we’ve pretty much selected bunch of heavy processing parameters in our batch job. On an 8 core single threadded processor running Windows 10, 24 GB memory and a GPU of a Radeon RX570 value series with SSD’s all of these models took about 6 hours to run total with all the options set. After everything was completed we have 8000+ models and 2600+ feature set combinations tested in our screen comparison.
According to RapidMiner Studio; the deep learning neural network methods aren’t the best ROI fit; compared to the linear general model. There are no errors though- and that’s worrisome which might mean that we have poor quality data or an overfit issue with the model. Let’s take a look at deep learning as it also states a potential 100% accuracy just to compare it.
In the Deep Learning above it’s tested against 187 different combinations of feature sets and the optimized model shows that unlike our own thoughts as to what features would be good including the vector and action mostly. We see even more weight put on the tokens in Action interesting words and the dates. Surprisingly; we did not see anything related to “email” or the word “device” in the actions as part of the optimized model.
Not to worry, as this doesn’t mean we’re dead wrong. It just means the feature sets it selected in its training (columns and extracted meta columns) provided less errors in the training set. This could be that we don’t have enough diverse or high quality data in our set. In the previous screen above you saw an orange circle and a translucent square.
The orange circle indicates the models suggested optimizer function and the square is our original selected feature set. If you examine the scale, our human selected feature set was an error rate of 0.9 and 1% which gives our accuracy closer to the 99% mark; but only at a much higher complexity model (more layers and connections in the neural net required) That makes me feel a little better and just goes to show you that caution is needed when interpreting all of these at face value.
Let’s say you don’t fully trust such a highly “100% accurate model”. We can try to re-run it using our feature sets in vanilla manner as a pure token label. We’re *not* going extract date information, no text tokenization via NLP and we don’t want it to automatically create new feature set meta based on our original selections. Basically, we’re going to use a plain vanilla set of columns for the calculations.
So in the above let’s re-run it looking at 3 different models including the original best fit model and the deep learning we absolutely no optimization and additional NLP applied. So it’s as if we only used encoded label values only in the calculations and not much else.
In the above, we get even worse results with an error rate of 39% is a 61% accuracy across pretty much all the models. Our selection and lack of complexity without using text token extraction is so reduced that even a more “primitive” Bayesian model (commonly used in basic email spam filter engines) seems to be just as accurate and has a fast compute time. This all looks bad but let’s dig a little deeper:
When we select the details of the deep learning model again we see the accuracy climb in linear fashion as more of the training set population is discovered and validated against. From an interpretation stand point this shows us a few things:
Our original primitive thoughts of feature sets of focusing on the vector and action frequency using only unique encoded values is about as only as good as a toss-up probability of an analyst finding a threat in the data. On the surface it appears that we have at best a 10% gain of increasing our chances of detecting an insider threat.
It also shows that even though action and vector were first thought of ‘green’ for unique record events for a better input selection was actually the opposite for insider threat scenarios that we need to think about multiple events for each incident/alert. In the optimized model many of the weights and tokens used were time correlated specific and action token words
This also tells us that our base data quality for this set is rather low and we would need additional context and possibly sentiment analysis of each user for each unique event which is also an inclusive HR data metric ‘OCEAN’ in the psychometric.csv file. Using tokens through NLP; we would possibly tune to include the column of mixture of nulls to include the website descriptor words from the original data sets and maybe the files.csv that would have to merged into our training set based on time and transaction ID as keys when performing those joins in our data pre-processing
While this section does not show screenshots, the last step in the RapidMiner studio is to deploy the optimized or non-optimized model of your choosing. Deploying locally in the context of studio won’t do much for you other than to re-use a model that you really like and to load new data through the interactions of the Studio application. You would need RapidMiner Server to make local or remote deployments automated to integrate with production applications. We do not illustrate such steps here, but there is great documentation on their site at: https://docs.rapidminer.com/latest/studio/guided/deployments/
Maybe RapidMiner Studio wasn’t for us and everyone talks about Tensorflow (TF) as one of the leading solutions. But, TF does not have a GUI. The new TF v2.0 has Keras API part of the installation which makes interaction in creating the neural net layers much easier along getting your data ingested from Python’s Panda Data Frame into model execution. Let’s get started.
As you recall from our manual steps we start data pre-processing. We re-use the same scenario 2 and data set and will use basic label encoding like we did with our non-optimized model in RapidMiner Studio to show you the comparison in methods and the fact the it’s all statistics at the end of the day based on algorithmic functions converted into libraries. Reusing the screenshot, remember that we did some manual pre-processing work and converted the insiderthreat, vector, and date columns into category numerical values already like so below:
I’ve placed a copy of the semi-scrubbed data on the Github if you wish to review the intermediate dataset prior to us running Python script to pre-process further:
Let’s examine the python code to help us get to the final state we want which is:
The code can be copied below:
import numpy as npimport pandas as pdimport tensorflow as tffrom tensorflow import feature_columnfrom tensorflow.keras import layersfrom sklearn.model_selection import train_test_splitfrom pandas.api.types import CategoricalDtype#Use Pandas to create a dataframe#In windows to get file from path other than same run directory see:#https://stackoverflow.com/questions/16952632/read-a-csv-into-pandas-from-f-drive-on-windows-7URL = 'https://raw.githubusercontent.com/dc401/tensorflow-insiderthreat/master/scenario2-training-dataset-transformed-tf.csv'dataframe = pd.read_csv(URL)#print(dataframe.head())#show dataframe details for column types#print(dataframe.info())#print(pd.unique(dataframe['user']))#https://pbpython.com/categorical-encoding.htmldataframe["user"] = dataframe["user"].astype('category')dataframe["source"] = dataframe["source"].astype('category')dataframe["action"] = dataframe["action"].astype('category')dataframe["user_cat"] = dataframe["user"].cat.codesdataframe["source_cat"] = dataframe["source"].cat.codesdataframe["action_cat"] = dataframe["action"].cat.codes#print(dataframe.info())#print(dataframe.head())#save dataframe with new columns for future datmappingdataframe.to_csv('dataframe-export-allcolumns.csv')#remove old columnsdel dataframe["user"]del dataframe["source"]del dataframe["action"]#restore original names of columnsdataframe.rename(columns={"user_cat": "user", "source_cat": "source", "action_cat": "action"}, inplace=True)print(dataframe.head())print(dataframe.info())#save dataframe cleaned updataframe.to_csv('dataframe-export-int-cleaned.csv')#Split the dataframe into train, validation, and testtrain, test = train_test_split(dataframe, test_size=0.2)train, val = train_test_split(train, test_size=0.2)print(len(train), 'train examples')print(len(val), 'validation examples')print(len(test), 'test examples')#Create an input pipeline using tf.data# A utility method to create a tf.data dataset from a Pandas Dataframedef df_to_dataset(dataframe, shuffle=True, batch_size=32): dataframe = dataframe.copy() labels = dataframe.pop('insiderthreat') ds = tf.data.Dataset.from_tensor_slices((dict(dataframe), labels)) if shuffle: ds = ds.shuffle(buffer_size=len(dataframe)) ds = ds.batch(batch_size) return ds#choose columns needed for calculations (features)feature_columns = []for header in ["vector", "date", "user", "source", "action"]: feature_columns.append(feature_column.numeric_column(header))#create feature layerfeature_layer = tf.keras.layers.DenseFeatures(feature_columns)#set batch size pipelinebatch_size = 32train_ds = df_to_dataset(train, batch_size=batch_size)val_ds = df_to_dataset(val, shuffle=False, batch_size=batch_size)test_ds = df_to_dataset(test, shuffle=False, batch_size=batch_size)#create compile and train modelmodel = tf.keras.Sequential([ feature_layer, layers.Dense(128, activation='relu'), layers.Dense(128, activation='relu'), layers.Dense(1)])model.compile(optimizer='adam', loss=tf.keras.losses.BinaryCrossentropy(from_logits=True), metrics=['accuracy'])model.fit(train_ds, validation_data=val_ds, epochs=5)loss, accuracy = model.evaluate(test_ds)print("Accuracy", accuracy)
In our scenario we’re going to ingest the data from Github. I’ve included in the comment the method of using the os import to do so from a file local to your disk. One thing to point out is that we use the Pandas dataframe construct and methods to manipulate the columns using label encoding for the input. Note that this is not the optimized manner as which RapidMiner Studio reported to us.
We’re still using our same feature set columns in the second round of modeling we re-ran in the previous screens; but this time in Tensorflow for method demonstration.
Note in the above there is an error in how vector still shows ‘object’ in the DType. I was pulling my hair out looking and I found I needed to update the dataset as I did not capture all the values into the vector column as a category numerical like I originally thought. Apparently, I was missing one. Once this was all corrected and errors gone, the model training was ran without a problem.
Unlike RapidMiner Studio, we don’t just have one large training set and let the system do it for us. We must divide the training set into smaller pieces that must be ran through a batch based on the following as a subset for the model to be trained using known correct data of true/false insider threats and a reserved portion that is split which is the remaining being validation only.
Next we need to choose our feature columns, which again is the ‘non optimized’ columns of our 5 columns of data encoded. We use a sampling batch size of 32 in each round of validation (epoch) for the pipeline as we define it early on.
Keep note that we did not execute anything related to the tensor or even create a model yet. This is all just data prep and building the ‘pipeline’ that feeds the tensor. Below is when we create the model using the layers in sequential format using Keras, we compile the model using Google TF’s tutorial demo optimizer and loss functions with an emphasis on accuracy. We try to fit and validate the model with 5 rounds and then print the display.
Welcome to the remaining 10% of your journey in applying AI to your insider threat data set!
Let’s run it again and well — now we see accuracy of around 61% like last time! So again, this just proves that a majority of your outcome will be in the data science process itself and the quality surrounding the pre-processing, tuning, and data. Not so much about which core software solution you go with. Without the optimizing and testing multiple model experimenting simulating in varying feature sets; our primitive models will only be at best 10% better than random chance sampling that a human analyst may or may not catch reviewing the same data.
For simple project tasks that can be accomplished on individual events as an alert vs. an incident using non-domain experts; AI enabled defenders through SOC’s or threat hunting can better achieve ROI faster on things that are considered anomalous or not using baseline data. Examples include anomalies user agent strings that may show C2 infections, or K-means or KNN clustering based on cyber threat intelligence IOC’s that may show specific APT similarities.
There’s some great curated lists found on Github that may give your team ideas on what else they can pursue with some simple methods as we’ve demonstrated in this article. Whatever software solution you elect to use, chances are that our alert payloads really need NLP applied and an appropriately sized neural network created to engage in more accurate modeling. Feel free to modify our base python template and try it out yourself.
I have to admit, I was pretty disappointed in myself at first; even if we knew this was not a tuned model with the labels and input selection I had. But when we cross compare it with other more complex datasets and models in the communities such as Kaggle: It really isn’t as bad as we first thought.
Microsoft hosted a malware detection competition to the community and provided enriched datasets. The competition highest scores show 67% prediction accuracy and this was in 2019 with over 2400 teams competing. One member shared their code which had a 63% score and was released free and to the public as a great template if you wanted to investigate further. He titles LightGBM.
Compared to the leaderboard points the public facing solution was only 5% “worse.” Is a 5% difference a huge amount in the world of data science? Yes (though it depends also how you measure confidence levels). So out of 2400+ teams, the best model achieved a success accuracy of ~68%. But from a budgeting ROI stand point when a CISO asks for their next FY’s CAPEX — 68% isn’t going to cut it for most security programs.
While somewhat discouraging, it’s important to remember that there are dedicated data science and dev ops professionals that spend their entire careers doing this to get models u to the 95% or better range. To achieve this, tons of model testing, additional data, and additional featureset extraction is required (as we saw in RapidMiner Studio doing this automatically for us).
Obviously, this is a complex task. Researchers at the Deakin University in published a paper called “Image-Based Feature Representation for Insider Threat Classification” which was mentioned briefly in the earlier portion of the article. They discuss the measures that they have had to create a feature set based on an extended amount of data provided by the same US-CERT CMU dataset and they created ‘images’ out of it that can be used for prediction classification where they achieved 98% accuracy.
Within the paper the researchers also discussed examination of prior models such as ‘BAIT’ for insider threat which at best a 70% accuracy also using imbalanced data. Security programs with enough budget can have in-house models made from scratch with the help of data scientists and dev ops engineers that can use this research paper into applicable code.
Focus less on the solution and more on the data science and pre-processing. I took the EdX Data8x Courseware (3 in total) and the book referenced (also free) provides great details and methods anyone can use to properly examine data and know what they’re looking at during the process. This course set and among others can really augment and enhance existing cyber security skills to prepare us to do things like:
Evaluate vendors providing ‘AI’ enabled services and solutions on their actual effectiveness such as asking questions into what data pre-processing, feature sets, model architecture and optimization functions are used
Build use cases and augment their SOC or threat hunt programs with more informed choices of AI specific modeling on what is considered anomalous
Be able to pipeline and automate high quality data into proven tried-and-true models for highly effective alerting and response
I hope you’ve enjoyed this article and tutorial brief on cyber security applications of insider threats or really any data set into a neural network using two different solutions. If you’re interested in professional services or an MSSP to bolster your organization’s cyber security please feel free to contact us at www.scissecurity.com | [
{
"code": null,
"e": 902,
"s": 172,
"text": "This technical article will teach you how to pre-process data, create your own neural networks, and train and evaluate models using the US-CERT’s simulated insider threat dataset. The methods and solutions are designed for non-domain experts; particularly cyber security professionals. We will start our journey with the raw data provided by the dataset and provide examples of different pre-processing methods to get it “ready” for the AI solution to ingest. We will ultimately create models that can be re-used for additional predictions based on security events. Throughout the article, I will also point out the applicability and return on investment depending on your existing Information Security program in the enterprise."
},
{
"code": null,
"e": 1245,
"s": 902,
"text": "Note: To use and replicate the pre-processed data and steps we use, prepare to spend 1–2 hours on this page. Stay with me and try not to fall asleep during the data pre-processing portion. What many tutorials don’t state is that if you’re starting from scratch; data pre-processing takes up to 90% of your time when doing projects like these."
},
{
"code": null,
"e": 1316,
"s": 1245,
"text": "At the end of this hybrid article and tutorial, you should be able to:"
},
{
"code": null,
"e": 1419,
"s": 1316,
"text": "Pre-process the data provided from US-CERT into an AI solution ready format (Tensorflow in particular)"
},
{
"code": null,
"e": 1537,
"s": 1419,
"text": "Use RapidMiner Studio and Tensorflow 2.0 + Keras to create and train a model using a pre-processed sample CSV dataset"
},
{
"code": null,
"e": 1689,
"s": 1537,
"text": "Perform basic analysis of your data, chosen fields for AI evaluation, and understand the practicality for your organization using the methods described"
},
{
"code": null,
"e": 1970,
"s": 1689,
"text": "The author provides these methods, insights, and recommendations *as is* and makes no claim of warranty. Please do not use the models you create in this tutorial in a production environment without sufficient tuning and analysis before making them a part of your security program."
},
{
"code": null,
"e": 2118,
"s": 1970,
"text": "If you wish to follow along and perform these activities yourself, please download and install the following tools from their respective locations:"
},
{
"code": null,
"e": 2350,
"s": 2118,
"text": "Choose: To be hands on from scratch and experiment with your own variations of data: download the full dataset: ftp://ftp.sei.cmu.edu/pub/cert-data: *Caution: it is very large. Please plan to have several hundred gigs of free space"
},
{
"code": null,
"e": 2603,
"s": 2350,
"text": "Choose: If you just want to follow along execute what I’ve done, you can download the pre-processed data, Python, and solution files from my Github (click repositories and find tensorflow-insiderthreat) https://github.com/dc401/tensorflow-insiderthreat"
},
{
"code": null,
"e": 2731,
"s": 2603,
"text": "Optional: if you want a nice IDE for Python: Visual Studio 2019 Community Edition with the applicable Python extensions install"
},
{
"code": null,
"e": 2811,
"s": 2731,
"text": "Required: Rapidminer Studio Trial (or educational license if it applies to you)"
},
{
"code": null,
"e": 2879,
"s": 2811,
"text": "Required: Python environment , use the Python 3.8.3 x64 bit release"
},
{
"code": null,
"e": 3004,
"s": 2879,
"text": "Required: Install python packages: (numpy, pandas, tensorflow, sklearn via “pip install <packagename>” from the command line"
},
{
"code": null,
"e": 3339,
"s": 3004,
"text": "It’s important for newcomers to any data science discipline to know that the majority of your time spent will be in data pre-processing and analyzing what you have which includes cleaning up the data, normalizing, extracting any additional meta insights, and then encoding the data so that it is ready for an AI solution to ingest it."
},
{
"code": null,
"e": 4042,
"s": 3339,
"text": "We need to extract and process the dataset in such a way where it is structured with fields that we may need as ‘features’ which is just to be inclusive in the AI model we create. We will need to ensure all the text strings are encoded into numbers so the engine we use can ingest it. We will also have to mark which are insider threat and non-threat rows (true positives, and true negatives).Next, after data pre-processing we’ll need select, setup, and create the functions we will use to create the model and create the neural network layers itselfGenerate the model; and examine the accuracy, applicability, and identify additional modifications or tuning needed in any of part of the data pipeline"
},
{
"code": null,
"e": 4436,
"s": 4042,
"text": "We need to extract and process the dataset in such a way where it is structured with fields that we may need as ‘features’ which is just to be inclusive in the AI model we create. We will need to ensure all the text strings are encoded into numbers so the engine we use can ingest it. We will also have to mark which are insider threat and non-threat rows (true positives, and true negatives)."
},
{
"code": null,
"e": 4595,
"s": 4436,
"text": "Next, after data pre-processing we’ll need select, setup, and create the functions we will use to create the model and create the neural network layers itself"
},
{
"code": null,
"e": 4747,
"s": 4595,
"text": "Generate the model; and examine the accuracy, applicability, and identify additional modifications or tuning needed in any of part of the data pipeline"
},
{
"code": null,
"e": 4960,
"s": 4747,
"text": "Examining the raw US-CERT data requires you to download compressed files that must be extracted. Note just how large the sets are compared to how much we will use and reduce at the end of the data pre-processing."
},
{
"code": null,
"e": 5453,
"s": 4960,
"text": "In our article, we saved a bunch of time by going directly to the answers.tar.bz2 that has the insiders.csv file for matching which datasets and individual extracted records of are value. Now, it is worth stating that in the index provided there has correlated record numbers in extended data such as the file, and psychometric related data. We didn’t use the extended meta in this tutorial brief because of the extra time to correlate and consolidate all of it into a single CSV in our case."
},
{
"code": null,
"e": 5743,
"s": 5453,
"text": "To see a more comprehensive set of feature sets extracted from this same data, consider checking out this research paper called “Image-Based Feature Representation for Insider Threat Classification.” We’ll be referring to that paper later in the article when we examine our model accuracy."
},
{
"code": null,
"e": 6080,
"s": 5743,
"text": "Before getting the data encoded and ready for a function to read it; we need to get the data extracted and categorized into columns that we need to predict one. Let’s use good old Excel to insert a column into the CSV. Prior to the screenshot we took and added all the rows from the referenced datasets in “insiders.csv” for scenario 2."
},
{
"code": null,
"e": 6117,
"s": 6080,
"text": "Insiders.csv index of true positives"
},
{
"code": null,
"e": 6367,
"s": 6117,
"text": "The scenario (2) is described in scenarios.txt: “User begins surfing job websites and soliciting employment from a competitor. Before leaving the company, they use a thumb drive (at markedly higher rates than their previous activity) to steal data.”"
},
{
"code": null,
"e": 6478,
"s": 6367,
"text": "Examine our pre-processed data that includes its intermediary and final forms as shown in the following below:"
},
{
"code": null,
"e": 6538,
"s": 6478,
"text": "Intermediate composite true positive records for scenario 2"
},
{
"code": null,
"e": 7100,
"s": 6538,
"text": "In the above photo, this is a snippet of all the different record types essentially appended to each other and properly sorted by date. Note that different vectors (http vs. email vs. device) do not all align easily have different contexts in the columns. This is not optimal by any means but since the insider threat scenario includes multiple event types; this is what we’ll have to work with for now. This is the usual case with data that you’ll get trying to correlate based on time and multiple events tied to a specific attribute or user like a SIEM does."
},
{
"code": null,
"e": 7164,
"s": 7100,
"text": "Comparison of different data types that have to be consolidated"
},
{
"code": null,
"e": 7418,
"s": 7164,
"text": "In the aggregation set; we combined the relevant CSV’s after moving all of the items mentioned from the insiders.csv for scenario 2 into the same folder. To formulate the entire ‘true positive’ only dataset portion; we’ve used powershell as shown below:"
},
{
"code": null,
"e": 7463,
"s": 7418,
"text": "Using powershell to merge the CSV’s together"
},
{
"code": null,
"e": 8138,
"s": 7463,
"text": "Right now we have a completely imbalanced dataset where we only have true positives. We’ll also have to add true negatives and the best approach is to have an equal amount of record types representing in a 50/50 scenario of non-threat activity. This is almost never the case with security data so we’ll do what we can as you’ll find below. I also want to point out, that if you’re doing manual data processing in an OS shell — whatever you import into a variable is in memory and does not get released or garbage collected by itself as you can see from my PowerShell memory consumption after a bunch of data manipulation and CSV wrangling, I’ve bumped up my usage to 5.6 GB."
},
{
"code": null,
"e": 8217,
"s": 8138,
"text": "Memory isn’t released automatically. We also count the lines in each CSV file."
},
{
"code": null,
"e": 8478,
"s": 8217,
"text": "Let’s look at the R1 dataset files. We’ll need to pull from that we know are confirmed true negatives (non-threats) for each of the 3 types from filenames we used in the true positive dataset extracts (again, it’s from the R1 dataset which have benign events)."
},
{
"code": null,
"e": 8717,
"s": 8478,
"text": "We’ll merge a number of records from all 3 of the R1 true negative data sets from logon, http, and device files. Note, that in the R1 true negative set, we did not find an emails CSV which adds to the imbalance for our aggregate data set."
},
{
"code": null,
"e": 9129,
"s": 8717,
"text": "Using PowerShell we count the length of lines in each file. Since we had about ~14K of rows from the true positive side, I arbitrarily took from the true negative side the first 4500 applicable rows from each subsequent file and appended them to the training dataset so that we have both true positives, and true negatives mixed in. We’ll have to add a column to mark which is a insider threat and which aren’t."
},
{
"code": null,
"e": 9193,
"s": 9129,
"text": "Extracting records of true negatives from 3 complementing CSV’s"
},
{
"code": null,
"e": 9542,
"s": 9193,
"text": "In pre-processing our data we’ve already added all the records of interest below and selected various other true-negative non-threat records from the R1 dataset. Now we have our baseline of threats and non-threats concatenated in a single CSV. To the left, we’ve added a new column to denote a true/false or (1 or 0) in a find and replace scenario."
},
{
"code": null,
"e": 9594,
"s": 9542,
"text": "Label encoding the insider threat True/False Column"
},
{
"code": null,
"e": 10164,
"s": 9594,
"text": "Above, you can also see we started changing true/false strings to numerical categories. This is us beginning on our path to encode the data through manual pre-processing which we could save ourselves the hassle as we see in future steps in RapidMiner Studio and using the Pandas Dataframe library in Python for Tensorflow. We just wanted to illustrate some of the steps and considerations you’ll have to perform. Following this, we will continue processing our data for a bit. Let’s highlight what we can do using excel functions before going the fully automated route."
},
{
"code": null,
"e": 10224,
"s": 10164,
"text": "Calculating Unix Epoch Time from the Date and Time Provided"
},
{
"code": null,
"e": 10688,
"s": 10224,
"text": "We’re also manually going to convert the date field into Unix Epoch Time for the sake of demonstration and as you seen it becomes a large integer with a new column. To remove the old column in excel for rename, create a new sheet such as ‘scratch’ and cut the old date (non epoch timestamp) values into that sheet. Reference the sheet along with the formula you see in the cell to achieve this effect. This formula is: “=(C2-DATE(1970,1,1))*86400” without quotes."
},
{
"code": null,
"e": 10742,
"s": 10688,
"text": "Encoding the vector column and feature set column map"
},
{
"code": null,
"e": 11127,
"s": 10742,
"text": "In our last manual pre-processing work example you need to format the CSV in is to ‘categorize’ by label encoding the data. You can automate this as one-hot encoding methods via a data dictionary in a script or in our case we show you the manual method of mapping this in excel since we have a finite set of vectors of the records of interest (http is 0, email is 1, and device is 2)."
},
{
"code": null,
"e": 11644,
"s": 11127,
"text": "You’ll notice that we have not done the user, source, or action columns as it has a very large number of unique values that need label encoding and it’s just impractical by hand. We were able to accomplish this without all the manual wrangling above using the ‘turbo prep’ feature of RapidMiner Studio and likewise for the remaining columns via Python’s Panda in our script snippet below. Don’t worry about this for now, we will show case the steps in each different AI tool and up doing the same thing the easy way."
},
{
"code": null,
"e": 12446,
"s": 11644,
"text": "#print(pd.unique(dataframe['user']))#https://pbpython.com/categorical-encoding.htmldataframe[\"user\"] = dataframe[\"user\"].astype('category')dataframe[\"source\"] = dataframe[\"source\"].astype('category')dataframe[\"action\"] = dataframe[\"action\"].astype('category')dataframe[\"user_cat\"] = dataframe[\"user\"].cat.codesdataframe[\"source_cat\"] = dataframe[\"source\"].cat.codesdataframe[\"action_cat\"] = dataframe[\"action\"].cat.codes#print(dataframe.info())#print(dataframe.head())#save dataframe with new columns for future datmappingdataframe.to_csv('dataframe-export-allcolumns.csv')#remove old columnsdel dataframe[\"user\"]del dataframe[\"source\"]del dataframe[\"action\"]#restore original names of columnsdataframe.rename(columns={\"user_cat\": \"user\", \"source_cat\": \"source\", \"action_cat\": \"action\"}, inplace=True)"
},
{
"code": null,
"e": 12780,
"s": 12446,
"text": "The above snippet is the using python’s panda library example of manipulating and label encoding the columns into numerical values unique to each string value in the original data set. Try not to get caught up in this yet. We’re going to show you the easy and comprehensive approach of all this data science work in Rapidminer Studio"
},
{
"code": null,
"e": 13677,
"s": 12780,
"text": "Important step for defenders: Given that we’re using the pre-simulated dataset that has been formatted from US-CERT, not every SOC is going to have access to the same uniform data for their own security events. Many times your SOC will have only raw logs to export. From an ROI perspective — before pursuing your own DIY project like this, consider the level of effort and if you can automate exporting meta of your logs into a CSV format, an enterprise solution as Splunk or another SIEM might be able to do this for you. You would have to correlate your events and add as many columns as possible for enriched data formatting. You would also have to examine how consistent and how you can automate exporting this data in a format that US-CERT has to use similar methods for pre-processing or ingestion. Make use of your SIEM’s API features to export reports into a CSV format whenever possible."
},
{
"code": null,
"e": 13996,
"s": 13677,
"text": "It’s time use to some GUI based and streamlined approaches. The desktop edition of RapidMiner is Studio and the latest editions as of 9.6.x have turbo prep and auto modeling built in as part of your workflows. Since we’re not domain experts, we are definitely going to take advantage of using this. Let’s dig right in."
},
{
"code": null,
"e": 14399,
"s": 13996,
"text": "Note: If your trial expired before getting to this tutorial and use community edition, you will be limited to 10,000 rows. Further pre-processing is required to limit your datasets to 5K of true positives, and 5K of true negatives including the header. If applicable, use an educational license which is unlimited and renewable each year that you enrolled in a qualifying institution with a .edu email."
},
{
"code": null,
"e": 14417,
"s": 14399,
"text": "RapidMiner Studio"
},
{
"code": null,
"e": 14732,
"s": 14417,
"text": "Upon starting we’re going to start a new project and utilize the Turbo Prep feature. You can use other methods or the manual way of selecting operators via the GUI in the bottom left for the community edition. However, we’re going to use the enterprise trial because it’s easy to walk through for first-time users."
},
{
"code": null,
"e": 14776,
"s": 14732,
"text": "Import the Non-Processed CSV Aggregate File"
},
{
"code": null,
"e": 15072,
"s": 14776,
"text": "We’ll import our aggregate CSV of true positive only data non-processed; and also remove the first row headers and use our own because the original row relates to the HTTP vector and does not apply to subsequent USB device connection and Email related records also in the dataset as shown below."
},
{
"code": null,
"e": 15382,
"s": 15072,
"text": "Note: Unlike our pre-processing steps which includes label encodings and reduction, we did not do this yet on RapidMiner Studio to show the full extent of what we can easily do in the ‘turbo prep’ feature. We’re going to enable the use of quotes as well and leave the other defaults for proper string escapes."
},
{
"code": null,
"e": 15452,
"s": 15382,
"text": "Next, we set our column header types to their appropriate data types."
},
{
"code": null,
"e": 15906,
"s": 15452,
"text": "Stepping through the wizard we arrive at the turbo prep tab for review and it shows us distribution and any errors such as missing values that need to be adjusted and which columns might be problematic. Let’s start with making sure we identify all of these true positives as insider threats to begin with. Click on generate and we’re going to transform this dataset by inserting a new column in all the rows with a logical ‘true’ statement like so below"
},
{
"code": null,
"e": 16124,
"s": 15906,
"text": "We’ll save the column details and export it for further processing later or we’ll use it as a base template set for when we begin to pre-process for the Tensorflow method following this to make things a little easier."
},
{
"code": null,
"e": 16350,
"s": 16124,
"text": "After the export as you can see above, don’t forget we need to balance the data with true negatives. We’ll repeat the same process of importing the true negatives. Now we should see multiple datasets in our turbo prep screen."
},
{
"code": null,
"e": 16614,
"s": 16350,
"text": "In the above, even though we’ve only imported 2 datasets, remember transformed the true positive by adding a column called insiderthreat which is a true/false boolean logic. We do the same with true negatives and you’ll eventually end up with 4 of these listings."
},
{
"code": null,
"e": 17045,
"s": 16614,
"text": "We’ll need to merge the true positives and true negatives into a ‘training set’ before we get to do anything fun with it. But first, we also need to drop columns that we don’t think are relevant our useful such as the transaction ID and the description column of the website keywords scraped as none of the other row data have these; and and would contain a bunch of empty (null) values that aren’t useful for calculation weights."
},
{
"code": null,
"e": 17673,
"s": 17045,
"text": "Important thought: As we’ve mentioned regarding other research papers, choosing columns for calculation aka ‘feature sets’ that include complex strings have to be tokenized using natural language processing (NLP). This adds to your pre-processing requirements in additional to label encoding in which in the Tensorflow + Pandas Python method would usually require wrangling multiple data frames and merging them together based on column keys for each record. While this is automated for you in RapidMiner, in Tensorflow you’ll have to include this in your pre-processing script. More documentation about this can be found here."
},
{
"code": null,
"e": 18050,
"s": 17673,
"text": "Take note that we did not do this in our datasets because you’ll see much later in an optimized RapidMiner Studio recommendation that heavier weight and emphasis on the date and time are were more efficient feature sets with less complexity. You on other hand on different datasets and applications may need to NLP for sentiment analysis to add to the insider threat modeling."
},
{
"code": null,
"e": 18342,
"s": 18050,
"text": "Finishing your training set: Although we do not illustrate this, after you have imported both true negatives and true positives within the Turbo prep menu click on the “merge” button and select both transformed datasets and select the “Append” option since both have been pre-sorted by date."
},
{
"code": null,
"e": 18577,
"s": 18342,
"text": "Within RapidMiner Studio we continue to the ‘Auto Model’ tab and utilize our selected aggregate ‘training’ data (remember training data includes true positives and true negatives) to predict on the insiderthreat column (true or false)"
},
{
"code": null,
"e": 18878,
"s": 18577,
"text": "We also notice what our actual balance is. We are still imbalanced with only 9,001 records of non-threats vs. threats of ~14K. It’s imbalanced and that can always be padded with additional records should you choose. For now, we’ll live with it and see what we can accomplish with not-so-perfect data."
},
{
"code": null,
"e": 19109,
"s": 18878,
"text": "Here the auto modeler recommends different feature columns in green and yellow and their respective correlation. The interesting thing is that it is estimating date is of high correlation but less stability than action and vector."
},
{
"code": null,
"e": 19553,
"s": 19109,
"text": "Important thought: In our head, we would think as defenders all of the feature set applies in each column as we’ve already reduced what we could as far as relevance and complexities. It’s also worth mentioning that this is based off a single event. Remember insider threats often take multiple events as we saw in the answers portion of the insiders.csv . What the green indicators are showing us are unique record single event identification."
},
{
"code": null,
"e": 19888,
"s": 19553,
"text": "We’re going to use all the columns anyways because we think it’s all relevant columns to use. We also move to the next screen on model types, and because we’re not domain experts we’re going to try almost all of them and we want the computer to re-run each model multiple times finding the optimized set of inputs and feature columns."
},
{
"code": null,
"e": 20329,
"s": 19888,
"text": "Remember that feature sets can include meta information based on insights from existing columns. We leave the default values of tokenization and we want to extract date and text information. Obviously the items with the free-form text are the ‘Action’ column with all the different URLs, and event activity that we want NLP to be applied. And we want to correlate between columns, the importance of columns, and explain predictions as well."
},
{
"code": null,
"e": 20757,
"s": 20329,
"text": "Note that in the above we’ve pretty much selected bunch of heavy processing parameters in our batch job. On an 8 core single threadded processor running Windows 10, 24 GB memory and a GPU of a Radeon RX570 value series with SSD’s all of these models took about 6 hours to run total with all the options set. After everything was completed we have 8000+ models and 2600+ feature set combinations tested in our screen comparison."
},
{
"code": null,
"e": 21125,
"s": 20757,
"text": "According to RapidMiner Studio; the deep learning neural network methods aren’t the best ROI fit; compared to the linear general model. There are no errors though- and that’s worrisome which might mean that we have poor quality data or an overfit issue with the model. Let’s take a look at deep learning as it also states a potential 100% accuracy just to compare it."
},
{
"code": null,
"e": 21558,
"s": 21125,
"text": "In the Deep Learning above it’s tested against 187 different combinations of feature sets and the optimized model shows that unlike our own thoughts as to what features would be good including the vector and action mostly. We see even more weight put on the tokens in Action interesting words and the dates. Surprisingly; we did not see anything related to “email” or the word “device” in the actions as part of the optimized model."
},
{
"code": null,
"e": 21910,
"s": 21558,
"text": "Not to worry, as this doesn’t mean we’re dead wrong. It just means the feature sets it selected in its training (columns and extracted meta columns) provided less errors in the training set. This could be that we don’t have enough diverse or high quality data in our set. In the previous screen above you saw an orange circle and a translucent square."
},
{
"code": null,
"e": 22399,
"s": 21910,
"text": "The orange circle indicates the models suggested optimizer function and the square is our original selected feature set. If you examine the scale, our human selected feature set was an error rate of 0.9 and 1% which gives our accuracy closer to the 99% mark; but only at a much higher complexity model (more layers and connections in the neural net required) That makes me feel a little better and just goes to show you that caution is needed when interpreting all of these at face value."
},
{
"code": null,
"e": 22812,
"s": 22399,
"text": "Let’s say you don’t fully trust such a highly “100% accurate model”. We can try to re-run it using our feature sets in vanilla manner as a pure token label. We’re *not* going extract date information, no text tokenization via NLP and we don’t want it to automatically create new feature set meta based on our original selections. Basically, we’re going to use a plain vanilla set of columns for the calculations."
},
{
"code": null,
"e": 23084,
"s": 22812,
"text": "So in the above let’s re-run it looking at 3 different models including the original best fit model and the deep learning we absolutely no optimization and additional NLP applied. So it’s as if we only used encoded label values only in the calculations and not much else."
},
{
"code": null,
"e": 23493,
"s": 23084,
"text": "In the above, we get even worse results with an error rate of 39% is a 61% accuracy across pretty much all the models. Our selection and lack of complexity without using text token extraction is so reduced that even a more “primitive” Bayesian model (commonly used in basic email spam filter engines) seems to be just as accurate and has a fast compute time. This all looks bad but let’s dig a little deeper:"
},
{
"code": null,
"e": 23736,
"s": 23493,
"text": "When we select the details of the deep learning model again we see the accuracy climb in linear fashion as more of the training set population is discovered and validated against. From an interpretation stand point this shows us a few things:"
},
{
"code": null,
"e": 24074,
"s": 23736,
"text": "Our original primitive thoughts of feature sets of focusing on the vector and action frequency using only unique encoded values is about as only as good as a toss-up probability of an analyst finding a threat in the data. On the surface it appears that we have at best a 10% gain of increasing our chances of detecting an insider threat."
},
{
"code": null,
"e": 24443,
"s": 24074,
"text": "It also shows that even though action and vector were first thought of ‘green’ for unique record events for a better input selection was actually the opposite for insider threat scenarios that we need to think about multiple events for each incident/alert. In the optimized model many of the weights and tokens used were time correlated specific and action token words"
},
{
"code": null,
"e": 25027,
"s": 24443,
"text": "This also tells us that our base data quality for this set is rather low and we would need additional context and possibly sentiment analysis of each user for each unique event which is also an inclusive HR data metric ‘OCEAN’ in the psychometric.csv file. Using tokens through NLP; we would possibly tune to include the column of mixture of nulls to include the website descriptor words from the original data sets and maybe the files.csv that would have to merged into our training set based on time and transaction ID as keys when performing those joins in our data pre-processing"
},
{
"code": null,
"e": 25641,
"s": 25027,
"text": "While this section does not show screenshots, the last step in the RapidMiner studio is to deploy the optimized or non-optimized model of your choosing. Deploying locally in the context of studio won’t do much for you other than to re-use a model that you really like and to load new data through the interactions of the Studio application. You would need RapidMiner Server to make local or remote deployments automated to integrate with production applications. We do not illustrate such steps here, but there is great documentation on their site at: https://docs.rapidminer.com/latest/studio/guided/deployments/"
},
{
"code": null,
"e": 26012,
"s": 25641,
"text": "Maybe RapidMiner Studio wasn’t for us and everyone talks about Tensorflow (TF) as one of the leading solutions. But, TF does not have a GUI. The new TF v2.0 has Keras API part of the installation which makes interaction in creating the neural net layers much easier along getting your data ingested from Python’s Panda Data Frame into model execution. Let’s get started."
},
{
"code": null,
"e": 26560,
"s": 26012,
"text": "As you recall from our manual steps we start data pre-processing. We re-use the same scenario 2 and data set and will use basic label encoding like we did with our non-optimized model in RapidMiner Studio to show you the comparison in methods and the fact the it’s all statistics at the end of the day based on algorithmic functions converted into libraries. Reusing the screenshot, remember that we did some manual pre-processing work and converted the insiderthreat, vector, and date columns into category numerical values already like so below:"
},
{
"code": null,
"e": 26724,
"s": 26560,
"text": "I’ve placed a copy of the semi-scrubbed data on the Github if you wish to review the intermediate dataset prior to us running Python script to pre-process further:"
},
{
"code": null,
"e": 26806,
"s": 26724,
"text": "Let’s examine the python code to help us get to the final state we want which is:"
},
{
"code": null,
"e": 26836,
"s": 26806,
"text": "The code can be copied below:"
},
{
"code": null,
"e": 30050,
"s": 26836,
"text": "import numpy as npimport pandas as pdimport tensorflow as tffrom tensorflow import feature_columnfrom tensorflow.keras import layersfrom sklearn.model_selection import train_test_splitfrom pandas.api.types import CategoricalDtype#Use Pandas to create a dataframe#In windows to get file from path other than same run directory see:#https://stackoverflow.com/questions/16952632/read-a-csv-into-pandas-from-f-drive-on-windows-7URL = 'https://raw.githubusercontent.com/dc401/tensorflow-insiderthreat/master/scenario2-training-dataset-transformed-tf.csv'dataframe = pd.read_csv(URL)#print(dataframe.head())#show dataframe details for column types#print(dataframe.info())#print(pd.unique(dataframe['user']))#https://pbpython.com/categorical-encoding.htmldataframe[\"user\"] = dataframe[\"user\"].astype('category')dataframe[\"source\"] = dataframe[\"source\"].astype('category')dataframe[\"action\"] = dataframe[\"action\"].astype('category')dataframe[\"user_cat\"] = dataframe[\"user\"].cat.codesdataframe[\"source_cat\"] = dataframe[\"source\"].cat.codesdataframe[\"action_cat\"] = dataframe[\"action\"].cat.codes#print(dataframe.info())#print(dataframe.head())#save dataframe with new columns for future datmappingdataframe.to_csv('dataframe-export-allcolumns.csv')#remove old columnsdel dataframe[\"user\"]del dataframe[\"source\"]del dataframe[\"action\"]#restore original names of columnsdataframe.rename(columns={\"user_cat\": \"user\", \"source_cat\": \"source\", \"action_cat\": \"action\"}, inplace=True)print(dataframe.head())print(dataframe.info())#save dataframe cleaned updataframe.to_csv('dataframe-export-int-cleaned.csv')#Split the dataframe into train, validation, and testtrain, test = train_test_split(dataframe, test_size=0.2)train, val = train_test_split(train, test_size=0.2)print(len(train), 'train examples')print(len(val), 'validation examples')print(len(test), 'test examples')#Create an input pipeline using tf.data# A utility method to create a tf.data dataset from a Pandas Dataframedef df_to_dataset(dataframe, shuffle=True, batch_size=32): dataframe = dataframe.copy() labels = dataframe.pop('insiderthreat') ds = tf.data.Dataset.from_tensor_slices((dict(dataframe), labels)) if shuffle: ds = ds.shuffle(buffer_size=len(dataframe)) ds = ds.batch(batch_size) return ds#choose columns needed for calculations (features)feature_columns = []for header in [\"vector\", \"date\", \"user\", \"source\", \"action\"]: feature_columns.append(feature_column.numeric_column(header))#create feature layerfeature_layer = tf.keras.layers.DenseFeatures(feature_columns)#set batch size pipelinebatch_size = 32train_ds = df_to_dataset(train, batch_size=batch_size)val_ds = df_to_dataset(val, shuffle=False, batch_size=batch_size)test_ds = df_to_dataset(test, shuffle=False, batch_size=batch_size)#create compile and train modelmodel = tf.keras.Sequential([ feature_layer, layers.Dense(128, activation='relu'), layers.Dense(128, activation='relu'), layers.Dense(1)])model.compile(optimizer='adam', loss=tf.keras.losses.BinaryCrossentropy(from_logits=True), metrics=['accuracy'])model.fit(train_ds, validation_data=val_ds, epochs=5)loss, accuracy = model.evaluate(test_ds)print(\"Accuracy\", accuracy)"
},
{
"code": null,
"e": 30443,
"s": 30050,
"text": "In our scenario we’re going to ingest the data from Github. I’ve included in the comment the method of using the os import to do so from a file local to your disk. One thing to point out is that we use the Pandas dataframe construct and methods to manipulate the columns using label encoding for the input. Note that this is not the optimized manner as which RapidMiner Studio reported to us."
},
{
"code": null,
"e": 30611,
"s": 30443,
"text": "We’re still using our same feature set columns in the second round of modeling we re-ran in the previous screens; but this time in Tensorflow for method demonstration."
},
{
"code": null,
"e": 31005,
"s": 30611,
"text": "Note in the above there is an error in how vector still shows ‘object’ in the DType. I was pulling my hair out looking and I found I needed to update the dataset as I did not capture all the values into the vector column as a category numerical like I originally thought. Apparently, I was missing one. Once this was all corrected and errors gone, the model training was ran without a problem."
},
{
"code": null,
"e": 31392,
"s": 31005,
"text": "Unlike RapidMiner Studio, we don’t just have one large training set and let the system do it for us. We must divide the training set into smaller pieces that must be ran through a batch based on the following as a subset for the model to be trained using known correct data of true/false insider threats and a reserved portion that is split which is the remaining being validation only."
},
{
"code": null,
"e": 31627,
"s": 31392,
"text": "Next we need to choose our feature columns, which again is the ‘non optimized’ columns of our 5 columns of data encoded. We use a sampling batch size of 32 in each round of validation (epoch) for the pipeline as we define it early on."
},
{
"code": null,
"e": 32074,
"s": 31627,
"text": "Keep note that we did not execute anything related to the tensor or even create a model yet. This is all just data prep and building the ‘pipeline’ that feeds the tensor. Below is when we create the model using the layers in sequential format using Keras, we compile the model using Google TF’s tutorial demo optimizer and loss functions with an emphasis on accuracy. We try to fit and validate the model with 5 rounds and then print the display."
},
{
"code": null,
"e": 32167,
"s": 32074,
"text": "Welcome to the remaining 10% of your journey in applying AI to your insider threat data set!"
},
{
"code": null,
"e": 32723,
"s": 32167,
"text": "Let’s run it again and well — now we see accuracy of around 61% like last time! So again, this just proves that a majority of your outcome will be in the data science process itself and the quality surrounding the pre-processing, tuning, and data. Not so much about which core software solution you go with. Without the optimizing and testing multiple model experimenting simulating in varying feature sets; our primitive models will only be at best 10% better than random chance sampling that a human analyst may or may not catch reviewing the same data."
},
{
"code": null,
"e": 33185,
"s": 32723,
"text": "For simple project tasks that can be accomplished on individual events as an alert vs. an incident using non-domain experts; AI enabled defenders through SOC’s or threat hunting can better achieve ROI faster on things that are considered anomalous or not using baseline data. Examples include anomalies user agent strings that may show C2 infections, or K-means or KNN clustering based on cyber threat intelligence IOC’s that may show specific APT similarities."
},
{
"code": null,
"e": 33619,
"s": 33185,
"text": "There’s some great curated lists found on Github that may give your team ideas on what else they can pursue with some simple methods as we’ve demonstrated in this article. Whatever software solution you elect to use, chances are that our alert payloads really need NLP applied and an appropriately sized neural network created to engage in more accurate modeling. Feel free to modify our base python template and try it out yourself."
},
{
"code": null,
"e": 33920,
"s": 33619,
"text": "I have to admit, I was pretty disappointed in myself at first; even if we knew this was not a tuned model with the labels and input selection I had. But when we cross compare it with other more complex datasets and models in the communities such as Kaggle: It really isn’t as bad as we first thought."
},
{
"code": null,
"e": 34300,
"s": 33920,
"text": "Microsoft hosted a malware detection competition to the community and provided enriched datasets. The competition highest scores show 67% prediction accuracy and this was in 2019 with over 2400 teams competing. One member shared their code which had a 63% score and was released free and to the public as a great template if you wanted to investigate further. He titles LightGBM."
},
{
"code": null,
"e": 34721,
"s": 34300,
"text": "Compared to the leaderboard points the public facing solution was only 5% “worse.” Is a 5% difference a huge amount in the world of data science? Yes (though it depends also how you measure confidence levels). So out of 2400+ teams, the best model achieved a success accuracy of ~68%. But from a budgeting ROI stand point when a CISO asks for their next FY’s CAPEX — 68% isn’t going to cut it for most security programs."
},
{
"code": null,
"e": 35100,
"s": 34721,
"text": "While somewhat discouraging, it’s important to remember that there are dedicated data science and dev ops professionals that spend their entire careers doing this to get models u to the 95% or better range. To achieve this, tons of model testing, additional data, and additional featureset extraction is required (as we saw in RapidMiner Studio doing this automatically for us)."
},
{
"code": null,
"e": 35601,
"s": 35100,
"text": "Obviously, this is a complex task. Researchers at the Deakin University in published a paper called “Image-Based Feature Representation for Insider Threat Classification” which was mentioned briefly in the earlier portion of the article. They discuss the measures that they have had to create a feature set based on an extended amount of data provided by the same US-CERT CMU dataset and they created ‘images’ out of it that can be used for prediction classification where they achieved 98% accuracy."
},
{
"code": null,
"e": 35958,
"s": 35601,
"text": "Within the paper the researchers also discussed examination of prior models such as ‘BAIT’ for insider threat which at best a 70% accuracy also using imbalanced data. Security programs with enough budget can have in-house models made from scratch with the help of data scientists and dev ops engineers that can use this research paper into applicable code."
},
{
"code": null,
"e": 36372,
"s": 35958,
"text": "Focus less on the solution and more on the data science and pre-processing. I took the EdX Data8x Courseware (3 in total) and the book referenced (also free) provides great details and methods anyone can use to properly examine data and know what they’re looking at during the process. This course set and among others can really augment and enhance existing cyber security skills to prepare us to do things like:"
},
{
"code": null,
"e": 36590,
"s": 36372,
"text": "Evaluate vendors providing ‘AI’ enabled services and solutions on their actual effectiveness such as asking questions into what data pre-processing, feature sets, model architecture and optimization functions are used"
},
{
"code": null,
"e": 36735,
"s": 36590,
"text": "Build use cases and augment their SOC or threat hunt programs with more informed choices of AI specific modeling on what is considered anomalous"
},
{
"code": null,
"e": 36863,
"s": 36735,
"text": "Be able to pipeline and automate high quality data into proven tried-and-true models for highly effective alerting and response"
}
] |
Field getType() method in Java with Examples - GeeksforGeeks | 26 Aug, 2019
The getType() method of java.lang.reflect.Field used to get the declared type of the field represented by this Field object.This method returns a Class object that identifies the declared type
Syntax:
public String getType()
Parameters: This method accepts nothing.
Return value: This method returns a Class object that identifies the declared type.
Below programs illustrate getType() method:Program 1:
// Java program to demonstrate getType() method import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws Exception { // Get the marks field object Field field = User.class.getField("Marks"); // Apply getType Method on User Object // to get the Type of Marks field Class value = field.getType(); // print result System.out.println("Type" + " is " + value); // Now Get the Fees field object field = User.class.getField("Fees"); // Apply getType Method on User Object // to get the Type of Fees field value = field.getType(); // print result System.out.println("Type" + " is " + value); }} // sample User classclass User { // static double values public static double Marks = 34.13; public static float Fees = 3413.99f; public static double getMarks() { return Marks; } public static void setMarks(double marks) { Marks = marks; } public static float getFees() { return Fees; } public static void setFees(float fees) { Fees = fees; }}
Type is double
Type is float
Program 2:
// Java program to demonstrate getType() method import java.lang.reflect.Field;import java.time.Month; public class GFG { public static void main(String[] args) throws Exception { // Get all field objects of Month class Field[] fields = Month.class.getFields(); for (int i = 0; i < fields.length; i++) { // print name of Fields System.out.println("Name of Field: " + fields[i].getType()); } }}
Name of Field: class java.time.Month
Name of Field: class java.time.Month
Name of Field: class java.time.Month
Name of Field: class java.time.Month
Name of Field: class java.time.Month
Name of Field: class java.time.Month
Name of Field: class java.time.Month
Name of Field: class java.time.Month
Name of Field: class java.time.Month
Name of Field: class java.time.Month
Name of Field: class java.time.Month
Name of Field: class java.time.Month
References: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#getType–
Java-Field
Java-Functions
java-lang-reflect-package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
LinkedList in Java | [
{
"code": null,
"e": 24085,
"s": 24057,
"text": "\n26 Aug, 2019"
},
{
"code": null,
"e": 24278,
"s": 24085,
"text": "The getType() method of java.lang.reflect.Field used to get the declared type of the field represented by this Field object.This method returns a Class object that identifies the declared type"
},
{
"code": null,
"e": 24286,
"s": 24278,
"text": "Syntax:"
},
{
"code": null,
"e": 24311,
"s": 24286,
"text": "public String getType()\n"
},
{
"code": null,
"e": 24352,
"s": 24311,
"text": "Parameters: This method accepts nothing."
},
{
"code": null,
"e": 24436,
"s": 24352,
"text": "Return value: This method returns a Class object that identifies the declared type."
},
{
"code": null,
"e": 24490,
"s": 24436,
"text": "Below programs illustrate getType() method:Program 1:"
},
{
"code": "// Java program to demonstrate getType() method import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws Exception { // Get the marks field object Field field = User.class.getField(\"Marks\"); // Apply getType Method on User Object // to get the Type of Marks field Class value = field.getType(); // print result System.out.println(\"Type\" + \" is \" + value); // Now Get the Fees field object field = User.class.getField(\"Fees\"); // Apply getType Method on User Object // to get the Type of Fees field value = field.getType(); // print result System.out.println(\"Type\" + \" is \" + value); }} // sample User classclass User { // static double values public static double Marks = 34.13; public static float Fees = 3413.99f; public static double getMarks() { return Marks; } public static void setMarks(double marks) { Marks = marks; } public static float getFees() { return Fees; } public static void setFees(float fees) { Fees = fees; }}",
"e": 25728,
"s": 24490,
"text": null
},
{
"code": null,
"e": 25758,
"s": 25728,
"text": "Type is double\nType is float\n"
},
{
"code": null,
"e": 25769,
"s": 25758,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate getType() method import java.lang.reflect.Field;import java.time.Month; public class GFG { public static void main(String[] args) throws Exception { // Get all field objects of Month class Field[] fields = Month.class.getFields(); for (int i = 0; i < fields.length; i++) { // print name of Fields System.out.println(\"Name of Field: \" + fields[i].getType()); } }}",
"e": 26269,
"s": 25769,
"text": null
},
{
"code": null,
"e": 26714,
"s": 26269,
"text": "Name of Field: class java.time.Month\nName of Field: class java.time.Month\nName of Field: class java.time.Month\nName of Field: class java.time.Month\nName of Field: class java.time.Month\nName of Field: class java.time.Month\nName of Field: class java.time.Month\nName of Field: class java.time.Month\nName of Field: class java.time.Month\nName of Field: class java.time.Month\nName of Field: class java.time.Month\nName of Field: class java.time.Month\n"
},
{
"code": null,
"e": 26806,
"s": 26714,
"text": "References: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#getType–"
},
{
"code": null,
"e": 26817,
"s": 26806,
"text": "Java-Field"
},
{
"code": null,
"e": 26832,
"s": 26817,
"text": "Java-Functions"
},
{
"code": null,
"e": 26858,
"s": 26832,
"text": "java-lang-reflect-package"
},
{
"code": null,
"e": 26863,
"s": 26858,
"text": "Java"
},
{
"code": null,
"e": 26868,
"s": 26863,
"text": "Java"
},
{
"code": null,
"e": 26966,
"s": 26868,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26975,
"s": 26966,
"text": "Comments"
},
{
"code": null,
"e": 26988,
"s": 26975,
"text": "Old Comments"
},
{
"code": null,
"e": 27039,
"s": 26988,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27069,
"s": 27039,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 27100,
"s": 27069,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 27119,
"s": 27100,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27151,
"s": 27119,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27169,
"s": 27151,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27189,
"s": 27169,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 27221,
"s": 27189,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 27245,
"s": 27221,
"text": "Singleton Class in Java"
}
] |
expand Command in LINUX with examples - GeeksforGeeks | 18 Oct, 2021
Whenever you work with files in LINUX there can be a situation when you are stuck with a file that contains a lot of tabs in it and whatever you need to do with file requires that file with no tabs but with spaces. In this situation, the task looks quite simple if you are dealing with a small file but what if the file you are dealing with is very big or you need to do this for a large number of files. For a situation like this, LINUX has a command line utility called expand which allows you to convert tabs into spaces in a file and when no file is specified it reads from standard input.
Thus, expand is useful for pre-processing character files like before sorting that contain tab characters. expand actually writes the produced output to standard output with tab characters expanded to space characters. In this, backspace characters are preserved into the output and also decrement the column count for tab calculations.
Syntax of expand :
//...syntax of expand...//
$expand [OPTION] FILE
The syntax of this is quite simple to understand. It just requires a file name FILE in which you want to expand tab characters into space characters and it reads from standard input if no file name is passed and gives result to standard output.
Example : Suppose you have a file name kt.txt containing tab characters. You can use expand as:
//using expand//
$expand kt.txt
/* expand will produce
the content of the file in
output with only tabs changed
to spaces*/
Note, if there is a need to make this type of change in multiple files then you just have to pass all file names in input and tabs will get converted into spaces.
You can also transfer the output of the changes made into some other file like:
$expand kt.txt > dv.txt
/*now the output will get
transfer to dv.txt as
redirection operator >
is used*/
1. -i, – – initial option : There can be a need to convert tabs that precede lines and leave unchanged those that appear after non-blanks. In simple words this option allows no conversion of tabs after non-blanks.
//using -i option//
$expand -i kt.txt
/*this will not change
those tabs that appear
after blanks*/
2. -t, – – tabs=N option : By default, expand converts tabs into the corresponding number of spaces. But it is possible to tweak the number of spaces using the -t command line option. This option requires you to enter the new number of spaces(N) you want the tabs to get converted.
//using -t option//
$expand -t1 kt.txt > dv.txt
/*this will convert the
tabs in kt.txt to 1 space
instead of default 8
spaces*/
You can also use it as:
$expand --tabs=1 kt.tx > dv.txt
/*this will also convert tabs to
one space each*/
3. -t, – -tabs=LIST option : This uses comma separated LIST of tab positions.
4. – -help : This will display a help message and exit.
5. –version : This will display version information and exit.
The number of options is not much when it comes to expanding command. So, that’s pretty much everything about expand command.
Also see : unexpand command
khushboogoyal499
linux-command
Linux-text-processing-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
nohup Command in Linux with Examples
scp command in Linux with Examples
Thread functions in C/C++
mv command in Linux with examples
chown command in Linux with Examples
SED command in Linux | Set 2
Docker - COPY Instruction
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
nslookup command in Linux with Examples | [
{
"code": null,
"e": 24430,
"s": 24402,
"text": "\n18 Oct, 2021"
},
{
"code": null,
"e": 25025,
"s": 24430,
"text": "Whenever you work with files in LINUX there can be a situation when you are stuck with a file that contains a lot of tabs in it and whatever you need to do with file requires that file with no tabs but with spaces. In this situation, the task looks quite simple if you are dealing with a small file but what if the file you are dealing with is very big or you need to do this for a large number of files. For a situation like this, LINUX has a command line utility called expand which allows you to convert tabs into spaces in a file and when no file is specified it reads from standard input. "
},
{
"code": null,
"e": 25363,
"s": 25025,
"text": "Thus, expand is useful for pre-processing character files like before sorting that contain tab characters. expand actually writes the produced output to standard output with tab characters expanded to space characters. In this, backspace characters are preserved into the output and also decrement the column count for tab calculations. "
},
{
"code": null,
"e": 25384,
"s": 25363,
"text": "Syntax of expand : "
},
{
"code": null,
"e": 25433,
"s": 25384,
"text": "//...syntax of expand...//\n$expand [OPTION] FILE"
},
{
"code": null,
"e": 25679,
"s": 25433,
"text": "The syntax of this is quite simple to understand. It just requires a file name FILE in which you want to expand tab characters into space characters and it reads from standard input if no file name is passed and gives result to standard output. "
},
{
"code": null,
"e": 25776,
"s": 25679,
"text": "Example : Suppose you have a file name kt.txt containing tab characters. You can use expand as: "
},
{
"code": null,
"e": 25906,
"s": 25778,
"text": "//using expand//\n\n$expand kt.txt\n\n/* expand will produce \nthe content of the file in\n output with only tabs changed\nto spaces*/"
},
{
"code": null,
"e": 26070,
"s": 25906,
"text": "Note, if there is a need to make this type of change in multiple files then you just have to pass all file names in input and tabs will get converted into spaces. "
},
{
"code": null,
"e": 26152,
"s": 26070,
"text": "You can also transfer the output of the changes made into some other file like: "
},
{
"code": null,
"e": 26261,
"s": 26152,
"text": "$expand kt.txt > dv.txt \n\n/*now the output will get \ntransfer to dv.txt as \nredirection operator >\nis used*/"
},
{
"code": null,
"e": 26478,
"s": 26263,
"text": "1. -i, – – initial option : There can be a need to convert tabs that precede lines and leave unchanged those that appear after non-blanks. In simple words this option allows no conversion of tabs after non-blanks. "
},
{
"code": null,
"e": 26582,
"s": 26480,
"text": "//using -i option//\n\n$expand -i kt.txt\n\n/*this will not change \nthose tabs that appear\nafter blanks*/"
},
{
"code": null,
"e": 26865,
"s": 26582,
"text": "2. -t, – – tabs=N option : By default, expand converts tabs into the corresponding number of spaces. But it is possible to tweak the number of spaces using the -t command line option. This option requires you to enter the new number of spaces(N) you want the tabs to get converted. "
},
{
"code": null,
"e": 26998,
"s": 26867,
"text": "//using -t option//\n\n$expand -t1 kt.txt > dv.txt\n\n/*this will convert the \ntabs in kt.txt to 1 space\ninstead of default 8\nspaces*/"
},
{
"code": null,
"e": 27023,
"s": 26998,
"text": "You can also use it as: "
},
{
"code": null,
"e": 27109,
"s": 27025,
"text": "$expand --tabs=1 kt.tx > dv.txt\n\n/*this will also convert tabs to \none space each*/"
},
{
"code": null,
"e": 27188,
"s": 27109,
"text": "3. -t, – -tabs=LIST option : This uses comma separated LIST of tab positions. "
},
{
"code": null,
"e": 27245,
"s": 27188,
"text": "4. – -help : This will display a help message and exit. "
},
{
"code": null,
"e": 27308,
"s": 27245,
"text": "5. –version : This will display version information and exit. "
},
{
"code": null,
"e": 27435,
"s": 27308,
"text": "The number of options is not much when it comes to expanding command. So, that’s pretty much everything about expand command. "
},
{
"code": null,
"e": 27464,
"s": 27435,
"text": "Also see : unexpand command "
},
{
"code": null,
"e": 27483,
"s": 27466,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 27497,
"s": 27483,
"text": "linux-command"
},
{
"code": null,
"e": 27528,
"s": 27497,
"text": "Linux-text-processing-commands"
},
{
"code": null,
"e": 27539,
"s": 27528,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27637,
"s": 27539,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27674,
"s": 27637,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 27709,
"s": 27674,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 27735,
"s": 27709,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 27769,
"s": 27735,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 27806,
"s": 27769,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 27835,
"s": 27806,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 27861,
"s": 27835,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 27901,
"s": 27861,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 27936,
"s": 27901,
"text": "Basic Operators in Shell Scripting"
}
] |
How to change text cursor color in Tkinter? | Tkinter Entry and text widgets are used to create single and multiline text input fields. In order to change the color of the cursor, we can specify the insertbackground property by assigning the color of the cursor.
In this example, we have created the text field and we have changed the color of the cursor by defining the insertbackground property.
#Import the tkinter library
from tkinter import *
#Create an instance of tkinter frame
win= Tk()
win.geometry("750x250")
#Create a text field
text= Text(win)
text.configure(bg= 'SteelBlue3',insertbackground='red')
text.pack()
win.mainloop()
Now, write something in the text field to see the reflected color of the cursor. | [
{
"code": null,
"e": 1279,
"s": 1062,
"text": "Tkinter Entry and text widgets are used to create single and multiline text input fields. In order to change the color of the cursor, we can specify the insertbackground property by assigning the color of the cursor."
},
{
"code": null,
"e": 1414,
"s": 1279,
"text": "In this example, we have created the text field and we have changed the color of the cursor by defining the insertbackground property."
},
{
"code": null,
"e": 1655,
"s": 1414,
"text": "#Import the tkinter library\nfrom tkinter import *\n#Create an instance of tkinter frame\nwin= Tk()\nwin.geometry(\"750x250\")\n#Create a text field\ntext= Text(win)\ntext.configure(bg= 'SteelBlue3',insertbackground='red')\ntext.pack()\nwin.mainloop()"
},
{
"code": null,
"e": 1736,
"s": 1655,
"text": "Now, write something in the text field to see the reflected color of the cursor."
}
] |
Add key-value pair in C# Dictionary | To add key-value pair in C# Dictionary, firstly declare a Dictionary.
IDictionary<int, string> d = new Dictionary<int, string>();
Now, add elements with KeyValuePair.
d.Add(new KeyValuePair<int, string>(1, "TVs"));
d.Add(new KeyValuePair<int, string>(2, "Appliances"));
d.Add(new KeyValuePair<int, string>(3, "Mobile"));
After adding elements, let us display the key-value pair.
Live Demo
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
IDictionary<int, string> d = new Dictionary<int, string>();
d.Add(new KeyValuePair<int, string>(1, "TVs"));
d.Add(new KeyValuePair<int, string>(2, "Appliances"));
d.Add(new KeyValuePair<int, string>(3, "Mobile"));
d.Add(new KeyValuePair<int, string>(4, "Tablet"));
d.Add(new KeyValuePair<int, string>(5, "Laptop"));
d.Add(new KeyValuePair<int, string>(6, "Desktop"));
d.Add(new KeyValuePair<int, string>(7, "Hard Drive"));
d.Add(new KeyValuePair<int, string>(8, "Flash Drive"));
foreach (KeyValuePair<int, string> ele in d) {
Console.WriteLine("Key = {0}, Value = {1}", ele.Key, ele.Value);
}
}
}
Key = 1, Value = TVs
Key = 2, Value = Appliances
Key = 3, Value = Mobile
Key = 4, Value = Tablet
Key = 5, Value = Laptop
Key = 6, Value = Desktop
Key = 7, Value = Hard Drive
Key = 8, Value = Flash Drive | [
{
"code": null,
"e": 1132,
"s": 1062,
"text": "To add key-value pair in C# Dictionary, firstly declare a Dictionary."
},
{
"code": null,
"e": 1192,
"s": 1132,
"text": "IDictionary<int, string> d = new Dictionary<int, string>();"
},
{
"code": null,
"e": 1229,
"s": 1192,
"text": "Now, add elements with KeyValuePair."
},
{
"code": null,
"e": 1383,
"s": 1229,
"text": "d.Add(new KeyValuePair<int, string>(1, \"TVs\"));\nd.Add(new KeyValuePair<int, string>(2, \"Appliances\"));\nd.Add(new KeyValuePair<int, string>(3, \"Mobile\"));"
},
{
"code": null,
"e": 1441,
"s": 1383,
"text": "After adding elements, let us display the key-value pair."
},
{
"code": null,
"e": 1452,
"s": 1441,
"text": " Live Demo"
},
{
"code": null,
"e": 2226,
"s": 1452,
"text": "using System;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main() {\n IDictionary<int, string> d = new Dictionary<int, string>();\n d.Add(new KeyValuePair<int, string>(1, \"TVs\"));\n d.Add(new KeyValuePair<int, string>(2, \"Appliances\"));\n d.Add(new KeyValuePair<int, string>(3, \"Mobile\"));\n d.Add(new KeyValuePair<int, string>(4, \"Tablet\"));\n d.Add(new KeyValuePair<int, string>(5, \"Laptop\"));\n d.Add(new KeyValuePair<int, string>(6, \"Desktop\"));\n d.Add(new KeyValuePair<int, string>(7, \"Hard Drive\"));\n d.Add(new KeyValuePair<int, string>(8, \"Flash Drive\"));\n foreach (KeyValuePair<int, string> ele in d) {\n Console.WriteLine(\"Key = {0}, Value = {1}\", ele.Key, ele.Value);\n }\n }\n}"
},
{
"code": null,
"e": 2429,
"s": 2226,
"text": "Key = 1, Value = TVs\nKey = 2, Value = Appliances\nKey = 3, Value = Mobile\nKey = 4, Value = Tablet\nKey = 5, Value = Laptop\nKey = 6, Value = Desktop\nKey = 7, Value = Hard Drive\nKey = 8, Value = Flash Drive"
}
] |
Tools for Sharing Jupyter Notebooks Online | by Rebecca Vickery | Towards Data Science | I recently started helping out on a new data project set up by a friend of mine. The data side of the project is an analysis piece applying some natural language processing to text-based responses from a survey. I created a Github repository for the project and completed the analysis in a Jupyter Notebook.
As part of this project, I want to be able to share the notebooks with non-programmers who won’t necessarily be set up with or familiar with Github. This is a common problem that most data scientists face.
Jupyter Notebooks are a great tool for exploratory data analysis but it is pretty common to need to share this analysis with non-programmer stakeholders in a project. Fortunately, there are a number of tools available to host notebooks online for non-Github users.
In the following article, I am going to walk through how to use three of these tools and discuss the pros and cons of each.
To test each of these tools I have created a Github repository and a sample notebook.
If you don’t already have a Github account you can create one for free. If you are unfamiliar with creating, cloning and pushing to a Github repository I have previously written a guide here.
I have created a Github Repository for testing with the following structure.
The notebooks folder contains a notebook consisting of a machine learning workflow for a Kaggle data set containing tweets labelled disaster or non-disaster. The information about this data set and the data can be found at this link.
A snapshot of the notebook can be viewed below.
Let’s now look at some methods for sharing this notebook with non-programmers.
Jupyter nbviewer is a tool created by the Jupyer community for rendering a notebook hosted on Github online.
It is extremely simple to use. Simply paste the URL to the notebook into this web page.
The notebook is now rendered via a unique link which you can share with others.
Advantages
Extremely simple to use.
Link stays active as long as the notebook remains in the same location in the Github repository.
Disadvantages
Nbviewer only renders the inputs and outputs of the notebook. The code in the link is not executable.
To cut down on rendering time nbviewer caches the output for around 10 minutes. There is, therefore, a delay in viewing any changes you make in the link.
Binder is another open-source project for sharing notebooks. Binder not only renders the inputs and outputs in the notebook but also builds a Docker image of the repository making the hosted notebook interactive.
To share the notebook navigate to this link. Unlike nbviewer you need to add the repository URL, rather than the path to the notebook, in the form as shown below. You can optionally add the path to the notebook but if left blank Binder will make the entire repository available via the link.
Binder will take a couple of minutes to build the docker image.
The notebook is now available online. Recipients of the link can view and interact with the code and outputs.
Advantages
The notebook is made available as executable code and therefore means that the recipient can reproduce and interact with your project.
Simple to use, no need to register for an account or anything.
The docker image is automatically rebuilt when a new commit is made to the repository.
Disadvantages
The Github repository needs to contain a configuration file for the Docker image. Accepted formats include environment.yml, Pipfile, requirements.txt, setup.py. Not really a disadvantage but if you don’t already work with these files this may be added complexity for you.
Jovian is a platform for tracking and collaborating on data science projects. Part of the platform is a tool for hosting Jupyter notebooks online which differs slightly from the other tools mentioned above. Jovian is open-source but also has some enterprise elements to the pricing. The free tier gives you unlimited public projects and access to 5 private projects. This is enough for quickly sharing the occasional notebook.
To upload a notebook you first have to create an account. Once signed up you need to install jovian locally on your machine in your project virtual environment. This can be installed via pip with pip install jovian .
To upload a notebook add import jovian . Once you are ready to share the notebook type the following.
jovian.commit()
This will ask for the API key which can be found on your account on the jovian.ml website.
Once you have entered the key after a few seconds you will get a “Committed Successfully!” message.
If you now go to your profile page you will see your notebook. Jovian.ml captures and uploads the python virtual environment along with the notebook so that collaborators can interact with the code.
If you navigate to the notebook you can add collaborators or use the link to share with others.
Advantages
The sharing options are suitable for both programmers and non-programmers as you have the option to simply view the static inputs and outputs, or to clone and run your own version.
Jovian allows cell level commenting and discussion which is a really nice feature.
Disadvantages
You need to have a Jovian.ml account and need to locally install jovian to share your notebooks, and therefore this tool requires a little more set up compared to the other two options.
The notebook needs to be uploaded separately to Jovian.ml so if you are using Github for version control you need to make two commits and your project will potentially be in two separate places.
This article has given an overview of three tools available to share Jupyter Notebooks online. Each tool is very useful in its own right and I would definitely use all three. However, for my purpose that I set out at the beginning of the article, which is to share the notebook with non-programmers, nbviewer is definitely the option I will choose. It is the simplest option and provides me with exactly what I need which is a view-only form of sharing.
Thanks for reading!
I send out a monthly newsletter if you would like to join please sign up via this link. Looking forward to being part of your learning journey! | [
{
"code": null,
"e": 480,
"s": 172,
"text": "I recently started helping out on a new data project set up by a friend of mine. The data side of the project is an analysis piece applying some natural language processing to text-based responses from a survey. I created a Github repository for the project and completed the analysis in a Jupyter Notebook."
},
{
"code": null,
"e": 686,
"s": 480,
"text": "As part of this project, I want to be able to share the notebooks with non-programmers who won’t necessarily be set up with or familiar with Github. This is a common problem that most data scientists face."
},
{
"code": null,
"e": 951,
"s": 686,
"text": "Jupyter Notebooks are a great tool for exploratory data analysis but it is pretty common to need to share this analysis with non-programmer stakeholders in a project. Fortunately, there are a number of tools available to host notebooks online for non-Github users."
},
{
"code": null,
"e": 1075,
"s": 951,
"text": "In the following article, I am going to walk through how to use three of these tools and discuss the pros and cons of each."
},
{
"code": null,
"e": 1161,
"s": 1075,
"text": "To test each of these tools I have created a Github repository and a sample notebook."
},
{
"code": null,
"e": 1353,
"s": 1161,
"text": "If you don’t already have a Github account you can create one for free. If you are unfamiliar with creating, cloning and pushing to a Github repository I have previously written a guide here."
},
{
"code": null,
"e": 1430,
"s": 1353,
"text": "I have created a Github Repository for testing with the following structure."
},
{
"code": null,
"e": 1664,
"s": 1430,
"text": "The notebooks folder contains a notebook consisting of a machine learning workflow for a Kaggle data set containing tweets labelled disaster or non-disaster. The information about this data set and the data can be found at this link."
},
{
"code": null,
"e": 1712,
"s": 1664,
"text": "A snapshot of the notebook can be viewed below."
},
{
"code": null,
"e": 1791,
"s": 1712,
"text": "Let’s now look at some methods for sharing this notebook with non-programmers."
},
{
"code": null,
"e": 1900,
"s": 1791,
"text": "Jupyter nbviewer is a tool created by the Jupyer community for rendering a notebook hosted on Github online."
},
{
"code": null,
"e": 1988,
"s": 1900,
"text": "It is extremely simple to use. Simply paste the URL to the notebook into this web page."
},
{
"code": null,
"e": 2068,
"s": 1988,
"text": "The notebook is now rendered via a unique link which you can share with others."
},
{
"code": null,
"e": 2079,
"s": 2068,
"text": "Advantages"
},
{
"code": null,
"e": 2104,
"s": 2079,
"text": "Extremely simple to use."
},
{
"code": null,
"e": 2201,
"s": 2104,
"text": "Link stays active as long as the notebook remains in the same location in the Github repository."
},
{
"code": null,
"e": 2215,
"s": 2201,
"text": "Disadvantages"
},
{
"code": null,
"e": 2317,
"s": 2215,
"text": "Nbviewer only renders the inputs and outputs of the notebook. The code in the link is not executable."
},
{
"code": null,
"e": 2471,
"s": 2317,
"text": "To cut down on rendering time nbviewer caches the output for around 10 minutes. There is, therefore, a delay in viewing any changes you make in the link."
},
{
"code": null,
"e": 2684,
"s": 2471,
"text": "Binder is another open-source project for sharing notebooks. Binder not only renders the inputs and outputs in the notebook but also builds a Docker image of the repository making the hosted notebook interactive."
},
{
"code": null,
"e": 2976,
"s": 2684,
"text": "To share the notebook navigate to this link. Unlike nbviewer you need to add the repository URL, rather than the path to the notebook, in the form as shown below. You can optionally add the path to the notebook but if left blank Binder will make the entire repository available via the link."
},
{
"code": null,
"e": 3040,
"s": 2976,
"text": "Binder will take a couple of minutes to build the docker image."
},
{
"code": null,
"e": 3150,
"s": 3040,
"text": "The notebook is now available online. Recipients of the link can view and interact with the code and outputs."
},
{
"code": null,
"e": 3161,
"s": 3150,
"text": "Advantages"
},
{
"code": null,
"e": 3296,
"s": 3161,
"text": "The notebook is made available as executable code and therefore means that the recipient can reproduce and interact with your project."
},
{
"code": null,
"e": 3359,
"s": 3296,
"text": "Simple to use, no need to register for an account or anything."
},
{
"code": null,
"e": 3446,
"s": 3359,
"text": "The docker image is automatically rebuilt when a new commit is made to the repository."
},
{
"code": null,
"e": 3460,
"s": 3446,
"text": "Disadvantages"
},
{
"code": null,
"e": 3732,
"s": 3460,
"text": "The Github repository needs to contain a configuration file for the Docker image. Accepted formats include environment.yml, Pipfile, requirements.txt, setup.py. Not really a disadvantage but if you don’t already work with these files this may be added complexity for you."
},
{
"code": null,
"e": 4159,
"s": 3732,
"text": "Jovian is a platform for tracking and collaborating on data science projects. Part of the platform is a tool for hosting Jupyter notebooks online which differs slightly from the other tools mentioned above. Jovian is open-source but also has some enterprise elements to the pricing. The free tier gives you unlimited public projects and access to 5 private projects. This is enough for quickly sharing the occasional notebook."
},
{
"code": null,
"e": 4376,
"s": 4159,
"text": "To upload a notebook you first have to create an account. Once signed up you need to install jovian locally on your machine in your project virtual environment. This can be installed via pip with pip install jovian ."
},
{
"code": null,
"e": 4478,
"s": 4376,
"text": "To upload a notebook add import jovian . Once you are ready to share the notebook type the following."
},
{
"code": null,
"e": 4494,
"s": 4478,
"text": "jovian.commit()"
},
{
"code": null,
"e": 4585,
"s": 4494,
"text": "This will ask for the API key which can be found on your account on the jovian.ml website."
},
{
"code": null,
"e": 4685,
"s": 4585,
"text": "Once you have entered the key after a few seconds you will get a “Committed Successfully!” message."
},
{
"code": null,
"e": 4884,
"s": 4685,
"text": "If you now go to your profile page you will see your notebook. Jovian.ml captures and uploads the python virtual environment along with the notebook so that collaborators can interact with the code."
},
{
"code": null,
"e": 4980,
"s": 4884,
"text": "If you navigate to the notebook you can add collaborators or use the link to share with others."
},
{
"code": null,
"e": 4991,
"s": 4980,
"text": "Advantages"
},
{
"code": null,
"e": 5172,
"s": 4991,
"text": "The sharing options are suitable for both programmers and non-programmers as you have the option to simply view the static inputs and outputs, or to clone and run your own version."
},
{
"code": null,
"e": 5255,
"s": 5172,
"text": "Jovian allows cell level commenting and discussion which is a really nice feature."
},
{
"code": null,
"e": 5269,
"s": 5255,
"text": "Disadvantages"
},
{
"code": null,
"e": 5455,
"s": 5269,
"text": "You need to have a Jovian.ml account and need to locally install jovian to share your notebooks, and therefore this tool requires a little more set up compared to the other two options."
},
{
"code": null,
"e": 5650,
"s": 5455,
"text": "The notebook needs to be uploaded separately to Jovian.ml so if you are using Github for version control you need to make two commits and your project will potentially be in two separate places."
},
{
"code": null,
"e": 6104,
"s": 5650,
"text": "This article has given an overview of three tools available to share Jupyter Notebooks online. Each tool is very useful in its own right and I would definitely use all three. However, for my purpose that I set out at the beginning of the article, which is to share the notebook with non-programmers, nbviewer is definitely the option I will choose. It is the simplest option and provides me with exactly what I need which is a view-only form of sharing."
},
{
"code": null,
"e": 6124,
"s": 6104,
"text": "Thanks for reading!"
}
] |
C# SortedList with Examples - GeeksforGeeks | 13 Jul, 2021
In C#, SortedList is a collection of key/value pairs which are sorted according to keys. By default, this collection sort the key/value pairs in ascending order. It is of both generic and non-generic type of collection. The generic SortedList is defined in System.Collections.Generic namespace whereas non-generic SortedList is defined under System.Collections namespace, here we will discuss non-generic type SortedList. Important Points:
The SortedList class implements the IEnumerable, ICollection, IDictionary and ICloneable interfaces.
In SortedList, an element can be accessed by its key or by its index.
A SortedList object internally maintains two arrays to store the elements of the list, i.e, one array for the keys and another array for the associated values.
Here, a key cannot be null, but a value can be.
The capacity of a SortedList object is the number of key/value pairs it can hold.
In SortedList, duplicate keys are not allowed.
In SortedList, you can store values of the same type and of the different types due to the non-generic collection. If you use a generic SortedList in your program, then it is necessary that the type of the values should be the same.
In SortedList you cannot store keys of different data types in the same SortedList because the compiler will throw an exception. So, always add the key in your SortedList of the same type.
You can also cast key/value pair of SortedList into DictionaryEntry.
The SortedList class provides 6 different types of constructors which are used to create a SortedList, here we only use SortedList(), constructor. To read more about SortedList’s constructors you can refer to C# | SortedList Class.SortedList(): It is used to create an instance of the SortedList class that is empty, has the default initial capacity, and is sorted according to the IComparable interface implemented by each key added to the SortedList object. Step 1: Include System.Collections namespace in your program with the help of using keyword:
using System.Collections;
Step 2: Create a SortedList using SortedList class as shown below:
SortedList list_name = new SortedList();
Step 3: If you want to add a key/value pair in your SortedList, then use Add() method to add key/value pairs in your SortedList. And you can also store a key/value pair in your SortedList without using the Add() method, this type of syntax is known as Collection Initializer Syntax as shown in the below example.Step 4: The key/value pairs of the SortedList is accessed using three different ways:
for loop: You can use for loop to access the key/value pairs of the SortedList.Example:
CSharp
for (int x = 0; x < my_slist1.Count; x++){ Console.WriteLine("{0} and {1}", my_slist1.GetKey(x), my_slist1.GetByIndex(x));}
Using Index: You can access the individual value of the SortedList by using the index. You need to pass the key or index as a parameter to find the respective value. If the specified key is not available, then the compiler will throw an error.Example:
CSharp
Console.WriteLine("Value is:{0}", my_slist1[1.04]); string x = (string)my_slist[1.02]; Console.WriteLine(x);
foreach loop: You can use a foreach loop to access the key/value pairs of the SortedList.Example:
CSharp
foreach(DictionaryEntry pair in my_slist1){ Console.WriteLine("{0} and {1}", pair.Key, pair.Value);}
Example:
CSharp
// C# program to illustrate how// to create a sortedlistusing System;using System.Collections; class GFG { // Main Method static public void Main() { // Creating a sortedlist // Using SortedList class SortedList my_slist1 = new SortedList(); // Adding key/value pairs in // SortedList using Add() method my_slist1.Add(1.02, "This"); my_slist1.Add(1.07, "Is"); my_slist1.Add(1.04, "SortedList"); my_slist1.Add(1.01, "Tutorial"); foreach(DictionaryEntry pair in my_slist1) { Console.WriteLine("{0} and {1}", pair.Key, pair.Value); } Console.WriteLine(); // Creating another SortedList // using Object Initializer Syntax // to initialize sortedlist SortedList my_slist2 = new SortedList() { { "b.09", 234 }, { "b.11", 395 }, { "b.01", 405 }, { "b.67", 100 }}; foreach(DictionaryEntry pair in my_slist2) { Console.WriteLine("{0} and {1}", pair.Key, pair.Value); } }}
1.01 and Tutorial
1.02 and This
1.04 and SortedList
1.07 and Is
b.01 and 405
b.09 and 234
b.11 and 395
b.67 and 100
Clear: This method is used to removes all elements from a SortedList object.
Remove: This method is used to removes the element with the specified key from a SortedList object.
RemoveAt: This method is used to removes the element at the specified index of a SortedList object.
Example:
CSharp
// C# program to illustrate how to// remove key/value pairs from// the sortedlistusing System;using System.Collections; class GFG { // Main Method static public void Main() { // Creating a sortedlist // Using SortedList class SortedList my_slist = new SortedList(); // Adding key/value pairs in SortedList // Using Add() method my_slist.Add(1.02, "This"); my_slist.Add(1.07, "Is"); my_slist.Add(1.04, "SortedList"); my_slist.Add(1.01, "Tutorial"); foreach(DictionaryEntry pair in my_slist) { Console.WriteLine("{0} and {1}", pair.Key, pair.Value); } Console.WriteLine(); // Remove value having 1.07 key // Using Remove() method my_slist.Remove(1.07); // After Remove() method foreach(DictionaryEntry pair in my_slist) { Console.WriteLine("{0} and {1}", pair.Key, pair.Value); } Console.WriteLine(); // Remove element at index 2 // Using RemoveAt() method my_slist.RemoveAt(2); // After RemoveAt() method foreach(DictionaryEntry pair in my_slist) { Console.WriteLine("{0} and {1}", pair.Key, pair.Value); } Console.WriteLine(); // Remove all key/value pairs // Using Clear method my_slist.Clear(); Console.WriteLine("The total number of key/value pairs"+ " present in my_slist:{0}", my_slist.Count); }}
1.01 and Tutorial
1.02 and This
1.04 and SortedList
1.07 and Is
1.01 and Tutorial
1.02 and This
1.04 and SortedList
1.01 and Tutorial
1.02 and This
The total number of key/value pairs present in my_slist:0
In SortedList, you can check whether the given pair is present or not using the following methods:
Contains: This method is used to check whether a SortedList object contains a specific key.
ContainsKey: This method is used to check whether a SortedList object contains a specific key.
ContainsValue: This method is used to check whether a SortedList object contains a specific value.
Example:
CSharp
// C# program to illustrate how to// check the given key or value// present in the sortedlist or notusing System;using System.Collections; class GFG { // Main Method static public void Main() { // Creating a sortedlist // Using SortedList class SortedList my_slist = new SortedList(); // Adding key/value pairs in // SortedList using Add() method my_slist.Add(1.02, "This"); my_slist.Add(1.07, "Is"); my_slist.Add(1.04, "SortedList"); my_slist.Add(1.01, "Tutorial"); // Using Contains() method to check // the specified key is present or not if (my_slist.Contains(1.02) == true) { Console.WriteLine("Key is found...!!"); } else { Console.WriteLine("Key is not found...!!"); } // Using ContainsKey() method to check // the specified key is present or not if (my_slist.ContainsKey(1.03) == true) { Console.WriteLine("Key is found...!!"); } else { Console.WriteLine("Key is not found...!!"); } // Using ContainsValue() method to check // the specified value is present or not if (my_slist.ContainsValue("Is") == true) { Console.WriteLine("Value is found...!!"); } else { Console.WriteLine("Value is not found...!!"); } }}
Key is found...!!
Key is not found...!!
Value is found...!!
anikakapoor
CSharp-Collections-Namespace
CSharp-Collections-SortedList
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Abstract Class and Interface in C#
C# | How to check whether a List contains a specified element
C# | IsNullOrEmpty() Method
String.Split() Method in C# with Examples
C# | Arrays of Strings
Destructors in C#
Difference between Ref and Out keywords in C#
C# | Delegates
Extension Method in C#
C# | String.IndexOf( ) Method | Set - 1 | [
{
"code": null,
"e": 25280,
"s": 25252,
"text": "\n13 Jul, 2021"
},
{
"code": null,
"e": 25722,
"s": 25280,
"text": "In C#, SortedList is a collection of key/value pairs which are sorted according to keys. By default, this collection sort the key/value pairs in ascending order. It is of both generic and non-generic type of collection. The generic SortedList is defined in System.Collections.Generic namespace whereas non-generic SortedList is defined under System.Collections namespace, here we will discuss non-generic type SortedList. Important Points: "
},
{
"code": null,
"e": 25823,
"s": 25722,
"text": "The SortedList class implements the IEnumerable, ICollection, IDictionary and ICloneable interfaces."
},
{
"code": null,
"e": 25893,
"s": 25823,
"text": "In SortedList, an element can be accessed by its key or by its index."
},
{
"code": null,
"e": 26053,
"s": 25893,
"text": "A SortedList object internally maintains two arrays to store the elements of the list, i.e, one array for the keys and another array for the associated values."
},
{
"code": null,
"e": 26101,
"s": 26053,
"text": "Here, a key cannot be null, but a value can be."
},
{
"code": null,
"e": 26183,
"s": 26101,
"text": "The capacity of a SortedList object is the number of key/value pairs it can hold."
},
{
"code": null,
"e": 26230,
"s": 26183,
"text": "In SortedList, duplicate keys are not allowed."
},
{
"code": null,
"e": 26463,
"s": 26230,
"text": "In SortedList, you can store values of the same type and of the different types due to the non-generic collection. If you use a generic SortedList in your program, then it is necessary that the type of the values should be the same."
},
{
"code": null,
"e": 26652,
"s": 26463,
"text": "In SortedList you cannot store keys of different data types in the same SortedList because the compiler will throw an exception. So, always add the key in your SortedList of the same type."
},
{
"code": null,
"e": 26721,
"s": 26652,
"text": "You can also cast key/value pair of SortedList into DictionaryEntry."
},
{
"code": null,
"e": 27277,
"s": 26723,
"text": "The SortedList class provides 6 different types of constructors which are used to create a SortedList, here we only use SortedList(), constructor. To read more about SortedList’s constructors you can refer to C# | SortedList Class.SortedList(): It is used to create an instance of the SortedList class that is empty, has the default initial capacity, and is sorted according to the IComparable interface implemented by each key added to the SortedList object. Step 1: Include System.Collections namespace in your program with the help of using keyword: "
},
{
"code": null,
"e": 27303,
"s": 27277,
"text": "using System.Collections;"
},
{
"code": null,
"e": 27371,
"s": 27303,
"text": "Step 2: Create a SortedList using SortedList class as shown below: "
},
{
"code": null,
"e": 27412,
"s": 27371,
"text": "SortedList list_name = new SortedList();"
},
{
"code": null,
"e": 27811,
"s": 27412,
"text": "Step 3: If you want to add a key/value pair in your SortedList, then use Add() method to add key/value pairs in your SortedList. And you can also store a key/value pair in your SortedList without using the Add() method, this type of syntax is known as Collection Initializer Syntax as shown in the below example.Step 4: The key/value pairs of the SortedList is accessed using three different ways: "
},
{
"code": null,
"e": 27900,
"s": 27811,
"text": "for loop: You can use for loop to access the key/value pairs of the SortedList.Example: "
},
{
"code": null,
"e": 27907,
"s": 27900,
"text": "CSharp"
},
{
"code": "for (int x = 0; x < my_slist1.Count; x++){ Console.WriteLine(\"{0} and {1}\", my_slist1.GetKey(x), my_slist1.GetByIndex(x));}",
"e": 28059,
"s": 27907,
"text": null
},
{
"code": null,
"e": 28312,
"s": 28059,
"text": "Using Index: You can access the individual value of the SortedList by using the index. You need to pass the key or index as a parameter to find the respective value. If the specified key is not available, then the compiler will throw an error.Example: "
},
{
"code": null,
"e": 28319,
"s": 28312,
"text": "CSharp"
},
{
"code": "Console.WriteLine(\"Value is:{0}\", my_slist1[1.04]); string x = (string)my_slist[1.02]; Console.WriteLine(x);",
"e": 28428,
"s": 28319,
"text": null
},
{
"code": null,
"e": 28527,
"s": 28428,
"text": "foreach loop: You can use a foreach loop to access the key/value pairs of the SortedList.Example: "
},
{
"code": null,
"e": 28534,
"s": 28527,
"text": "CSharp"
},
{
"code": "foreach(DictionaryEntry pair in my_slist1){ Console.WriteLine(\"{0} and {1}\", pair.Key, pair.Value);}",
"e": 28651,
"s": 28534,
"text": null
},
{
"code": null,
"e": 28661,
"s": 28651,
"text": "Example: "
},
{
"code": null,
"e": 28668,
"s": 28661,
"text": "CSharp"
},
{
"code": "// C# program to illustrate how// to create a sortedlistusing System;using System.Collections; class GFG { // Main Method static public void Main() { // Creating a sortedlist // Using SortedList class SortedList my_slist1 = new SortedList(); // Adding key/value pairs in // SortedList using Add() method my_slist1.Add(1.02, \"This\"); my_slist1.Add(1.07, \"Is\"); my_slist1.Add(1.04, \"SortedList\"); my_slist1.Add(1.01, \"Tutorial\"); foreach(DictionaryEntry pair in my_slist1) { Console.WriteLine(\"{0} and {1}\", pair.Key, pair.Value); } Console.WriteLine(); // Creating another SortedList // using Object Initializer Syntax // to initialize sortedlist SortedList my_slist2 = new SortedList() { { \"b.09\", 234 }, { \"b.11\", 395 }, { \"b.01\", 405 }, { \"b.67\", 100 }}; foreach(DictionaryEntry pair in my_slist2) { Console.WriteLine(\"{0} and {1}\", pair.Key, pair.Value); } }}",
"e": 29901,
"s": 28668,
"text": null
},
{
"code": null,
"e": 30018,
"s": 29901,
"text": "1.01 and Tutorial\n1.02 and This\n1.04 and SortedList\n1.07 and Is\n\nb.01 and 405\nb.09 and 234\nb.11 and 395\nb.67 and 100"
},
{
"code": null,
"e": 30097,
"s": 30020,
"text": "Clear: This method is used to removes all elements from a SortedList object."
},
{
"code": null,
"e": 30197,
"s": 30097,
"text": "Remove: This method is used to removes the element with the specified key from a SortedList object."
},
{
"code": null,
"e": 30297,
"s": 30197,
"text": "RemoveAt: This method is used to removes the element at the specified index of a SortedList object."
},
{
"code": null,
"e": 30307,
"s": 30297,
"text": "Example: "
},
{
"code": null,
"e": 30314,
"s": 30307,
"text": "CSharp"
},
{
"code": "// C# program to illustrate how to// remove key/value pairs from// the sortedlistusing System;using System.Collections; class GFG { // Main Method static public void Main() { // Creating a sortedlist // Using SortedList class SortedList my_slist = new SortedList(); // Adding key/value pairs in SortedList // Using Add() method my_slist.Add(1.02, \"This\"); my_slist.Add(1.07, \"Is\"); my_slist.Add(1.04, \"SortedList\"); my_slist.Add(1.01, \"Tutorial\"); foreach(DictionaryEntry pair in my_slist) { Console.WriteLine(\"{0} and {1}\", pair.Key, pair.Value); } Console.WriteLine(); // Remove value having 1.07 key // Using Remove() method my_slist.Remove(1.07); // After Remove() method foreach(DictionaryEntry pair in my_slist) { Console.WriteLine(\"{0} and {1}\", pair.Key, pair.Value); } Console.WriteLine(); // Remove element at index 2 // Using RemoveAt() method my_slist.RemoveAt(2); // After RemoveAt() method foreach(DictionaryEntry pair in my_slist) { Console.WriteLine(\"{0} and {1}\", pair.Key, pair.Value); } Console.WriteLine(); // Remove all key/value pairs // Using Clear method my_slist.Clear(); Console.WriteLine(\"The total number of key/value pairs\"+ \" present in my_slist:{0}\", my_slist.Count); }}",
"e": 31883,
"s": 30314,
"text": null
},
{
"code": null,
"e": 32092,
"s": 31883,
"text": "1.01 and Tutorial\n1.02 and This\n1.04 and SortedList\n1.07 and Is\n\n1.01 and Tutorial\n1.02 and This\n1.04 and SortedList\n\n1.01 and Tutorial\n1.02 and This\n\nThe total number of key/value pairs present in my_slist:0"
},
{
"code": null,
"e": 32194,
"s": 32094,
"text": "In SortedList, you can check whether the given pair is present or not using the following methods: "
},
{
"code": null,
"e": 32286,
"s": 32194,
"text": "Contains: This method is used to check whether a SortedList object contains a specific key."
},
{
"code": null,
"e": 32381,
"s": 32286,
"text": "ContainsKey: This method is used to check whether a SortedList object contains a specific key."
},
{
"code": null,
"e": 32480,
"s": 32381,
"text": "ContainsValue: This method is used to check whether a SortedList object contains a specific value."
},
{
"code": null,
"e": 32490,
"s": 32480,
"text": "Example: "
},
{
"code": null,
"e": 32497,
"s": 32490,
"text": "CSharp"
},
{
"code": "// C# program to illustrate how to// check the given key or value// present in the sortedlist or notusing System;using System.Collections; class GFG { // Main Method static public void Main() { // Creating a sortedlist // Using SortedList class SortedList my_slist = new SortedList(); // Adding key/value pairs in // SortedList using Add() method my_slist.Add(1.02, \"This\"); my_slist.Add(1.07, \"Is\"); my_slist.Add(1.04, \"SortedList\"); my_slist.Add(1.01, \"Tutorial\"); // Using Contains() method to check // the specified key is present or not if (my_slist.Contains(1.02) == true) { Console.WriteLine(\"Key is found...!!\"); } else { Console.WriteLine(\"Key is not found...!!\"); } // Using ContainsKey() method to check // the specified key is present or not if (my_slist.ContainsKey(1.03) == true) { Console.WriteLine(\"Key is found...!!\"); } else { Console.WriteLine(\"Key is not found...!!\"); } // Using ContainsValue() method to check // the specified value is present or not if (my_slist.ContainsValue(\"Is\") == true) { Console.WriteLine(\"Value is found...!!\"); } else { Console.WriteLine(\"Value is not found...!!\"); } }}",
"e": 33933,
"s": 32497,
"text": null
},
{
"code": null,
"e": 33993,
"s": 33933,
"text": "Key is found...!!\nKey is not found...!!\nValue is found...!!"
},
{
"code": null,
"e": 34007,
"s": 33995,
"text": "anikakapoor"
},
{
"code": null,
"e": 34036,
"s": 34007,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 34066,
"s": 34036,
"text": "CSharp-Collections-SortedList"
},
{
"code": null,
"e": 34069,
"s": 34066,
"text": "C#"
},
{
"code": null,
"e": 34167,
"s": 34069,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34221,
"s": 34167,
"text": "Difference between Abstract Class and Interface in C#"
},
{
"code": null,
"e": 34283,
"s": 34221,
"text": "C# | How to check whether a List contains a specified element"
},
{
"code": null,
"e": 34311,
"s": 34283,
"text": "C# | IsNullOrEmpty() Method"
},
{
"code": null,
"e": 34353,
"s": 34311,
"text": "String.Split() Method in C# with Examples"
},
{
"code": null,
"e": 34376,
"s": 34353,
"text": "C# | Arrays of Strings"
},
{
"code": null,
"e": 34394,
"s": 34376,
"text": "Destructors in C#"
},
{
"code": null,
"e": 34440,
"s": 34394,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 34455,
"s": 34440,
"text": "C# | Delegates"
},
{
"code": null,
"e": 34478,
"s": 34455,
"text": "Extension Method in C#"
}
] |
Mean of array using recursion - GeeksforGeeks | 29 Jul, 2021
To find the mean of the elements of the array.
Mean = (Sum of elements of the Array) /
(Total no of elements in Array)
Examples:
Input : 1 2 3 4 5
Output : 3
Input : 1 2 3
Output : 2
To find the mean using recursion assume that the problem is already solved for N-1 ie you have to find for n
Sum of first N-1 elements =
(Mean of N-1 elements)*(N-1)
Mean of N elements = (Sum of first N-1 elements +
N-th elements) / (N)
Note : Since array indexing starts from 0, we access N-th element using A[N-1].
C++
C
Java
Python3
C#
PHP
Javascript
// Recursive C++ program to find mean of array#include <iostream>using namespace std; // Function Definition of findMean functionfloat findMean(int A[], int N){ if (N == 1) return (float)A[N-1]; else return ((float)(findMean(A, N-1)*(N-1) + A[N-1]) / N);} // Main Calling Functionint main(){ float Mean = 0; int A[] = {1, 2, 3, 4, 5}; int N = sizeof(A)/sizeof(A[0]); cout << " "<< findMean(A, N); return 0;} // this code is contributed by shivanisinghss2110
// Recursive C program to find mean of array#include<stdio.h> // Function Definition of findMean functionfloat findMean(int A[], int N){ if (N == 1) return (float)A[N-1]; else return ((float)(findMean(A, N-1)*(N-1) + A[N-1]) / N);} // Main Calling Functionint main(){ float Mean = 0; int A[] = {1, 2, 3, 4, 5}; int N = sizeof(A)/sizeof(A[0]); printf("%.2f\n", findMean(A, N)); return 0;}
// Recursive Java program to find mean of arrayclass CalcMean{ // Function Definition of findMean function static float findMean(int A[], int N) { if (N == 1) return (float)A[N-1]; else return ((float)(findMean(A, N-1)*(N-1) + A[N-1]) / N); } // main Function public static void main (String[] args) { float Mean = 0; int A[] = {1, 2, 3, 4, 5}; int N = A.length; System.out.println(findMean(A, N)); }}
# Recursive Python3 program to# find mean of array # Function Definition of findMean functiondef findMean(A, N): if (N == 1): return A[N - 1] else: return ((findMean(A, N - 1) * (N - 1) + A[N - 1]) / N) # Driver CodeMean = 0A = [1, 2, 3, 4, 5]N = len(A)print(findMean(A, N)) # This code is contributed by Anant Agarwal.
// Recursive C# program to find mean of arrayusing System; class CalcMean{ // Function Definition of findMean function static float findMean(int []A, int N) { if (N == 1) return (float)A[N - 1]; else return ((float)(findMean(A, N - 1) * (N - 1) + A[N - 1]) / N); } // Driver code public static void Main() { //float Mean = 0; int []A = {1, 2, 3, 4, 5}; int N = A.Length; Console.WriteLine(findMean(A, N)); }} // This code is contributed by Anant Agarwal.
<?php// Recursive PHP program to find mean of array // Function Definition of findMean functionfunction findMean($A, $N){ if ($N == 1) return $A[$N - 1]; else return ((findMean($A, $N - 1) * ($N - 1) + $A[$N - 1]) / $N);} // Driver Code$Mean = 0;$A = array(1, 2, 3, 4, 5);$N = sizeof($A);echo findMean($A, $N); // This code is contributed by ajit.?>
<script> // Recursive Javascript program to find mean of array // Function Definition of findMean function function findMean(A, N) { if (N == 1) return A[N - 1]; else return ((findMean(A, N - 1) * (N - 1) + A[N - 1]) / N); } // float Mean = 0; let A = [1, 2, 3, 4, 5]; let N = A.length; document.write(findMean(A, N)); // This code is contributed by rameshtravel07.</script>
Output:
3
This article is contributed by Prakhar Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
jit_t
rameshtravel07
surindertarika1234
shivanisinghss2110
Arrays
School Programming
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Multidimensional Arrays in Java
Queue | Set 1 (Introduction and Array Implementation)
Linear Search
Python | Using 2D arrays/lists the right way
Python Dictionary
Inheritance in C++
Reverse a string in Java
Overriding in Java
Copy Constructor in C++ | [
{
"code": null,
"e": 24493,
"s": 24465,
"text": "\n29 Jul, 2021"
},
{
"code": null,
"e": 24542,
"s": 24493,
"text": "To find the mean of the elements of the array. "
},
{
"code": null,
"e": 24621,
"s": 24542,
"text": "Mean = (Sum of elements of the Array) /\n (Total no of elements in Array)"
},
{
"code": null,
"e": 24633,
"s": 24621,
"text": "Examples: "
},
{
"code": null,
"e": 24688,
"s": 24633,
"text": "Input : 1 2 3 4 5\nOutput : 3\n\nInput : 1 2 3\nOutput : 2"
},
{
"code": null,
"e": 24800,
"s": 24690,
"text": "To find the mean using recursion assume that the problem is already solved for N-1 ie you have to find for n "
},
{
"code": null,
"e": 24970,
"s": 24800,
"text": "Sum of first N-1 elements = \n (Mean of N-1 elements)*(N-1)\n\nMean of N elements = (Sum of first N-1 elements + \n N-th elements) / (N)"
},
{
"code": null,
"e": 25051,
"s": 24970,
"text": "Note : Since array indexing starts from 0, we access N-th element using A[N-1]. "
},
{
"code": null,
"e": 25057,
"s": 25053,
"text": "C++"
},
{
"code": null,
"e": 25059,
"s": 25057,
"text": "C"
},
{
"code": null,
"e": 25064,
"s": 25059,
"text": "Java"
},
{
"code": null,
"e": 25072,
"s": 25064,
"text": "Python3"
},
{
"code": null,
"e": 25075,
"s": 25072,
"text": "C#"
},
{
"code": null,
"e": 25079,
"s": 25075,
"text": "PHP"
},
{
"code": null,
"e": 25090,
"s": 25079,
"text": "Javascript"
},
{
"code": "// Recursive C++ program to find mean of array#include <iostream>using namespace std; // Function Definition of findMean functionfloat findMean(int A[], int N){ if (N == 1) return (float)A[N-1]; else return ((float)(findMean(A, N-1)*(N-1) + A[N-1]) / N);} // Main Calling Functionint main(){ float Mean = 0; int A[] = {1, 2, 3, 4, 5}; int N = sizeof(A)/sizeof(A[0]); cout << \" \"<< findMean(A, N); return 0;} // this code is contributed by shivanisinghss2110",
"e": 25618,
"s": 25090,
"text": null
},
{
"code": "// Recursive C program to find mean of array#include<stdio.h> // Function Definition of findMean functionfloat findMean(int A[], int N){ if (N == 1) return (float)A[N-1]; else return ((float)(findMean(A, N-1)*(N-1) + A[N-1]) / N);} // Main Calling Functionint main(){ float Mean = 0; int A[] = {1, 2, 3, 4, 5}; int N = sizeof(A)/sizeof(A[0]); printf(\"%.2f\\n\", findMean(A, N)); return 0;}",
"e": 26076,
"s": 25618,
"text": null
},
{
"code": "// Recursive Java program to find mean of arrayclass CalcMean{ // Function Definition of findMean function static float findMean(int A[], int N) { if (N == 1) return (float)A[N-1]; else return ((float)(findMean(A, N-1)*(N-1) + A[N-1]) / N); } // main Function public static void main (String[] args) { float Mean = 0; int A[] = {1, 2, 3, 4, 5}; int N = A.length; System.out.println(findMean(A, N)); }}",
"e": 26610,
"s": 26076,
"text": null
},
{
"code": "# Recursive Python3 program to# find mean of array # Function Definition of findMean functiondef findMean(A, N): if (N == 1): return A[N - 1] else: return ((findMean(A, N - 1) * (N - 1) + A[N - 1]) / N) # Driver CodeMean = 0A = [1, 2, 3, 4, 5]N = len(A)print(findMean(A, N)) # This code is contributed by Anant Agarwal.",
"e": 26966,
"s": 26610,
"text": null
},
{
"code": "// Recursive C# program to find mean of arrayusing System; class CalcMean{ // Function Definition of findMean function static float findMean(int []A, int N) { if (N == 1) return (float)A[N - 1]; else return ((float)(findMean(A, N - 1) * (N - 1) + A[N - 1]) / N); } // Driver code public static void Main() { //float Mean = 0; int []A = {1, 2, 3, 4, 5}; int N = A.Length; Console.WriteLine(findMean(A, N)); }} // This code is contributed by Anant Agarwal.",
"e": 27541,
"s": 26966,
"text": null
},
{
"code": "<?php// Recursive PHP program to find mean of array // Function Definition of findMean functionfunction findMean($A, $N){ if ($N == 1) return $A[$N - 1]; else return ((findMean($A, $N - 1) * ($N - 1) + $A[$N - 1]) / $N);} // Driver Code$Mean = 0;$A = array(1, 2, 3, 4, 5);$N = sizeof($A);echo findMean($A, $N); // This code is contributed by ajit.?>",
"e": 27936,
"s": 27541,
"text": null
},
{
"code": "<script> // Recursive Javascript program to find mean of array // Function Definition of findMean function function findMean(A, N) { if (N == 1) return A[N - 1]; else return ((findMean(A, N - 1) * (N - 1) + A[N - 1]) / N); } // float Mean = 0; let A = [1, 2, 3, 4, 5]; let N = A.length; document.write(findMean(A, N)); // This code is contributed by rameshtravel07.</script>",
"e": 28392,
"s": 27936,
"text": null
},
{
"code": null,
"e": 28402,
"s": 28392,
"text": "Output: "
},
{
"code": null,
"e": 28404,
"s": 28402,
"text": "3"
},
{
"code": null,
"e": 28828,
"s": 28404,
"text": "This article is contributed by Prakhar Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 28834,
"s": 28828,
"text": "jit_t"
},
{
"code": null,
"e": 28849,
"s": 28834,
"text": "rameshtravel07"
},
{
"code": null,
"e": 28868,
"s": 28849,
"text": "surindertarika1234"
},
{
"code": null,
"e": 28887,
"s": 28868,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 28894,
"s": 28887,
"text": "Arrays"
},
{
"code": null,
"e": 28913,
"s": 28894,
"text": "School Programming"
},
{
"code": null,
"e": 28920,
"s": 28913,
"text": "Arrays"
},
{
"code": null,
"e": 29018,
"s": 28920,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29027,
"s": 29018,
"text": "Comments"
},
{
"code": null,
"e": 29040,
"s": 29027,
"text": "Old Comments"
},
{
"code": null,
"e": 29088,
"s": 29040,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 29120,
"s": 29088,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 29174,
"s": 29120,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 29188,
"s": 29174,
"text": "Linear Search"
},
{
"code": null,
"e": 29233,
"s": 29188,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 29251,
"s": 29233,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29270,
"s": 29251,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 29295,
"s": 29270,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 29314,
"s": 29295,
"text": "Overriding in Java"
}
] |
Classifying Parkinson’s disease through image analysis: Part 1 | by Robin T. White, PhD | Towards Data Science | Parkinson’s disease is often associated with movement disorder symptoms such as tremors and rigidity. These can have a noticeable effect on the handwriting and sketching (drawing)of a person suffering from early stages of the disease [1]. Micrographia, are abnormally small undulations in a persons handwriting, however, have claimed to be difficult to interpret due to the variability in one’s developed handwriting, language, proficiency and education etc [1]. As such, a study conducted in 2017 aimed to improve the diagnosis through a standardized analysis using spirals and waves. In this series of posts, we will analyze the raw images collected in that study and see if we can create a classifier for a patient having Parkinson’s, and draw some conclusions along the way. The data we will be using is hosted on Kaggle [2] with special thanks to Kevin Mader for sharing the dataset upload.
In this part 1, we will be conducting some exploratory data analysis and pre-processing the images to create some features that will hopefully be helpful in classification. I am choosing to NOT use a convolutional neural network (CNN) to simply classify the images as this will be black box — without any metric into the underlying differences between the curves/sketches. Instead, we are not simply performing a task of classifying but trying to use image processing to understand and quantify the differences. In a subsequent post, I will compare with a CNN.
Before we begin, disclaimer that this is not meant to be any kind of medical study or test. Please refer to the original paper for details on the actual experiment, which I was not a part of.Zham P, Kumar DK, Dabnichki P, Poosapadi Arjunan S, Raghav S. Distinguishing Different Stages of Parkinson’s Disease Using Composite Index of Speed and Pen-Pressure of Sketching a Spiral. Front Neurol. 2017;8:435. Published 2017 Sep 6. doi:10.3389/fneur.2017.00435
First, let us take a look at the images, perform some basic segmentation and start poking around with some potential features of interest. We will be using pandas throughout to store the images and information. For those of you questioning whether you will read this section here is what we will get into: - Thresholding and cleaning- Thickness quantification through nearest neighbors- Skeletonization- Intersections and edge points
We use a modified read and threshold function, mostly obtained from the original notebook by Kevin Mader on Kaggle [2]. Here, we have the option to perform a resizing when wanting to view the montage style images, like above and below. We first read in and invert the image so the drawings are white on black background, as well as resize if necessary. We also apply a small median filter.
This project has quite a fair bit of code, I won’t be posting it all here so please see the github link if you want to view the notebook or python script for more details.
from skimage.io import imreadfrom skimage.util import montage as montage2dfrom skimage.filters import threshold_yen as thresh_funcfrom skimage.filters import medianfrom skimage.morphology import diskimport numpy as npdef process_imread(in_path, resize=True): """read images, invert and scale them""" c_img = 1.0-imread(in_path, as_gray=True) max_dim = np.max(c_img.shape) if not resize: return c_img if c_img.shape==(256, 256): return c_img if max_dim>256: big_dim = 512 else: big_dim = 256 """ pad with zeros and center image, sizing to either 256 or 512""" out_img = np.zeros((big_dim, big_dim), dtype='float32') c_offset = (big_dim-c_img.shape[0])//2 d_offset = c_img.shape[0]+c_offset e_offset = (big_dim-c_img.shape[1])//2 f_offset = c_img.shape[1]+e_offset out_img[c_offset:d_offset, e_offset:f_offset] = c_img[:(d_offset-c_offset), :(f_offset-e_offset)] return out_imgdef read_and_thresh(in_path, resize=True): c_img = process_imread(in_path, resize=resize) c_img = (255*c_img).clip(0, 255).astype('uint8') c_img = median(c_img, disk(1)) c_thresh = thresh_func(c_img) return c_img>c_thresh
Lastly, for the read in, we also clean up the images by removing any small objects disconnected from the main sketch.
from skimage.morphology import label as sk_labeldef label_sort(in_img, cutoff=0.01): total_cnt = np.sum(in_img>0) lab_img = sk_label(in_img) new_image = np.zeros_like(lab_img) remap_index = [] for k in np.unique(lab_img[lab_img>0]): cnt = np.sum(lab_img==k) # get area of labelled object if cnt>total_cnt*cutoff: remap_index+=[(k, cnt)] sorted_index = sorted(remap_index, key=lambda x: -x[1]) # reverse sort - largest is first for new_idx, (old_idx, idx_count) in enumerate(sorted_index, 1): #enumerate starting at id 1 new_image[lab_img==old_idx] = new_idx return new_image
This works by keeping only large enough components that are >1% of activated pixels; defined by cutoff. First label each separate object in the image and sum the areas for each label identified (that isn’t 0). Keep the index if the count is more than 1% of the total. Perform negative sort to have the largest objects with label 1. Replace the old label number with the new ordered id.
As an initial view of how different the drawings are, we can create a skeleton image and form a new data frame where each row is a single pixel coordinate of non-zero pixels in each image. We can then plot each of these curves on a single graph — after normalizing the positions. We won’t be using this format of the data frame, this is just for visualization.
As we can see there is strong consistency between healthy sketches. This makes sense considering the random motion that Parkinson’s symptoms can cause.
Next, we will try to quantify the thickness. For this, we will be using a distance map to give an approximation of the width of the drawings. The medial axis also returns a distance map, but skeletonize is cleaner as it does some pruning.
from skimage.morphology import medial_axisfrom skimage.morphology import skeletonizedef stroke_thickness_img(in_img): skel, distance = medial_axis(in_img, return_distance=True) skeleton = skeletonize(in_img) # Distance to the background for pixels of the skeleton return distance * skeleton
Plotting the mean and standard deviation we see some correlation between the drawings. Mostly in the standard deviation which again makes sense considering the random impact, also the fact it is great and not less than healthy also makes sense.
Due to the way that skeletonizing an image works, depending on the ‘smoothness’ of the line, there will be a higher number of end-points for more undulating curves. These are therefore some measure of the random movement compared with a smooth line. In addition, we can calculate the number of intersection points; a perfect curve would have no intersections and only two end-points. These are also useful in other image processing applications such as with road mapping.
I won’t go into the code too much here as there is a fair bit of cleaning required, however, I will try to explain what I did using some images. First, we calculate a nearest neighbors image of the skeleton of the curve. This gives us values of 2 everywhere, except a value of 1 at edge-points, and a value of 3 at intersections; this is when using a connectivity of 2 (the 8 nearest neighbors). Here is an image of the result, zoomed in.
As you can see this works as expected, except we run into some issues if we want to get only one pixel intersection to properly quantify the number of intersections. The image on the right has three pixels with value 3, although this is only one intersection. We can clean this up with the following pseudo algorithm by isolating for these regions as the sum of these intersections is greater than the ‘correct’ intersection. We can sum the nearest neighbors (NN) image and threshold to isolate these. Connectivity 1 has direct neighbors, connected 2 includes diagonals.
From original NN, sum using connectivity 1 and 2 separately.
Isolate intersections which have value ≥ 8 in connectivity 2.
Label each edge that is connected to the intersection pixels.
Isolate the intersection pixels which sum between 3 and 5 for the connectivity 1 image. These are the one we don’t want.
Overwrite incorrect intersection pixels.
Here is the result:
As you can see we now have a single pixel with value 3 at the intersection location. We can now simply sum these locations to quantify the number of intersection points. If we draw these on a curve we can see the result, below yellow are intersections and green are edge-points.
If we plot the number of these for each drawing type we can see the fairly strong correlation:
We can also see our initial estimate of a healthy curve having approximately 2 edge-points is also correct. There is a very high number of edge-points for Parkinson’s wave drawings because these are usually quite ‘sharp’ instead of curved smoothly, this creates a high number of edge-points at the tips of these waves.
Lastly, we can also check the correlation with the overall number of pixels in the skeleton image. This is related to the ‘indirect’ nature of the drawings. This quantification is very simple, we just sum the pixels greater than zero in a skeleton image.
Not as strong as a relationship but still something.
So far we have now read in, cleaned and obtained some potentially useful metrics, that help us not only understand the degree of micrographia but also can be used as inputs into a classifier such as Logistic Regression or Random Forest. In part 2 of this series we will perform classification using these metrics and also compare to a more powerful, but black-box, neural network. The advantage of using Random Forest is we will also be able to see which features provide the strongest impact to the model. Based on the above observations, do you have an intuition already about which features may be the most important?
If you felt that any part of this post provided some useful information or just a bit of inspiration please follow me for more.
You can find the source code on my github. This project is currently still under construction.
Link to my other posts:
Computer Vision and the Ultimate Pong AI — Using Python and OpenCV to play Pong online
Minecraft Mapper — Computer Vision and OCR to grab positions from screenshots and plot
Not used here, but for fun, we can also create a graph for the representation of each image since we have nodes and edges, where the nodes are the intersections or edge-points and the edges are the sections of the drawings connecting these.
We used Networkx library for this, where each number is either a node or intersection with the colors corresponding to the length of the section of drawing connecting the nodes.
[1] Zham P, Kumar DK, Dabnichki P, Poosapadi Arjunan S, Raghav S. Distinguishing Different Stages of Parkinson’s Disease Using Composite Index of Speed and Pen-Pressure of Sketching a Spiral. Front Neurol. 2017;8:435. Published 2017 Sep 6. doi:10.3389/fneur.2017.00435[2] Mader, K. Parkinson’s Sketch Overview. https://www.kaggle.com/kmader/parkinsons-drawings. Obtained: 09/07/2020 | [
{
"code": null,
"e": 1067,
"s": 171,
"text": "Parkinson’s disease is often associated with movement disorder symptoms such as tremors and rigidity. These can have a noticeable effect on the handwriting and sketching (drawing)of a person suffering from early stages of the disease [1]. Micrographia, are abnormally small undulations in a persons handwriting, however, have claimed to be difficult to interpret due to the variability in one’s developed handwriting, language, proficiency and education etc [1]. As such, a study conducted in 2017 aimed to improve the diagnosis through a standardized analysis using spirals and waves. In this series of posts, we will analyze the raw images collected in that study and see if we can create a classifier for a patient having Parkinson’s, and draw some conclusions along the way. The data we will be using is hosted on Kaggle [2] with special thanks to Kevin Mader for sharing the dataset upload."
},
{
"code": null,
"e": 1628,
"s": 1067,
"text": "In this part 1, we will be conducting some exploratory data analysis and pre-processing the images to create some features that will hopefully be helpful in classification. I am choosing to NOT use a convolutional neural network (CNN) to simply classify the images as this will be black box — without any metric into the underlying differences between the curves/sketches. Instead, we are not simply performing a task of classifying but trying to use image processing to understand and quantify the differences. In a subsequent post, I will compare with a CNN."
},
{
"code": null,
"e": 2084,
"s": 1628,
"text": "Before we begin, disclaimer that this is not meant to be any kind of medical study or test. Please refer to the original paper for details on the actual experiment, which I was not a part of.Zham P, Kumar DK, Dabnichki P, Poosapadi Arjunan S, Raghav S. Distinguishing Different Stages of Parkinson’s Disease Using Composite Index of Speed and Pen-Pressure of Sketching a Spiral. Front Neurol. 2017;8:435. Published 2017 Sep 6. doi:10.3389/fneur.2017.00435"
},
{
"code": null,
"e": 2518,
"s": 2084,
"text": "First, let us take a look at the images, perform some basic segmentation and start poking around with some potential features of interest. We will be using pandas throughout to store the images and information. For those of you questioning whether you will read this section here is what we will get into: - Thresholding and cleaning- Thickness quantification through nearest neighbors- Skeletonization- Intersections and edge points"
},
{
"code": null,
"e": 2908,
"s": 2518,
"text": "We use a modified read and threshold function, mostly obtained from the original notebook by Kevin Mader on Kaggle [2]. Here, we have the option to perform a resizing when wanting to view the montage style images, like above and below. We first read in and invert the image so the drawings are white on black background, as well as resize if necessary. We also apply a small median filter."
},
{
"code": null,
"e": 3080,
"s": 2908,
"text": "This project has quite a fair bit of code, I won’t be posting it all here so please see the github link if you want to view the notebook or python script for more details."
},
{
"code": null,
"e": 4272,
"s": 3080,
"text": "from skimage.io import imreadfrom skimage.util import montage as montage2dfrom skimage.filters import threshold_yen as thresh_funcfrom skimage.filters import medianfrom skimage.morphology import diskimport numpy as npdef process_imread(in_path, resize=True): \"\"\"read images, invert and scale them\"\"\" c_img = 1.0-imread(in_path, as_gray=True) max_dim = np.max(c_img.shape) if not resize: return c_img if c_img.shape==(256, 256): return c_img if max_dim>256: big_dim = 512 else: big_dim = 256 \"\"\" pad with zeros and center image, sizing to either 256 or 512\"\"\" out_img = np.zeros((big_dim, big_dim), dtype='float32') c_offset = (big_dim-c_img.shape[0])//2 d_offset = c_img.shape[0]+c_offset e_offset = (big_dim-c_img.shape[1])//2 f_offset = c_img.shape[1]+e_offset out_img[c_offset:d_offset, e_offset:f_offset] = c_img[:(d_offset-c_offset), :(f_offset-e_offset)] return out_imgdef read_and_thresh(in_path, resize=True): c_img = process_imread(in_path, resize=resize) c_img = (255*c_img).clip(0, 255).astype('uint8') c_img = median(c_img, disk(1)) c_thresh = thresh_func(c_img) return c_img>c_thresh"
},
{
"code": null,
"e": 4390,
"s": 4272,
"text": "Lastly, for the read in, we also clean up the images by removing any small objects disconnected from the main sketch."
},
{
"code": null,
"e": 5021,
"s": 4390,
"text": "from skimage.morphology import label as sk_labeldef label_sort(in_img, cutoff=0.01): total_cnt = np.sum(in_img>0) lab_img = sk_label(in_img) new_image = np.zeros_like(lab_img) remap_index = [] for k in np.unique(lab_img[lab_img>0]): cnt = np.sum(lab_img==k) # get area of labelled object if cnt>total_cnt*cutoff: remap_index+=[(k, cnt)] sorted_index = sorted(remap_index, key=lambda x: -x[1]) # reverse sort - largest is first for new_idx, (old_idx, idx_count) in enumerate(sorted_index, 1): #enumerate starting at id 1 new_image[lab_img==old_idx] = new_idx return new_image"
},
{
"code": null,
"e": 5407,
"s": 5021,
"text": "This works by keeping only large enough components that are >1% of activated pixels; defined by cutoff. First label each separate object in the image and sum the areas for each label identified (that isn’t 0). Keep the index if the count is more than 1% of the total. Perform negative sort to have the largest objects with label 1. Replace the old label number with the new ordered id."
},
{
"code": null,
"e": 5768,
"s": 5407,
"text": "As an initial view of how different the drawings are, we can create a skeleton image and form a new data frame where each row is a single pixel coordinate of non-zero pixels in each image. We can then plot each of these curves on a single graph — after normalizing the positions. We won’t be using this format of the data frame, this is just for visualization."
},
{
"code": null,
"e": 5920,
"s": 5768,
"text": "As we can see there is strong consistency between healthy sketches. This makes sense considering the random motion that Parkinson’s symptoms can cause."
},
{
"code": null,
"e": 6159,
"s": 5920,
"text": "Next, we will try to quantify the thickness. For this, we will be using a distance map to give an approximation of the width of the drawings. The medial axis also returns a distance map, but skeletonize is cleaner as it does some pruning."
},
{
"code": null,
"e": 6462,
"s": 6159,
"text": "from skimage.morphology import medial_axisfrom skimage.morphology import skeletonizedef stroke_thickness_img(in_img): skel, distance = medial_axis(in_img, return_distance=True) skeleton = skeletonize(in_img) # Distance to the background for pixels of the skeleton return distance * skeleton"
},
{
"code": null,
"e": 6707,
"s": 6462,
"text": "Plotting the mean and standard deviation we see some correlation between the drawings. Mostly in the standard deviation which again makes sense considering the random impact, also the fact it is great and not less than healthy also makes sense."
},
{
"code": null,
"e": 7179,
"s": 6707,
"text": "Due to the way that skeletonizing an image works, depending on the ‘smoothness’ of the line, there will be a higher number of end-points for more undulating curves. These are therefore some measure of the random movement compared with a smooth line. In addition, we can calculate the number of intersection points; a perfect curve would have no intersections and only two end-points. These are also useful in other image processing applications such as with road mapping."
},
{
"code": null,
"e": 7618,
"s": 7179,
"text": "I won’t go into the code too much here as there is a fair bit of cleaning required, however, I will try to explain what I did using some images. First, we calculate a nearest neighbors image of the skeleton of the curve. This gives us values of 2 everywhere, except a value of 1 at edge-points, and a value of 3 at intersections; this is when using a connectivity of 2 (the 8 nearest neighbors). Here is an image of the result, zoomed in."
},
{
"code": null,
"e": 8189,
"s": 7618,
"text": "As you can see this works as expected, except we run into some issues if we want to get only one pixel intersection to properly quantify the number of intersections. The image on the right has three pixels with value 3, although this is only one intersection. We can clean this up with the following pseudo algorithm by isolating for these regions as the sum of these intersections is greater than the ‘correct’ intersection. We can sum the nearest neighbors (NN) image and threshold to isolate these. Connectivity 1 has direct neighbors, connected 2 includes diagonals."
},
{
"code": null,
"e": 8250,
"s": 8189,
"text": "From original NN, sum using connectivity 1 and 2 separately."
},
{
"code": null,
"e": 8312,
"s": 8250,
"text": "Isolate intersections which have value ≥ 8 in connectivity 2."
},
{
"code": null,
"e": 8374,
"s": 8312,
"text": "Label each edge that is connected to the intersection pixels."
},
{
"code": null,
"e": 8495,
"s": 8374,
"text": "Isolate the intersection pixels which sum between 3 and 5 for the connectivity 1 image. These are the one we don’t want."
},
{
"code": null,
"e": 8536,
"s": 8495,
"text": "Overwrite incorrect intersection pixels."
},
{
"code": null,
"e": 8556,
"s": 8536,
"text": "Here is the result:"
},
{
"code": null,
"e": 8835,
"s": 8556,
"text": "As you can see we now have a single pixel with value 3 at the intersection location. We can now simply sum these locations to quantify the number of intersection points. If we draw these on a curve we can see the result, below yellow are intersections and green are edge-points."
},
{
"code": null,
"e": 8930,
"s": 8835,
"text": "If we plot the number of these for each drawing type we can see the fairly strong correlation:"
},
{
"code": null,
"e": 9249,
"s": 8930,
"text": "We can also see our initial estimate of a healthy curve having approximately 2 edge-points is also correct. There is a very high number of edge-points for Parkinson’s wave drawings because these are usually quite ‘sharp’ instead of curved smoothly, this creates a high number of edge-points at the tips of these waves."
},
{
"code": null,
"e": 9504,
"s": 9249,
"text": "Lastly, we can also check the correlation with the overall number of pixels in the skeleton image. This is related to the ‘indirect’ nature of the drawings. This quantification is very simple, we just sum the pixels greater than zero in a skeleton image."
},
{
"code": null,
"e": 9557,
"s": 9504,
"text": "Not as strong as a relationship but still something."
},
{
"code": null,
"e": 10178,
"s": 9557,
"text": "So far we have now read in, cleaned and obtained some potentially useful metrics, that help us not only understand the degree of micrographia but also can be used as inputs into a classifier such as Logistic Regression or Random Forest. In part 2 of this series we will perform classification using these metrics and also compare to a more powerful, but black-box, neural network. The advantage of using Random Forest is we will also be able to see which features provide the strongest impact to the model. Based on the above observations, do you have an intuition already about which features may be the most important?"
},
{
"code": null,
"e": 10306,
"s": 10178,
"text": "If you felt that any part of this post provided some useful information or just a bit of inspiration please follow me for more."
},
{
"code": null,
"e": 10401,
"s": 10306,
"text": "You can find the source code on my github. This project is currently still under construction."
},
{
"code": null,
"e": 10425,
"s": 10401,
"text": "Link to my other posts:"
},
{
"code": null,
"e": 10512,
"s": 10425,
"text": "Computer Vision and the Ultimate Pong AI — Using Python and OpenCV to play Pong online"
},
{
"code": null,
"e": 10599,
"s": 10512,
"text": "Minecraft Mapper — Computer Vision and OCR to grab positions from screenshots and plot"
},
{
"code": null,
"e": 10840,
"s": 10599,
"text": "Not used here, but for fun, we can also create a graph for the representation of each image since we have nodes and edges, where the nodes are the intersections or edge-points and the edges are the sections of the drawings connecting these."
},
{
"code": null,
"e": 11018,
"s": 10840,
"text": "We used Networkx library for this, where each number is either a node or intersection with the colors corresponding to the length of the section of drawing connecting the nodes."
}
] |
Matcher appendReplacement() method in Java with Examples | The java.util.regex.Matcher class represents an engine that performs various match operations. There is no constructor for this class, you can create/obtain an object of this class using the matches() method of the class java.util.regex.Pattern.
The appendReplacement() method of this (Matcher) class accepts a StringBuffer object and a String (replacement string) as parameters and, appends the input data to the StringBuffer object, replacing the matched content with the replacement string.
Internally, this method reads each character from the input string and appends the String buffer, whenever a match occurs it appends the replacement string instead of matched content part of the string to the buffer and, proceeds from the next position of the matched substring.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class appendReplacementExample {
public static void main(String[] args) {
String str = "<p>This <b>is</b> an <b>example</b>HTML <b>script</b>.</p>";
//Regular expression to match contents of the bold tags
String regex = "<b>(\\S+)</b>";
System.out.println("Input string: \n"+str);
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Matching the compiled pattern in the String
Matcher matcher = pattern.matcher(str);
//Creating an empty string buffer
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, "BoldData");
}
matcher.appendTail(sb);
System.out.println("Contents of the StringBuffer: \n"+ sb.toString() );
}
}
Input string:
<p>This <b>is</b> an <b>example</b> HTML <b>script</b>.</p>
Contents of the StringBuffer:
This BoldData an BoldData HTML BoldData.
<p>This BoldData an BoldData HTML BoldData.</p>
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class appendReplacementExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
String regex = "[#$&+=@|<>-]";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Creating a Matcher object
Matcher matcher = pattern.matcher(input);
int count =0;
StringBuffer buffer = new StringBuffer();
System.out.println("Removing the special character form the given string");
while(matcher.find()) {
count++;
matcher.appendReplacement(buffer, "");
}
matcher.appendTail(buffer);
//Retrieving Pattern used
System.out.println("The are special characters occurred "+count+" times in the given text");
System.out.println("Text after removing all of them \n"+buffer.toString());
}
}
Enter input text:
Hello# how$ are& yo|u welco<me to> Tut-oria@ls@po-in#t.
Removing the special character form the given string
The are special characters occurred 11 times in the given text
Text after removing all of them
Hello how are you welcome to Tutorialspoint. | [
{
"code": null,
"e": 1308,
"s": 1062,
"text": "The java.util.regex.Matcher class represents an engine that performs various match operations. There is no constructor for this class, you can create/obtain an object of this class using the matches() method of the class java.util.regex.Pattern."
},
{
"code": null,
"e": 1556,
"s": 1308,
"text": "The appendReplacement() method of this (Matcher) class accepts a StringBuffer object and a String (replacement string) as parameters and, appends the input data to the StringBuffer object, replacing the matched content with the replacement string."
},
{
"code": null,
"e": 1835,
"s": 1556,
"text": "Internally, this method reads each character from the input string and appends the String buffer, whenever a match occurs it appends the replacement string instead of matched content part of the string to the buffer and, proceeds from the next position of the matched substring."
},
{
"code": null,
"e": 2684,
"s": 1835,
"text": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class appendReplacementExample {\n public static void main(String[] args) {\n String str = \"<p>This <b>is</b> an <b>example</b>HTML <b>script</b>.</p>\";\n //Regular expression to match contents of the bold tags\n String regex = \"<b>(\\\\S+)</b>\";\n System.out.println(\"Input string: \\n\"+str);\n //Creating a pattern object\n Pattern pattern = Pattern.compile(regex);\n //Matching the compiled pattern in the String\n Matcher matcher = pattern.matcher(str);\n //Creating an empty string buffer\n StringBuffer sb = new StringBuffer();\n while (matcher.find()) {\n matcher.appendReplacement(sb, \"BoldData\");\n }\n matcher.appendTail(sb);\n System.out.println(\"Contents of the StringBuffer: \\n\"+ sb.toString() );\n }\n}"
},
{
"code": null,
"e": 2877,
"s": 2684,
"text": "Input string:\n<p>This <b>is</b> an <b>example</b> HTML <b>script</b>.</p>\nContents of the StringBuffer:\nThis BoldData an BoldData HTML BoldData.\n<p>This BoldData an BoldData HTML BoldData.</p>"
},
{
"code": null,
"e": 3887,
"s": 2877,
"text": "import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class appendReplacementExample {\n public static void main(String[] args) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter input text: \");\n String input = sc.nextLine();\n String regex = \"[#$&+=@|<>-]\";\n //Creating a pattern object\n Pattern pattern = Pattern.compile(regex);\n //Creating a Matcher object\n Matcher matcher = pattern.matcher(input);\n int count =0;\n StringBuffer buffer = new StringBuffer();\n System.out.println(\"Removing the special character form the given string\");\n while(matcher.find()) {\n count++;\n matcher.appendReplacement(buffer, \"\");\n }\n matcher.appendTail(buffer);\n //Retrieving Pattern used\n System.out.println(\"The are special characters occurred \"+count+\" times in the given text\");\n System.out.println(\"Text after removing all of them \\n\"+buffer.toString());\n }\n}"
},
{
"code": null,
"e": 4154,
"s": 3887,
"text": "Enter input text:\nHello# how$ are& yo|u welco<me to> Tut-oria@ls@po-in#t.\nRemoving the special character form the given string\nThe are special characters occurred 11 times in the given text\nText after removing all of them\nHello how are you welcome to Tutorialspoint."
}
] |
Else without IF and L-Value Required Error in C - GeeksforGeeks | 08 Jan, 2019
This error is shown if we write anything in between if and else clause.
Example:
#include <stdio.h> void main(){ int a; if (a == 2) a++; // due to this line, we will // get error as misplaced else. printf("value of a is", a); else printf("value of a is not equal to 2 ");}
Output:
prog.c: In function 'main':
prog.c:15:5: error: 'else' without a previous 'if'
else printf("value of a is not equal to 2 ");
^
This error occurs when we put constants on left hand side of = operator and variables on right hand side of it.
Example:
#include <stdio.h> void main(){ int a; 10 = a;}
Output:
prog.c: In function 'main':
prog.c:6:5: error: lvalue required as left operand of assignment
10 = a;
^
Example 2: At line number 12, it will show an error L-value because arr++ means arr=arr+1.Now that is what their is difference in normal variable and array. If we write a=a+1 (where a is normal variable), compiler will know its job and their will be no error but when you write arr=arr+1 (where arr is name of an array) then, compiler will think arr contain address and how we can change address. Therefore it will take arr as address and left side will be constant, hence it will show error as L-value required.
#include <stdio.h> void main(){ int arr[5]; int i; for (i = 0; i < 5; i++) { printf("Enter number: "); scanf("%d", arr); arr++; }}
Output:
prog.c: In function 'main':
prog.c:10:6: error: lvalue required as increment operand
arr++;
^
C Language
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Multithreading in C
Exception Handling in C++
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Strings in C
Arrow operator -> in C/C++ with Examples
C Program to read contents of Whole File
UDP Server-Client implementation in C
Header files in C/C++ and its uses | [
{
"code": null,
"e": 24234,
"s": 24206,
"text": "\n08 Jan, 2019"
},
{
"code": null,
"e": 24306,
"s": 24234,
"text": "This error is shown if we write anything in between if and else clause."
},
{
"code": null,
"e": 24315,
"s": 24306,
"text": "Example:"
},
{
"code": "#include <stdio.h> void main(){ int a; if (a == 2) a++; // due to this line, we will // get error as misplaced else. printf(\"value of a is\", a); else printf(\"value of a is not equal to 2 \");}",
"e": 24539,
"s": 24315,
"text": null
},
{
"code": null,
"e": 24547,
"s": 24539,
"text": "Output:"
},
{
"code": null,
"e": 24685,
"s": 24547,
"text": "prog.c: In function 'main':\nprog.c:15:5: error: 'else' without a previous 'if'\n else printf(\"value of a is not equal to 2 \");\n ^\n"
},
{
"code": null,
"e": 24797,
"s": 24685,
"text": "This error occurs when we put constants on left hand side of = operator and variables on right hand side of it."
},
{
"code": null,
"e": 24806,
"s": 24797,
"text": "Example:"
},
{
"code": "#include <stdio.h> void main(){ int a; 10 = a;}",
"e": 24861,
"s": 24806,
"text": null
},
{
"code": null,
"e": 24869,
"s": 24861,
"text": "Output:"
},
{
"code": null,
"e": 24980,
"s": 24869,
"text": "prog.c: In function 'main':\nprog.c:6:5: error: lvalue required as left operand of assignment\n 10 = a;\n ^\n"
},
{
"code": null,
"e": 25493,
"s": 24980,
"text": "Example 2: At line number 12, it will show an error L-value because arr++ means arr=arr+1.Now that is what their is difference in normal variable and array. If we write a=a+1 (where a is normal variable), compiler will know its job and their will be no error but when you write arr=arr+1 (where arr is name of an array) then, compiler will think arr contain address and how we can change address. Therefore it will take arr as address and left side will be constant, hence it will show error as L-value required."
},
{
"code": "#include <stdio.h> void main(){ int arr[5]; int i; for (i = 0; i < 5; i++) { printf(\"Enter number: \"); scanf(\"%d\", arr); arr++; }}",
"e": 25658,
"s": 25493,
"text": null
},
{
"code": null,
"e": 25666,
"s": 25658,
"text": "Output:"
},
{
"code": null,
"e": 25770,
"s": 25666,
"text": "prog.c: In function 'main':\nprog.c:10:6: error: lvalue required as increment operand\n arr++;\n ^\n"
},
{
"code": null,
"e": 25781,
"s": 25770,
"text": "C Language"
},
{
"code": null,
"e": 25792,
"s": 25781,
"text": "C Programs"
},
{
"code": null,
"e": 25890,
"s": 25792,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25928,
"s": 25890,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 25948,
"s": 25928,
"text": "Multithreading in C"
},
{
"code": null,
"e": 25974,
"s": 25948,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 25996,
"s": 25974,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 26037,
"s": 25996,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 26050,
"s": 26037,
"text": "Strings in C"
},
{
"code": null,
"e": 26091,
"s": 26050,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 26132,
"s": 26091,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 26170,
"s": 26132,
"text": "UDP Server-Client implementation in C"
}
] |
Apache Solr - Retrieving Data | In this chapter, we will discuss how to retrieve data using Java Client API. Suppose we have a .csv document named sample.csv with the following content.
001,9848022337,Hyderabad,Rajiv,Reddy
002,9848022338,Kolkata,Siddarth,Battacharya
003,9848022339,Delhi,Rajesh,Khanna
You can index this data under the core named sample_Solr using the post command.
[Hadoop@localhost bin]$ ./post -c Solr_sample sample.csv
Following is the Java program to add documents to Apache Solr index. Save this code in a file with named RetrievingData.java.
import java.io.IOException;
import org.apache.Solr.client.Solrj.SolrClient;
import org.apache.Solr.client.Solrj.SolrQuery;
import org.apache.Solr.client.Solrj.SolrServerException;
import org.apache.Solr.client.Solrj.impl.HttpSolrClient;
import org.apache.Solr.client.Solrj.response.QueryResponse;
import org.apache.Solr.common.SolrDocumentList;
public class RetrievingData {
public static void main(String args[]) throws SolrServerException, IOException {
//Preparing the Solr client
String urlString = "http://localhost:8983/Solr/my_core";
SolrClient Solr = new HttpSolrClient.Builder(urlString).build();
//Preparing Solr query
SolrQuery query = new SolrQuery();
query.setQuery("*:*");
//Adding the field to be retrieved
query.addField("*");
//Executing the query
QueryResponse queryResponse = Solr.query(query);
//Storing the results of the query
SolrDocumentList docs = queryResponse.getResults();
System.out.println(docs);
System.out.println(docs.get(0));
System.out.println(docs.get(1));
System.out.println(docs.get(2));
//Saving the operations
Solr.commit();
}
}
Compile the above code by executing the following commands in the terminal −
[Hadoop@localhost bin]$ javac RetrievingData
[Hadoop@localhost bin]$ java RetrievingData
On executing the above command, you will get the following output.
{numFound = 3,start = 0,docs = [SolrDocument{id=001, phone = [9848022337],
city = [Hyderabad], first_name = [Rajiv], last_name = [Reddy],
_version_ = 1547262806014820352}, SolrDocument{id = 002, phone = [9848022338],
city = [Kolkata], first_name = [Siddarth], last_name = [Battacharya],
_version_ = 1547262806026354688}, SolrDocument{id = 003, phone = [9848022339],
city = [Delhi], first_name = [Rajesh], last_name = [Khanna],
_version_ = 1547262806029500416}]}
SolrDocument{id = 001, phone = [9848022337], city = [Hyderabad], first_name = [Rajiv],
last_name = [Reddy], _version_ = 1547262806014820352}
SolrDocument{id = 002, phone = [9848022338], city = [Kolkata], first_name = [Siddarth],
last_name = [Battacharya], _version_ = 1547262806026354688}
SolrDocument{id = 003, phone = [9848022339], city = [Delhi], first_name = [Rajesh],
last_name = [Khanna], _version_ = 1547262806029500416}
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2178,
"s": 2024,
"text": "In this chapter, we will discuss how to retrieve data using Java Client API. Suppose we have a .csv document named sample.csv with the following content."
},
{
"code": null,
"e": 2298,
"s": 2178,
"text": "001,9848022337,Hyderabad,Rajiv,Reddy \n002,9848022338,Kolkata,Siddarth,Battacharya \n003,9848022339,Delhi,Rajesh,Khanna\n"
},
{
"code": null,
"e": 2379,
"s": 2298,
"text": "You can index this data under the core named sample_Solr using the post command."
},
{
"code": null,
"e": 2437,
"s": 2379,
"text": "[Hadoop@localhost bin]$ ./post -c Solr_sample sample.csv\n"
},
{
"code": null,
"e": 2563,
"s": 2437,
"text": "Following is the Java program to add documents to Apache Solr index. Save this code in a file with named RetrievingData.java."
},
{
"code": null,
"e": 3826,
"s": 2563,
"text": "import java.io.IOException; \n\nimport org.apache.Solr.client.Solrj.SolrClient; \nimport org.apache.Solr.client.Solrj.SolrQuery; \nimport org.apache.Solr.client.Solrj.SolrServerException; \nimport org.apache.Solr.client.Solrj.impl.HttpSolrClient; \nimport org.apache.Solr.client.Solrj.response.QueryResponse; \nimport org.apache.Solr.common.SolrDocumentList; \n\npublic class RetrievingData { \n public static void main(String args[]) throws SolrServerException, IOException { \n //Preparing the Solr client \n String urlString = \"http://localhost:8983/Solr/my_core\"; \n SolrClient Solr = new HttpSolrClient.Builder(urlString).build(); \n \n //Preparing Solr query \n SolrQuery query = new SolrQuery(); \n query.setQuery(\"*:*\"); \n \n //Adding the field to be retrieved \n query.addField(\"*\"); \n \n //Executing the query \n QueryResponse queryResponse = Solr.query(query); \n \n //Storing the results of the query \n SolrDocumentList docs = queryResponse.getResults(); \n System.out.println(docs); \n System.out.println(docs.get(0)); \n System.out.println(docs.get(1)); \n System.out.println(docs.get(2)); \n \n //Saving the operations \n Solr.commit(); \n } \n}"
},
{
"code": null,
"e": 3903,
"s": 3826,
"text": "Compile the above code by executing the following commands in the terminal −"
},
{
"code": null,
"e": 3994,
"s": 3903,
"text": "[Hadoop@localhost bin]$ javac RetrievingData \n[Hadoop@localhost bin]$ java RetrievingData\n"
},
{
"code": null,
"e": 4061,
"s": 3994,
"text": "On executing the above command, you will get the following output."
},
{
"code": null,
"e": 4969,
"s": 4061,
"text": "{numFound = 3,start = 0,docs = [SolrDocument{id=001, phone = [9848022337], \ncity = [Hyderabad], first_name = [Rajiv], last_name = [Reddy], \n_version_ = 1547262806014820352}, SolrDocument{id = 002, phone = [9848022338], \ncity = [Kolkata], first_name = [Siddarth], last_name = [Battacharya], \n\n_version_ = 1547262806026354688}, SolrDocument{id = 003, phone = [9848022339], \ncity = [Delhi], first_name = [Rajesh], last_name = [Khanna], \n\n_version_ = 1547262806029500416}]} \n\nSolrDocument{id = 001, phone = [9848022337], city = [Hyderabad], first_name = [Rajiv], \nlast_name = [Reddy], _version_ = 1547262806014820352} \n\nSolrDocument{id = 002, phone = [9848022338], city = [Kolkata], first_name = [Siddarth], \nlast_name = [Battacharya], _version_ = 1547262806026354688} \n\nSolrDocument{id = 003, phone = [9848022339], city = [Delhi], first_name = [Rajesh], \nlast_name = [Khanna], _version_ = 1547262806029500416}\n"
},
{
"code": null,
"e": 5004,
"s": 4969,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5023,
"s": 5004,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5058,
"s": 5023,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5079,
"s": 5058,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 5112,
"s": 5079,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5125,
"s": 5112,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 5160,
"s": 5125,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5178,
"s": 5160,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5211,
"s": 5178,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5229,
"s": 5211,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5262,
"s": 5229,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5280,
"s": 5262,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5287,
"s": 5280,
"text": " Print"
},
{
"code": null,
"e": 5298,
"s": 5287,
"text": " Add Notes"
}
] |