title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Upload files in Python
07 Oct, 2021 In this article, we will be looking into the process of file uploading in Python using cgi environment. One often comes across various web applications in which the client or the users is required to upload data in the form of a file(eg. image file, an audio file, text file, etc). There are two aspects to uploading a file, as there are two sides to that particular interaction being client-side and the server-side. A form needs to be created to accept the user input in the form of a file.An HTML form has different attributes that you can set it to, for instance, which URL is the uploaded data is to be submitted is done through the action attribute. An enctype attribute called multi-part/form-data is required in a HTML form to upload a file. Secondly we will be required to use the input tag of HTML and set it equal to “file”. This adds a upload button in addition to an input button in the form. The below code example demonstrates it well: html <html><body> <form enctype = "multipart/form-data" action = "python_script.py" method = "post"> <p>Upload File: <input type = "file" name = "filename" /></p> <p><input type = "submit" value = "Upload" /></p> </form></body></html> The output for the above HTML code would look like below: In the above code, the attribute action has a python script that gets executed when a file is uploaded by the user. On the server end as the python script accepts the uploaded data the field storage object retrieves the submitted name of the file from the form’s “filename”. Now all the server needs to do it is read the file that has been uploaded and write it to the “fileitem”(say, ). At the end of this entire process the uploaded file now will be written to the server.So, the python script looks somewhat like the below code: Python3 import os fileitem = form['filename'] # check if the file has been uploadedif fileitem.filename: # strip the leading path from the file name fn = os.path.basename(fileitem.filename) # open read and write the file into the server open(fn, 'wb').write(fileitem.file.read()) Note: The above python script doesn’t work on every server as every server has its own dependencies to allow running a script in their server for security reasons. For instance if using an Azure server one would need to import msvcrt which is Microsoft visual C++ runtime module to work. anikaseth98 Python-CGI Python Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Oct, 2021" }, { "code": null, "e": 1004, "s": 52, "text": "In this article, we will be looking into the process of file uploading in Python using cgi environment. One often comes across various web applications in which the client or the users is required to upload data in the form of a file(eg. image file, an audio file, text file, etc). There are two aspects to uploading a file, as there are two sides to that particular interaction being client-side and the server-side. A form needs to be created to accept the user input in the form of a file.An HTML form has different attributes that you can set it to, for instance, which URL is the uploaded data is to be submitted is done through the action attribute. An enctype attribute called multi-part/form-data is required in a HTML form to upload a file. Secondly we will be required to use the input tag of HTML and set it equal to “file”. This adds a upload button in addition to an input button in the form. The below code example demonstrates it well: " }, { "code": null, "e": 1009, "s": 1004, "text": "html" }, { "code": "<html><body> <form enctype = \"multipart/form-data\" action = \"python_script.py\" method = \"post\"> <p>Upload File: <input type = \"file\" name = \"filename\" /></p> <p><input type = \"submit\" value = \"Upload\" /></p> </form></body></html>", "e": 1248, "s": 1009, "text": null }, { "code": null, "e": 1308, "s": 1248, "text": "The output for the above HTML code would look like below: " }, { "code": null, "e": 1842, "s": 1308, "text": "In the above code, the attribute action has a python script that gets executed when a file is uploaded by the user. On the server end as the python script accepts the uploaded data the field storage object retrieves the submitted name of the file from the form’s “filename”. Now all the server needs to do it is read the file that has been uploaded and write it to the “fileitem”(say, ). At the end of this entire process the uploaded file now will be written to the server.So, the python script looks somewhat like the below code: " }, { "code": null, "e": 1850, "s": 1842, "text": "Python3" }, { "code": "import os fileitem = form['filename'] # check if the file has been uploadedif fileitem.filename: # strip the leading path from the file name fn = os.path.basename(fileitem.filename) # open read and write the file into the server open(fn, 'wb').write(fileitem.file.read())", "e": 2138, "s": 1850, "text": null }, { "code": null, "e": 2427, "s": 2138, "text": "Note: The above python script doesn’t work on every server as every server has its own dependencies to allow running a script in their server for security reasons. For instance if using an Azure server one would need to import msvcrt which is Microsoft visual C++ runtime module to work. " }, { "code": null, "e": 2439, "s": 2427, "text": "anikaseth98" }, { "code": null, "e": 2450, "s": 2439, "text": "Python-CGI" }, { "code": null, "e": 2457, "s": 2450, "text": "Python" }, { "code": null, "e": 2473, "s": 2457, "text": "Write From Home" } ]
How to create a To-Do list using Drag and Drop in Angular 7 ?
14 May, 2020 We can easily create a To-Do list using Drag-Drop module provided by angular Component Development Kit (CDK). First of all, create an angular component by using the following command- ng g c To-Do Now import CdkDragDrop, moveItemInArray, transferArrayItem from @angular/cdk/drag-drop to our to-Do component, Writing the code for component view:Create two divisions, one for the items that are TO BE DONE and other for items that are COMPLETED.These are some of theparameters: cdkDropList: It lets the division know that it is a drop containercdkDropListData: It binds the data to the viewcdkDropListConnectedTo: It gets the id of another drop container that the current division is connected tocdkDropListDropped: After dragging the items, the data model has to be updated. For that, we can listen to this eventcdkDrag: it specifies that the item can be dragged cdkDropList: It lets the division know that it is a drop container cdkDropListData: It binds the data to the view cdkDropListConnectedTo: It gets the id of another drop container that the current division is connected to cdkDropListDropped: After dragging the items, the data model has to be updated. For that, we can listen to this event cdkDrag: it specifies that the item can be dragged Example: <div><!-- container for both list --> <h1>To do</h1> <!-- To-Do list --> <div cdkDropList #todoList="cdkDropList" [cdkDropListConnectedTo]="[doneList]" [cdkDropListData]="todo" (cdkDropListDropped)="drag($event)"> <div *ngFor="let item of todo" cdkDrag>{{item}}</div> </div></div> <div> <h1>Done</h1> <!-- Done list --> <div cdkDropList #doneList="cdkDropList" [cdkDropListConnectedTo]="[todoList]" [cdkDropListData]="done" class="example-list" (cdkDropListDropped)="drag($event)"> <div *ngFor="let item of done" cdkDrag>{{item}}</div> </div></div> Now write the code for listening the event and adding the data.Here we used a hardcoded list but you can always take input by using ngmodel directive. There aretwo possibilities: Item is dragged to the same container: Use moveItemInArray to move it in the same containerItem is dragged to another container: Use transferArrayItem to move to another container Item is dragged to the same container: Use moveItemInArray to move it in the same container Item is dragged to another container: Use transferArrayItem to move to another container export class To-Do { // hardcoded lists todo = [ 'Go to gym', 'Eat lunch', 'Take a nap', 'Physics syllabus' ]; done = [ 'Assignment', 'Coding practice', 'Maths syllabus', 'English syllabus' ]; //function for listening to the event drag(event: CdkDragDrop<string[]>) { //if movement if within the same container if (event.previousContainer === event.container) { moveItemInArray(event.container.data, event.previousIndex, event.currentIndex); } //if movement if to other containers else { transferArrayItem(event.previousContainer.data, event.container.data, event.previousIndex, event.currentIndex); } }} Output: successful Dragging of ‘Eat lunch’ from To do list to done list. AngularJS-Misc Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n14 May, 2020" }, { "code": null, "e": 164, "s": 54, "text": "We can easily create a To-Do list using Drag-Drop module provided by angular Component Development Kit (CDK)." }, { "code": null, "e": 238, "s": 164, "text": "First of all, create an angular component by using the following command-" }, { "code": null, "e": 253, "s": 238, "text": " ng g c To-Do " }, { "code": null, "e": 364, "s": 253, "text": "Now import CdkDragDrop, moveItemInArray, transferArrayItem from @angular/cdk/drag-drop to our to-Do component," }, { "code": null, "e": 532, "s": 364, "text": "Writing the code for component view:Create two divisions, one for the items that are TO BE DONE and other for items that are COMPLETED.These are some of theparameters:" }, { "code": null, "e": 918, "s": 532, "text": "cdkDropList: It lets the division know that it is a drop containercdkDropListData: It binds the data to the viewcdkDropListConnectedTo: It gets the id of another drop container that the current division is connected tocdkDropListDropped: After dragging the items, the data model has to be updated. For that, we can listen to this eventcdkDrag: it specifies that the item can be dragged" }, { "code": null, "e": 985, "s": 918, "text": "cdkDropList: It lets the division know that it is a drop container" }, { "code": null, "e": 1032, "s": 985, "text": "cdkDropListData: It binds the data to the view" }, { "code": null, "e": 1139, "s": 1032, "text": "cdkDropListConnectedTo: It gets the id of another drop container that the current division is connected to" }, { "code": null, "e": 1257, "s": 1139, "text": "cdkDropListDropped: After dragging the items, the data model has to be updated. For that, we can listen to this event" }, { "code": null, "e": 1308, "s": 1257, "text": "cdkDrag: it specifies that the item can be dragged" }, { "code": null, "e": 1317, "s": 1308, "text": "Example:" }, { "code": "<div><!-- container for both list --> <h1>To do</h1> <!-- To-Do list --> <div cdkDropList #todoList=\"cdkDropList\" [cdkDropListConnectedTo]=\"[doneList]\" [cdkDropListData]=\"todo\" (cdkDropListDropped)=\"drag($event)\"> <div *ngFor=\"let item of todo\" cdkDrag>{{item}}</div> </div></div> <div> <h1>Done</h1> <!-- Done list --> <div cdkDropList #doneList=\"cdkDropList\" [cdkDropListConnectedTo]=\"[todoList]\" [cdkDropListData]=\"done\" class=\"example-list\" (cdkDropListDropped)=\"drag($event)\"> <div *ngFor=\"let item of done\" cdkDrag>{{item}}</div> </div></div>", "e": 1923, "s": 1317, "text": null }, { "code": null, "e": 2102, "s": 1923, "text": "Now write the code for listening the event and adding the data.Here we used a hardcoded list but you can always take input by using ngmodel directive. There aretwo possibilities:" }, { "code": null, "e": 2282, "s": 2102, "text": "Item is dragged to the same container: Use moveItemInArray to move it in the same containerItem is dragged to another container: Use transferArrayItem to move to another container" }, { "code": null, "e": 2374, "s": 2282, "text": "Item is dragged to the same container: Use moveItemInArray to move it in the same container" }, { "code": null, "e": 2463, "s": 2374, "text": "Item is dragged to another container: Use transferArrayItem to move to another container" }, { "code": "export class To-Do { // hardcoded lists todo = [ 'Go to gym', 'Eat lunch', 'Take a nap', 'Physics syllabus' ]; done = [ 'Assignment', 'Coding practice', 'Maths syllabus', 'English syllabus' ]; //function for listening to the event drag(event: CdkDragDrop<string[]>) { //if movement if within the same container if (event.previousContainer === event.container) { moveItemInArray(event.container.data, event.previousIndex, event.currentIndex); } //if movement if to other containers else { transferArrayItem(event.previousContainer.data, event.container.data, event.previousIndex, event.currentIndex); } }}", "e": 3204, "s": 2463, "text": null }, { "code": null, "e": 3277, "s": 3204, "text": "Output: successful Dragging of ‘Eat lunch’ from To do list to done list." }, { "code": null, "e": 3292, "s": 3277, "text": "AngularJS-Misc" }, { "code": null, "e": 3299, "s": 3292, "text": "Picked" }, { "code": null, "e": 3309, "s": 3299, "text": "AngularJS" }, { "code": null, "e": 3326, "s": 3309, "text": "Web Technologies" } ]
Construct a Turing machine for L = {aibjck | i < j < k or i > j > k}
26 Aug, 2021 Prerequisite – Turing MachineThe language L = {aibjck | i < j < k or i > j > k} is same as the union of two languages L1={aibjck | i < j < k } and L2={aibjck | i > j > k }In this language, every string of ‘a’, ‘b’ and ‘c’ have certain number of a’s, then certain number of b’s and then certain number of c’s. Count of 1st symbols should be atleast 1. ‘b’ and ‘c’ can have thereafter be as many but count of a is less than count of ‘b’ and count of ‘b’ is less than count of ‘c’. The count of 3rd symbols should be atleast 1. ‘a’ and ‘b’ can have thereafter be as many but count of c is less than count of ‘b’ and count of ‘b’ is less than count of ‘a’ Assume that string is ending with ‘$’. Input: a a a b b c Here a = 3, b = 2, c = 1 Output: ACCEPTED Input: a b b c c c Here a = 1, b = 2, c = 3 Output: ACCEPTED Input: a a b b c c c Here a = 2, b = 2, c = 3 but |a|>|b|>|c| or |a|<|b|<|c| Output: NOT ACCEPTED Tape Representation: Approach: Comparing two elements by making two element as a single element.After that the elements which are treated as single element are compared again .If |First| is greater than |(Second, Third)| and |Second| greater than |Third|, then it is accepted.If |Third| is greater than |(First, Second)| and |First| greater than |Second|, then it is accepted.Else it is not accepted. Comparing two elements by making two element as a single element. After that the elements which are treated as single element are compared again . If |First| is greater than |(Second, Third)| and |Second| greater than |Third|, then it is accepted. If |Third| is greater than |(First, Second)| and |First| greater than |Second|, then it is accepted. Else it is not accepted. Steps: Step-1: Convert A into X and move right and goto step 2.If Y is found ignore it and move right to step-5. Step-2: Keep ignoring A and Y and move towards right. Convert D into Y and move right and goto step-3. Step-3: Keep ignoring D and Z and move towards right.If C is found make it Z and move left to step 4.If B is found ignore it and move left and goto step-8. Step-4: Keep ignoring Z, A, Y and D and move towards left.If X is found ignore it and move right and goto step-1. Step-5: Keep ignoring Y and move towards right. Ignore Z move left and goto step-11.If D is found make it Y and move right to step-6. Step-6: Keep ignoring D and Z and move towards right.Convert C into Z and move left and goto step-7. Step-7: Keep ignoring D and Z and move towards left.If Y is found ignore it and move right and goto step-5. Step-8: Keep ignoring D, Y and A and move towards left. Ignore X move right and goto step-9. Step-9: Convert A into X and move right and goto step-10. Step-10: Keep ignoring Y and A and move towards right.If B is found ignore it and move left and goto step-11.If D make it Y and move right and goto step-8. Step-11: Stop the Machine (String is accepted) State transition diagram : Here, Q0 shows the initial state and Q1, Q2, Q3, Q4, Q5, Q6, Q8, Q9, Q10 shows the transition state and Q7 and Q11 shows the final state. A, C, D are the variables used and R, L shows right and left. Explanation: Using Q0, when A is found make it X and go to right and to state Q1.And, when Y is found ignore it and go to right and to state Q4 On the state Q1, ignore all A and Y and goto right.If D found make it Y and goto right into next state Q2. In Q2, ignore all D, Z and move right.If B found ignore it, move left and goto the state Q4, If C found make it Z move left and to Q3. In Q3 state, ignore all Z, D, Y, A and move left.If X found ignore it move right to Q0. In Q4, ignore all Y and move right.If Z found ignore it move left to state Q6.If D is found make it Y and move to right to Q5. In Q5 state, ignore all D, Z and move right.If C found make it Z move left to state Q6 In Q6, ignore all D, Z and move left.If Y found ignore it and move right to state Q4. If Q7 state is reached it will produced the result of acceptance of string. In Q8, ignore all A, Y, D and move left.If X found ignore it move right to state Q9. In Q9 state, if A found make it X move right to state Q10 In Q10, ignore all A, Y and move right.If D found make it Y and move right to state Q8.If B is found ignore it and move left to Q11 If Q11 state is reached it will produced the result of acceptance of string. Note: For comparison of |A|, |D|, |C|, the concept of Turing Machine as Comparator is used anikaseth98 GATE CS Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Aug, 2021" }, { "code": null, "e": 337, "s": 28, "text": "Prerequisite – Turing MachineThe language L = {aibjck | i < j < k or i > j > k} is same as the union of two languages L1={aibjck | i < j < k } and L2={aibjck | i > j > k }In this language, every string of ‘a’, ‘b’ and ‘c’ have certain number of a’s, then certain number of b’s and then certain number of c’s." }, { "code": null, "e": 507, "s": 337, "text": "Count of 1st symbols should be atleast 1. ‘b’ and ‘c’ can have thereafter be as many but count of a is less than count of ‘b’ and count of ‘b’ is less than count of ‘c’." }, { "code": null, "e": 680, "s": 507, "text": "The count of 3rd symbols should be atleast 1. ‘a’ and ‘b’ can have thereafter be as many but count of c is less than count of ‘b’ and count of ‘b’ is less than count of ‘a’" }, { "code": null, "e": 719, "s": 680, "text": "Assume that string is ending with ‘$’." }, { "code": null, "e": 976, "s": 719, "text": "Input: a a a b b c \n Here a = 3, b = 2, c = 1\nOutput: ACCEPTED\n \nInput: a b b c c c\n Here a = 1, b = 2, c = 3 \nOutput: ACCEPTED\n\nInput: a a b b c c c\n Here a = 2, b = 2, c = 3 but |a|>|b|>|c| or |a|<|b|<|c|\nOutput: NOT ACCEPTED " }, { "code": null, "e": 997, "s": 976, "text": "Tape Representation:" }, { "code": null, "e": 1007, "s": 997, "text": "Approach:" }, { "code": null, "e": 1377, "s": 1007, "text": "Comparing two elements by making two element as a single element.After that the elements which are treated as single element are compared again .If |First| is greater than |(Second, Third)| and |Second| greater than |Third|, then it is accepted.If |Third| is greater than |(First, Second)| and |First| greater than |Second|, then it is accepted.Else it is not accepted." }, { "code": null, "e": 1443, "s": 1377, "text": "Comparing two elements by making two element as a single element." }, { "code": null, "e": 1524, "s": 1443, "text": "After that the elements which are treated as single element are compared again ." }, { "code": null, "e": 1625, "s": 1524, "text": "If |First| is greater than |(Second, Third)| and |Second| greater than |Third|, then it is accepted." }, { "code": null, "e": 1726, "s": 1625, "text": "If |Third| is greater than |(First, Second)| and |First| greater than |Second|, then it is accepted." }, { "code": null, "e": 1751, "s": 1726, "text": "Else it is not accepted." }, { "code": null, "e": 1758, "s": 1751, "text": "Steps:" }, { "code": null, "e": 1864, "s": 1758, "text": "Step-1: Convert A into X and move right and goto step 2.If Y is found ignore it and move right to step-5." }, { "code": null, "e": 1967, "s": 1864, "text": "Step-2: Keep ignoring A and Y and move towards right. Convert D into Y and move right and goto step-3." }, { "code": null, "e": 2123, "s": 1967, "text": "Step-3: Keep ignoring D and Z and move towards right.If C is found make it Z and move left to step 4.If B is found ignore it and move left and goto step-8." }, { "code": null, "e": 2237, "s": 2123, "text": "Step-4: Keep ignoring Z, A, Y and D and move towards left.If X is found ignore it and move right and goto step-1." }, { "code": null, "e": 2371, "s": 2237, "text": "Step-5: Keep ignoring Y and move towards right. Ignore Z move left and goto step-11.If D is found make it Y and move right to step-6." }, { "code": null, "e": 2472, "s": 2371, "text": "Step-6: Keep ignoring D and Z and move towards right.Convert C into Z and move left and goto step-7." }, { "code": null, "e": 2580, "s": 2472, "text": "Step-7: Keep ignoring D and Z and move towards left.If Y is found ignore it and move right and goto step-5." }, { "code": null, "e": 2673, "s": 2580, "text": "Step-8: Keep ignoring D, Y and A and move towards left. Ignore X move right and goto step-9." }, { "code": null, "e": 2731, "s": 2673, "text": "Step-9: Convert A into X and move right and goto step-10." }, { "code": null, "e": 2887, "s": 2731, "text": "Step-10: Keep ignoring Y and A and move towards right.If B is found ignore it and move left and goto step-11.If D make it Y and move right and goto step-8." }, { "code": null, "e": 2934, "s": 2887, "text": "Step-11: Stop the Machine (String is accepted)" }, { "code": null, "e": 2961, "s": 2934, "text": "State transition diagram :" }, { "code": null, "e": 3161, "s": 2961, "text": "Here, Q0 shows the initial state and Q1, Q2, Q3, Q4, Q5, Q6, Q8, Q9, Q10 shows the transition state and Q7 and Q11 shows the final state. A, C, D are the variables used and R, L shows right and left." }, { "code": null, "e": 3174, "s": 3161, "text": "Explanation:" }, { "code": null, "e": 3305, "s": 3174, "text": "Using Q0, when A is found make it X and go to right and to state Q1.And, when Y is found ignore it and go to right and to state Q4" }, { "code": null, "e": 3412, "s": 3305, "text": "On the state Q1, ignore all A and Y and goto right.If D found make it Y and goto right into next state Q2." }, { "code": null, "e": 3547, "s": 3412, "text": "In Q2, ignore all D, Z and move right.If B found ignore it, move left and goto the state Q4, If C found make it Z move left and to Q3." }, { "code": null, "e": 3635, "s": 3547, "text": "In Q3 state, ignore all Z, D, Y, A and move left.If X found ignore it move right to Q0." }, { "code": null, "e": 3762, "s": 3635, "text": "In Q4, ignore all Y and move right.If Z found ignore it move left to state Q6.If D is found make it Y and move to right to Q5." }, { "code": null, "e": 3849, "s": 3762, "text": "In Q5 state, ignore all D, Z and move right.If C found make it Z move left to state Q6" }, { "code": null, "e": 3935, "s": 3849, "text": "In Q6, ignore all D, Z and move left.If Y found ignore it and move right to state Q4." }, { "code": null, "e": 4011, "s": 3935, "text": "If Q7 state is reached it will produced the result of acceptance of string." }, { "code": null, "e": 4096, "s": 4011, "text": "In Q8, ignore all A, Y, D and move left.If X found ignore it move right to state Q9." }, { "code": null, "e": 4154, "s": 4096, "text": "In Q9 state, if A found make it X move right to state Q10" }, { "code": null, "e": 4286, "s": 4154, "text": "In Q10, ignore all A, Y and move right.If D found make it Y and move right to state Q8.If B is found ignore it and move left to Q11" }, { "code": null, "e": 4363, "s": 4286, "text": "If Q11 state is reached it will produced the result of acceptance of string." }, { "code": null, "e": 4454, "s": 4363, "text": "Note: For comparison of |A|, |D|, |C|, the concept of Turing Machine as Comparator is used" }, { "code": null, "e": 4466, "s": 4454, "text": "anikaseth98" }, { "code": null, "e": 4474, "s": 4466, "text": "GATE CS" }, { "code": null, "e": 4507, "s": 4474, "text": "Theory of Computation & Automata" } ]
Kaprekar Constant
22 Jun, 2022 6174 is the Kaprekar Constant. This number is special as we always get this number when following steps are followed for any four digit number such that all digits of number are not same, i.e., all four digit numbers excluding (0000, 1111, ...) Sort four digits in ascending order and store result in a number “asc”.Sort four digits in descending order and store result in a number “desc”.Subtract number larger number from smaller number, i.e., abs(asc – desc).Repeat above three steps until the result of subtraction doesn’t become equal to the previous number. Sort four digits in ascending order and store result in a number “asc”. Sort four digits in descending order and store result in a number “desc”. Subtract number larger number from smaller number, i.e., abs(asc – desc). Repeat above three steps until the result of subtraction doesn’t become equal to the previous number. We always end up with 6174.Following is the program to demonstrate the same. C++ Java Python3 C# PHP Javascript // C++ program to demonstrate working of// Kaprekar constant#include<bits/stdc++.h>using namespace std; // This function checks validity of kaprekar's// constant. It returns kaprekar's constant for// any four digit number "n" such that all digits// of n are not same.int kaprekarRec(int n, int &prev){ if (n == 0) return 0; // Store current n as previous number prev = n; // Get four digits of given number int digits[4]; for (int i=0; i<4; i++) { digits[i] = n%10; n = n/10; } // Sort all four digits in ascending order // And giet in the form of number "asc" sort(digits, digits+4); int asc = 0; for (int i=0; i<4; i++) asc = asc*10 + digits[i]; // Get all four digits in descending order // in the form of number "desc" sort(digits, digits+4, std::greater<int> ()); int desc = 0; for (int i=0; i<4; i++) desc = desc*10 + digits[i]; // Get the difference of two numbers int diff = abs(asc - desc); // If difference is same as previous, we have // reached kaprekar's constant if (diff == prev) return diff; // Else recur return kaprekarRec(diff, prev);} // A wrapper over kaprekarRec()int kaprekar(int n){ int prev = 0; return kaprekarRec(n, prev);} // Driver codeint main(){ // Trying few four digit numbers, we // always get 6174 cout << kaprekar(1000) << endl; cout << kaprekar(1112) << endl; cout << kaprekar(9812) << endl; return 0;} // Java program to demonstrate working of// Kaprekar constantimport java.util.Arrays; class GFG{// This function checks validity of kaprekar's// constant. It returns kaprekar's constant for// any four digit number "n" such that all digits// of n are not same.static int kaprekarRec(int n, int prev){ if (n == 0) return 0; // Store current n as previous number prev = n; // Get four digits of given number int[] digits=new int[4]; for (int i=0; i<4; i++) { digits[i] = n%10; n = n/10; } // Sort all four digits in ascending order // And giet in the form of number "asc" Arrays.sort(digits); int asc = 0; for (int i=0; i<4; i++) asc = asc*10 + digits[i]; // Get all four digits in descending order // in the form of number "desc" Arrays.sort(digits); int desc = 0; for (int i=3; i>=0; i--) desc = desc*10 + digits[i]; // Get the difference of two numbers int diff = Math.abs(asc - desc); // If difference is same as previous, we have // reached kaprekar's constant if (diff == prev) return diff; // Else recur return kaprekarRec(diff, prev);} // A wrapper over kaprekarRec()static int kaprekar(int n){ int prev = 0; return kaprekarRec(n, prev);} // Driver codepublic static void main(String[] args){ // Trying few four digit numbers, we // always get 6174 System.out.println(kaprekar(1000)); System.out.println(kaprekar(1112)); System.out.println(kaprekar(9812));}}// This code is contributed by mits # Python3 program to demonstrate# working of Kaprekar constant # This function checks validity of# kaprekar's constant. It returns# kaprekar's constant for any four# digit number "n" such that all# digits of n are not same.def kaprekarRec(n, prev): if (n == 0): return 0; # Store current n as previous # number prev = n; # Get four digits of given number digits = [0] * 4; for i in range(4): digits[i] = n % 10; n = int(n / 10); # Sort all four digits in ascending order # And giet in the form of number "asc" digits.sort(); asc = 0; for i in range(4): asc = asc * 10 + digits[i]; # Get all four digits in descending order # in the form of number "desc" digits.sort(); desc = 0; for i in range(3, -1, -1): desc = desc * 10 + digits[i]; # Get the difference of two numbers diff = abs(asc - desc); # If difference is same as previous, # we have reached kaprekar's constant if (diff == prev): return diff; # Else recur return kaprekarRec(diff, prev); # A wrapper over kaprekarRec()def kaprekar(n): rev = 0; return kaprekarRec(n, rev); # Driver code # Trying few four digit numbers, # we always get 6174print(kaprekar(1000));print(kaprekar(1112));print(kaprekar(9812)); # This code is contributed by mits. // C# program to demonstrate working of// Kaprekar constantusing System; class GFG{// This function checks validity of kaprekar's// constant. It returns kaprekar's constant for// any four digit number "n" such that all digits// of n are not same.static int kaprekarRec(int n, int prev){ if (n == 0) return 0; // Store current n as previous number prev = n; // Get four digits of given number int[] digits=new int[4]; for (int i=0; i<4; i++) { digits[i] = n%10; n = n/10; } // Sort all four digits in ascending order // And giet in the form of number "asc" Array.Sort(digits); int asc = 0; for (int i=0; i<4; i++) asc = asc*10 + digits[i]; // Get all four digits in descending order // in the form of number "desc" Array.Sort(digits); int desc = 0; for (int i=3; i>=0; i--) desc = desc*10 + digits[i]; // Get the difference of two numbers int diff = Math.Abs(asc - desc); // If difference is same as previous, we have // reached kaprekar's constant if (diff == prev) return diff; // Else recur return kaprekarRec(diff, prev);} // A wrapper over kaprekarRec()static int kaprekar(int n){ int prev = 0; return kaprekarRec(n, prev);} // Driver codepublic static void Main(){ // Trying few four digit numbers, we // always get 6174 System.Console.WriteLine(kaprekar(1000)); System.Console.WriteLine(kaprekar(1112)); System.Console.WriteLine(kaprekar(9812));}}// This code is contributed by mits <?php// PHP program to demonstrate working of// Kaprekar constant // This function checks validity of kaprekar's// constant. It returns kaprekar's constant// for any four digit number "n" such that// all digits of n are not same.function kaprekarRec($n, $prev){ if ($n == 0) return 0; // Store current n as previous number $prev = $n; // Get four digits of given number $digits = array_fill(0, 4, 0); for ($i = 0; $i < 4; $i++) { $digits[$i] = $n % 10; $n = (int)($n / 10); } // Sort all four digits in ascending order // And giet in the form of number "asc" sort($digits); $asc = 0; for ($i = 0; $i < 4; $i++) $asc = $asc * 10 + $digits[$i]; // Get all four digits in descending order // in the form of number "desc" rsort($digits); $desc = 0; for ($i = 0; $i < 4; $i++) $desc = $desc * 10 + $digits[$i]; // Get the difference of two numbers $diff = abs($asc - $desc); // If difference is same as previous, // we have reached kaprekar's constant if ($diff == $prev) return $diff; // Else recur return kaprekarRec($diff, $prev);} // A wrapper over kaprekarRec()function kaprekar($n){ $rev = 0; return kaprekarRec($n, $rev);} // Driver code // Trying few four digit numbers, we// always get 6174echo kaprekar(1000) . "\n";echo kaprekar(1112) . "\n";echo kaprekar(9812) . "\n"; // This code is contributed by mits.?> <script> // Javascript program to demonstrate working of// Kaprekar constant // This function checks validity of kaprekar's// constant. It returns kaprekar's constant for// any four digit number "n" such that all digits// of n are not same.function kaprekarRec(n , prev){ if (n == 0) return 0; // Store current n as previous number prev = n; // Get four digits of given number var digits= Array.from({length: 4}, (_, i) => 0); for (i=0; i<4; i++) { digits[i] = n%10; n = parseInt(n/10); } // Sort all four digits in ascending order // And giet in the form of number "asc" digits.sort(); var asc = 0; for (i=0; i<4; i++) asc = asc*10 + digits[i]; // Get all four digits in descending order // in the form of number "desc" digits.sort(); var desc = 0; for (i=3; i>=0; i--) desc = desc*10 + digits[i]; // Get the difference of two numbers var diff = Math.abs(asc - desc); // If difference is same as previous, we have // reached kaprekar's constant if (diff == prev) return diff; // Else recur return kaprekarRec(diff, prev);} // A wrapper over kaprekarRec()function kaprekar(n){ var prev = 0; return kaprekarRec(n, prev);} // Driver code //Trying few four digit numbers, we// always get 6174document.write(kaprekar(1000)+"<br>");document.write(kaprekar(1112)+"<br>");document.write(kaprekar(9812)+"<br>"); // This code contributed by Princi Singh </script> Output : 6174 6174 6174 Illustration : n = 2324 1) asc = 2234 2) desc = 4322 3) Difference = 2088 4) Repeating above steps as difference is not same as n n = 2088 1) asc = 0288 2) desc = 8820 3) Difference = 8532 4) Repeating above steps as difference is not same as n. n = 8532 1) asc = 2358 2) desc = 8532 3) Difference = 6174 4) Repeating above steps as difference is not same as n. n = 6174 1) asc = 1467 2) desc = 7641 3) Difference = 6174 Stopping here as difference is same as n. Time Complexity: O(nlogn) where n is the number of digits. Reference: https://en.wikipedia.org/wiki/6174_(number)Related Article: Kaprekar NumberThis article is contributed by Gaurav Saxena. 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 Mithun Kumar princi singh hritikbhatnagar2182 surindertarika1234 kumargaurav97520 Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Jun, 2022" }, { "code": null, "e": 300, "s": 54, "text": "6174 is the Kaprekar Constant. This number is special as we always get this number when following steps are followed for any four digit number such that all digits of number are not same, i.e., all four digit numbers excluding (0000, 1111, ...) " }, { "code": null, "e": 619, "s": 300, "text": "Sort four digits in ascending order and store result in a number “asc”.Sort four digits in descending order and store result in a number “desc”.Subtract number larger number from smaller number, i.e., abs(asc – desc).Repeat above three steps until the result of subtraction doesn’t become equal to the previous number." }, { "code": null, "e": 691, "s": 619, "text": "Sort four digits in ascending order and store result in a number “asc”." }, { "code": null, "e": 765, "s": 691, "text": "Sort four digits in descending order and store result in a number “desc”." }, { "code": null, "e": 839, "s": 765, "text": "Subtract number larger number from smaller number, i.e., abs(asc – desc)." }, { "code": null, "e": 941, "s": 839, "text": "Repeat above three steps until the result of subtraction doesn’t become equal to the previous number." }, { "code": null, "e": 1020, "s": 941, "text": "We always end up with 6174.Following is the program to demonstrate the same. " }, { "code": null, "e": 1024, "s": 1020, "text": "C++" }, { "code": null, "e": 1029, "s": 1024, "text": "Java" }, { "code": null, "e": 1037, "s": 1029, "text": "Python3" }, { "code": null, "e": 1040, "s": 1037, "text": "C#" }, { "code": null, "e": 1044, "s": 1040, "text": "PHP" }, { "code": null, "e": 1055, "s": 1044, "text": "Javascript" }, { "code": "// C++ program to demonstrate working of// Kaprekar constant#include<bits/stdc++.h>using namespace std; // This function checks validity of kaprekar's// constant. It returns kaprekar's constant for// any four digit number \"n\" such that all digits// of n are not same.int kaprekarRec(int n, int &prev){ if (n == 0) return 0; // Store current n as previous number prev = n; // Get four digits of given number int digits[4]; for (int i=0; i<4; i++) { digits[i] = n%10; n = n/10; } // Sort all four digits in ascending order // And giet in the form of number \"asc\" sort(digits, digits+4); int asc = 0; for (int i=0; i<4; i++) asc = asc*10 + digits[i]; // Get all four digits in descending order // in the form of number \"desc\" sort(digits, digits+4, std::greater<int> ()); int desc = 0; for (int i=0; i<4; i++) desc = desc*10 + digits[i]; // Get the difference of two numbers int diff = abs(asc - desc); // If difference is same as previous, we have // reached kaprekar's constant if (diff == prev) return diff; // Else recur return kaprekarRec(diff, prev);} // A wrapper over kaprekarRec()int kaprekar(int n){ int prev = 0; return kaprekarRec(n, prev);} // Driver codeint main(){ // Trying few four digit numbers, we // always get 6174 cout << kaprekar(1000) << endl; cout << kaprekar(1112) << endl; cout << kaprekar(9812) << endl; return 0;}", "e": 2538, "s": 1055, "text": null }, { "code": "// Java program to demonstrate working of// Kaprekar constantimport java.util.Arrays; class GFG{// This function checks validity of kaprekar's// constant. It returns kaprekar's constant for// any four digit number \"n\" such that all digits// of n are not same.static int kaprekarRec(int n, int prev){ if (n == 0) return 0; // Store current n as previous number prev = n; // Get four digits of given number int[] digits=new int[4]; for (int i=0; i<4; i++) { digits[i] = n%10; n = n/10; } // Sort all four digits in ascending order // And giet in the form of number \"asc\" Arrays.sort(digits); int asc = 0; for (int i=0; i<4; i++) asc = asc*10 + digits[i]; // Get all four digits in descending order // in the form of number \"desc\" Arrays.sort(digits); int desc = 0; for (int i=3; i>=0; i--) desc = desc*10 + digits[i]; // Get the difference of two numbers int diff = Math.abs(asc - desc); // If difference is same as previous, we have // reached kaprekar's constant if (diff == prev) return diff; // Else recur return kaprekarRec(diff, prev);} // A wrapper over kaprekarRec()static int kaprekar(int n){ int prev = 0; return kaprekarRec(n, prev);} // Driver codepublic static void main(String[] args){ // Trying few four digit numbers, we // always get 6174 System.out.println(kaprekar(1000)); System.out.println(kaprekar(1112)); System.out.println(kaprekar(9812));}}// This code is contributed by mits", "e": 4062, "s": 2538, "text": null }, { "code": "# Python3 program to demonstrate# working of Kaprekar constant # This function checks validity of# kaprekar's constant. It returns# kaprekar's constant for any four# digit number \"n\" such that all# digits of n are not same.def kaprekarRec(n, prev): if (n == 0): return 0; # Store current n as previous # number prev = n; # Get four digits of given number digits = [0] * 4; for i in range(4): digits[i] = n % 10; n = int(n / 10); # Sort all four digits in ascending order # And giet in the form of number \"asc\" digits.sort(); asc = 0; for i in range(4): asc = asc * 10 + digits[i]; # Get all four digits in descending order # in the form of number \"desc\" digits.sort(); desc = 0; for i in range(3, -1, -1): desc = desc * 10 + digits[i]; # Get the difference of two numbers diff = abs(asc - desc); # If difference is same as previous, # we have reached kaprekar's constant if (diff == prev): return diff; # Else recur return kaprekarRec(diff, prev); # A wrapper over kaprekarRec()def kaprekar(n): rev = 0; return kaprekarRec(n, rev); # Driver code # Trying few four digit numbers, # we always get 6174print(kaprekar(1000));print(kaprekar(1112));print(kaprekar(9812)); # This code is contributed by mits.", "e": 5393, "s": 4062, "text": null }, { "code": "// C# program to demonstrate working of// Kaprekar constantusing System; class GFG{// This function checks validity of kaprekar's// constant. It returns kaprekar's constant for// any four digit number \"n\" such that all digits// of n are not same.static int kaprekarRec(int n, int prev){ if (n == 0) return 0; // Store current n as previous number prev = n; // Get four digits of given number int[] digits=new int[4]; for (int i=0; i<4; i++) { digits[i] = n%10; n = n/10; } // Sort all four digits in ascending order // And giet in the form of number \"asc\" Array.Sort(digits); int asc = 0; for (int i=0; i<4; i++) asc = asc*10 + digits[i]; // Get all four digits in descending order // in the form of number \"desc\" Array.Sort(digits); int desc = 0; for (int i=3; i>=0; i--) desc = desc*10 + digits[i]; // Get the difference of two numbers int diff = Math.Abs(asc - desc); // If difference is same as previous, we have // reached kaprekar's constant if (diff == prev) return diff; // Else recur return kaprekarRec(diff, prev);} // A wrapper over kaprekarRec()static int kaprekar(int n){ int prev = 0; return kaprekarRec(n, prev);} // Driver codepublic static void Main(){ // Trying few four digit numbers, we // always get 6174 System.Console.WriteLine(kaprekar(1000)); System.Console.WriteLine(kaprekar(1112)); System.Console.WriteLine(kaprekar(9812));}}// This code is contributed by mits", "e": 6907, "s": 5393, "text": null }, { "code": "<?php// PHP program to demonstrate working of// Kaprekar constant // This function checks validity of kaprekar's// constant. It returns kaprekar's constant// for any four digit number \"n\" such that// all digits of n are not same.function kaprekarRec($n, $prev){ if ($n == 0) return 0; // Store current n as previous number $prev = $n; // Get four digits of given number $digits = array_fill(0, 4, 0); for ($i = 0; $i < 4; $i++) { $digits[$i] = $n % 10; $n = (int)($n / 10); } // Sort all four digits in ascending order // And giet in the form of number \"asc\" sort($digits); $asc = 0; for ($i = 0; $i < 4; $i++) $asc = $asc * 10 + $digits[$i]; // Get all four digits in descending order // in the form of number \"desc\" rsort($digits); $desc = 0; for ($i = 0; $i < 4; $i++) $desc = $desc * 10 + $digits[$i]; // Get the difference of two numbers $diff = abs($asc - $desc); // If difference is same as previous, // we have reached kaprekar's constant if ($diff == $prev) return $diff; // Else recur return kaprekarRec($diff, $prev);} // A wrapper over kaprekarRec()function kaprekar($n){ $rev = 0; return kaprekarRec($n, $rev);} // Driver code // Trying few four digit numbers, we// always get 6174echo kaprekar(1000) . \"\\n\";echo kaprekar(1112) . \"\\n\";echo kaprekar(9812) . \"\\n\"; // This code is contributed by mits.?>", "e": 8340, "s": 6907, "text": null }, { "code": "<script> // Javascript program to demonstrate working of// Kaprekar constant // This function checks validity of kaprekar's// constant. It returns kaprekar's constant for// any four digit number \"n\" such that all digits// of n are not same.function kaprekarRec(n , prev){ if (n == 0) return 0; // Store current n as previous number prev = n; // Get four digits of given number var digits= Array.from({length: 4}, (_, i) => 0); for (i=0; i<4; i++) { digits[i] = n%10; n = parseInt(n/10); } // Sort all four digits in ascending order // And giet in the form of number \"asc\" digits.sort(); var asc = 0; for (i=0; i<4; i++) asc = asc*10 + digits[i]; // Get all four digits in descending order // in the form of number \"desc\" digits.sort(); var desc = 0; for (i=3; i>=0; i--) desc = desc*10 + digits[i]; // Get the difference of two numbers var diff = Math.abs(asc - desc); // If difference is same as previous, we have // reached kaprekar's constant if (diff == prev) return diff; // Else recur return kaprekarRec(diff, prev);} // A wrapper over kaprekarRec()function kaprekar(n){ var prev = 0; return kaprekarRec(n, prev);} // Driver code //Trying few four digit numbers, we// always get 6174document.write(kaprekar(1000)+\"<br>\");document.write(kaprekar(1112)+\"<br>\");document.write(kaprekar(9812)+\"<br>\"); // This code contributed by Princi Singh </script>", "e": 9806, "s": 8340, "text": null }, { "code": null, "e": 9816, "s": 9806, "text": "Output : " }, { "code": null, "e": 9831, "s": 9816, "text": "6174\n6174\n6174" }, { "code": null, "e": 9848, "s": 9831, "text": "Illustration : " }, { "code": null, "e": 10310, "s": 9848, "text": "n = 2324\n1) asc = 2234\n2) desc = 4322\n3) Difference = 2088 \n4) Repeating above steps as difference is not same\nas n\n\nn = 2088\n1) asc = 0288\n2) desc = 8820\n3) Difference = 8532 \n4) Repeating above steps as difference is not same\nas n.\n\nn = 8532\n1) asc = 2358\n2) desc = 8532\n3) Difference = 6174 \n4) Repeating above steps as difference is not same\nas n.\n\nn = 6174\n1) asc = 1467\n2) desc = 7641\n3) Difference = 6174 \nStopping here as difference is same as n." }, { "code": null, "e": 10369, "s": 10310, "text": "Time Complexity: O(nlogn) where n is the number of digits." }, { "code": null, "e": 10876, "s": 10369, "text": "Reference: https://en.wikipedia.org/wiki/6174_(number)Related Article: Kaprekar NumberThis article is contributed by Gaurav Saxena. 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": 10889, "s": 10876, "text": "Mithun Kumar" }, { "code": null, "e": 10902, "s": 10889, "text": "princi singh" }, { "code": null, "e": 10922, "s": 10902, "text": "hritikbhatnagar2182" }, { "code": null, "e": 10941, "s": 10922, "text": "surindertarika1234" }, { "code": null, "e": 10958, "s": 10941, "text": "kumargaurav97520" }, { "code": null, "e": 10971, "s": 10958, "text": "Mathematical" }, { "code": null, "e": 10984, "s": 10971, "text": "Mathematical" } ]
Python – Subset DataFrame by Column Name
16 Mar, 2021 Using Pandas library, we can perform multiple operations on a DataFrame. We can even create and access the subset of a DataFrame in multiple formats. The task here is to create a subset DataFrame by column name. We can choose different methods to perform this task. Here are possible methods mentioned below – Before performing any action, we need to write few lines of code to import necessary libraries and create a DataFrame. Creating the DataFrame Python3 #import pandasimport pandas as pd # create dataframedata = {'Name': ['John', 'Emily', 'Lara', 'Lucas', 'Katy', 'Jordan'], 'Gender': [30, 27, 21, 21, 16, 20], 'Branch': ['Arts', 'Arts', 'Commerce', 'Science', 'Science', 'Science'], 'pre_1': [9, 9, 10, 7, 6, 9], 'pre_2': [8, 7, 10, 6, 8, 8]} df = pd.DataFrame(data)df Output: Method 1: Using Python iloc() function This function allows us to create a subset by choosing specific values from columns based on indexes. Syntax: df_name.iloc[beg_index:end_index+1,beg_index:end_index+1] Example: Create a subset with Name, Gender and Branch column Python3 # create a subset of all rows# and Name, Gender and Branch columndf.iloc[:, 0:3] Output : Method 2: Using Indexing Operator We can use the indexing operator i.e. square brackets to create a subset dataframe Example: Create a subset with Name, pre_1, and pre_2 column Python3 # creating subset dataframe using # indexing operatordf[['Name', 'pre_1', 'pre_2']] Output – Method 3: Using filter() method with like keyword We can use this method particularly when we have to create a subset dataframe with columns having similarly patterned names. Example: Create a subset with pre_1 and pre_2 column Python3 # create a subset of columns pre_1 and pre_2# using filter() methoddf.filter(like='pre') Output: Picked Python pandas-dataFrame Python Pandas-exercise Python-pandas 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 Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Mar, 2021" }, { "code": null, "e": 338, "s": 28, "text": "Using Pandas library, we can perform multiple operations on a DataFrame. We can even create and access the subset of a DataFrame in multiple formats. The task here is to create a subset DataFrame by column name. We can choose different methods to perform this task. Here are possible methods mentioned below –" }, { "code": null, "e": 457, "s": 338, "text": "Before performing any action, we need to write few lines of code to import necessary libraries and create a DataFrame." }, { "code": null, "e": 480, "s": 457, "text": "Creating the DataFrame" }, { "code": null, "e": 488, "s": 480, "text": "Python3" }, { "code": "#import pandasimport pandas as pd # create dataframedata = {'Name': ['John', 'Emily', 'Lara', 'Lucas', 'Katy', 'Jordan'], 'Gender': [30, 27, 21, 21, 16, 20], 'Branch': ['Arts', 'Arts', 'Commerce', 'Science', 'Science', 'Science'], 'pre_1': [9, 9, 10, 7, 6, 9], 'pre_2': [8, 7, 10, 6, 8, 8]} df = pd.DataFrame(data)df", "e": 856, "s": 488, "text": null }, { "code": null, "e": 864, "s": 856, "text": "Output:" }, { "code": null, "e": 904, "s": 864, "text": "Method 1: Using Python iloc() function " }, { "code": null, "e": 1007, "s": 904, "text": "This function allows us to create a subset by choosing specific values from columns based on indexes. " }, { "code": null, "e": 1015, "s": 1007, "text": "Syntax:" }, { "code": null, "e": 1073, "s": 1015, "text": "df_name.iloc[beg_index:end_index+1,beg_index:end_index+1]" }, { "code": null, "e": 1134, "s": 1073, "text": "Example: Create a subset with Name, Gender and Branch column" }, { "code": null, "e": 1142, "s": 1134, "text": "Python3" }, { "code": "# create a subset of all rows# and Name, Gender and Branch columndf.iloc[:, 0:3]", "e": 1223, "s": 1142, "text": null }, { "code": null, "e": 1232, "s": 1223, "text": "Output :" }, { "code": null, "e": 1266, "s": 1232, "text": "Method 2: Using Indexing Operator" }, { "code": null, "e": 1350, "s": 1266, "text": "We can use the indexing operator i.e. square brackets to create a subset dataframe " }, { "code": null, "e": 1410, "s": 1350, "text": "Example: Create a subset with Name, pre_1, and pre_2 column" }, { "code": null, "e": 1418, "s": 1410, "text": "Python3" }, { "code": "# creating subset dataframe using # indexing operatordf[['Name', 'pre_1', 'pre_2']]", "e": 1502, "s": 1418, "text": null }, { "code": null, "e": 1512, "s": 1502, "text": "Output – " }, { "code": null, "e": 1562, "s": 1512, "text": "Method 3: Using filter() method with like keyword" }, { "code": null, "e": 1687, "s": 1562, "text": "We can use this method particularly when we have to create a subset dataframe with columns having similarly patterned names." }, { "code": null, "e": 1740, "s": 1687, "text": "Example: Create a subset with pre_1 and pre_2 column" }, { "code": null, "e": 1748, "s": 1740, "text": "Python3" }, { "code": "# create a subset of columns pre_1 and pre_2# using filter() methoddf.filter(like='pre')", "e": 1837, "s": 1748, "text": null }, { "code": null, "e": 1845, "s": 1837, "text": "Output:" }, { "code": null, "e": 1852, "s": 1845, "text": "Picked" }, { "code": null, "e": 1876, "s": 1852, "text": "Python pandas-dataFrame" }, { "code": null, "e": 1899, "s": 1876, "text": "Python Pandas-exercise" }, { "code": null, "e": 1913, "s": 1899, "text": "Python-pandas" }, { "code": null, "e": 1920, "s": 1913, "text": "Python" }, { "code": null, "e": 2018, "s": 1920, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2050, "s": 2018, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2077, "s": 2050, "text": "Python Classes and Objects" }, { "code": null, "e": 2098, "s": 2077, "text": "Python OOPs Concepts" }, { "code": null, "e": 2121, "s": 2098, "text": "Introduction To PYTHON" }, { "code": null, "e": 2152, "s": 2121, "text": "Python | os.path.join() method" }, { "code": null, "e": 2208, "s": 2152, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2250, "s": 2208, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2292, "s": 2250, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2331, "s": 2292, "text": "Python | Get unique values from a list" } ]
Count of Triplets
22 Jun, 2021 Given N points in a plane in the form of 2D array such that every row consist of two integer L and R where L belongs to x-ordinate and R belongs to y-ordinate. The task is to count the triplets of points(say a, b & c) such that distance between a & b is equals to the distance between a & c. Note: The order of triplets matters. Examples: Input: arr[] = { { 0, 0 }, { 1, 0 }, { 2, 0 } } Output: 2 Explanation: The possible triplets are: {{1, 0}, {0, 0}, {2, 0}} and {{1, 0}, {2, 0}, {0, 0}} Input: arr[] = { {1, 0}, {1, -1}, {2, 3}, {4, 3}, {4, 4} } Output: 0 Explanation: There is no such triplets exists. Approach: For each point calculate it’s distance to every other points.Store intermediate distances(say d) for point to other points in a Map.If Map has already same distance then count of triplets is twice the value stored for d in Map.Update the count of current distance in the Map. For each point calculate it’s distance to every other points. Store intermediate distances(say d) for point to other points in a Map. If Map has already same distance then count of triplets is twice the value stored for d in Map. Update the count of current distance in the Map. Below is the implementation of the above: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count the tripletsint countTriplets(vector<vector<int> >& p){ // Initialise count int count = 0; // Traverse the arr[] for (int i = 0; i < p.size(); i++) { // Map to store the distance between // every pairs p[i] and p[j] unordered_map<int, int> d; for (int j = 0; j < p.size(); j++) { // Find the distance int dist = pow(p[j][1] - p[i][1], 2) + pow(p[j][0] - p[i][0], 2); // If count of distance is greater // than 0, then find the count if (d[dist] > 0) { count += 2 * d[dist]; } // Update the current count of the // distance d[dist]++; } } // Return the count of triplets return count;} // Driver Codeint main(){ // Set of points in plane vector<vector<int> > arr = { { 0, 0 }, { 1, 0 }, { 2, 0 } }; // Function call cout << countTriplets(arr); return 0;} // Java program for the above approachimport java.util.*;class GFG{ // Function to count the triplets static int countTriplets(int p[][]) { // Initialise count int count = 0; // Traverse the arr[] for (int i = 0; i < p.length; i++) { // Map to store the distance between // every pairs p[i] and p[j] HashMap<Integer, Integer> d = new HashMap<Integer,Integer>(); for (int j = 0; j < p.length; j++) { // Find the distance int dist = (int)(Math.pow(p[j][1] - p[i][1], 2)+ Math.pow(p[j][0] - p[i][0], 2)); // If count of distance is greater // than 0, then find the count if (d.containsKey(dist) && d.get(dist) > 0) { count += 2 * d.get(dist); } // Update the current count of the // distance if (d.containsKey(dist)){ d.put(dist,d.get(dist)+1); } else d.put(dist,1); } } // Return the count of triplets return count; } // Driver Code public static void main(String args[]) { // Set of points in plane int arr[][] = { { 0, 0 }, { 1, 0 }, { 2, 0 } }; // Function call System.out.println(countTriplets(arr)); }} // This code is contributed by AbhiThakur # Python3 program for the above approach # Function to count the tripletsdef countTriplets(p) : # Initialise count count = 0; # Traverse the arr[] for i in range(len(p)) : # Map to store the distance between # every pairs p[i] and p[j] d = {}; for j in range(len(p)) : # Find the distance dist = pow(p[j][1] - p[i][1], 2) + \ pow(p[j][0] - p[i][0], 2); if dist not in d : d[dist] = 0; # If count of distance is greater # than 0, then find the count if (d[dist] > 0) : count += 2 * d[dist]; # Update the current count of the # distance d[dist] += 1; # Return the count of triplets return count; # Driver Codeif __name__ == "__main__" : # Set of points in plane arr = [ [ 0, 0 ], [ 1, 0 ], [ 2, 0 ] ]; # Function call print(countTriplets(arr)); # This code is contributed by Yash_R // C# program for the above approach using System;using System.Collections.Generic; class GFG{ // Function to count the tripletsstatic int countTriplets(int[,] p){ // Initialise count int count = 0; // Traverse the arr[] for(int i = 0; i < p.GetLength(0); i++) { // Map to store the distance between // every pairs p[i] and p[j] Dictionary<int, int> d = new Dictionary<int, int>(); for(int j = 0; j < p.GetLength(0); j++) { // Find the distance int dist = (int)(Math.Pow(p[j, 1] - p[i, 1], 2) + Math.Pow(p[j, 0] - p[i, 0], 2)); // If count of distance is greater // than 0, then find the count if (d.ContainsKey(dist) && d[dist] > 0) { count += 2 * d[dist]; } // Update the current count of the // distance if (d.ContainsKey(dist)) { d[dist]++; } else d.Add(dist, 1); } } // Return the count of triplets return count;} // Driver codestatic void Main(){ // Set of points in plane int[,] arr = new int [3, 2]{ { 0, 0 }, { 1, 0 }, { 2, 0 } }; // Function call Console.WriteLine(countTriplets(arr));}} // This code is contributed by divyeshrabadiya07 <script> // Javascript program for the above approach // Function to count the triplets function countTriplets(p) { // Let initialise count let count = 0; // Traverse the arr[] for (let i = 0; i < p.length; i++) { // Map to store the distance between // every pairs p[i] and p[j] let d = new Map(); for (let j = 0; j < p.length; j++) { // Find the distance let dist = (Math.pow(p[j][1] - p[i][1], 2)+ Math.pow(p[j][0] - p[i][0], 2)); // If count of distance is greater // than 0, then find the count if (d.has(dist) && d.get(dist) > 0) { count += 2 * d.get(dist); } // Update the current count of the // distance if (d.has(dist)){ d.set(dist,d.get(dist)+1); } else d.set(dist,1); } } // Return the count of triplets return count; } // Driver code // Set of polets in plane let arr = [[ 0, 0 ], [ 1, 0 ], [ 2, 0 ]]; // Function call document.write(countTriplets(arr)); </script> 2 Yash_R abhaysingh290895 divyeshrabadiya07 splevel62 anikaseth98 Hash Write From Home Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Hashing | A Complete Tutorial Find k numbers with most occurrences in the given array Real-time application of Data Structures Non-Repeating Element Find the length of largest subarray with 0 sum Convert integer to string in Python Convert string to integer in Python How to set input type date in dd-mm-yyyy format using HTML ? Python infinity Similarities and Difference between Java and C++
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jun, 2021" }, { "code": null, "e": 381, "s": 52, "text": "Given N points in a plane in the form of 2D array such that every row consist of two integer L and R where L belongs to x-ordinate and R belongs to y-ordinate. The task is to count the triplets of points(say a, b & c) such that distance between a & b is equals to the distance between a & c. Note: The order of triplets matters." }, { "code": null, "e": 393, "s": 381, "text": "Examples: " }, { "code": null, "e": 545, "s": 393, "text": "Input: arr[] = { { 0, 0 }, { 1, 0 }, { 2, 0 } } Output: 2 Explanation: The possible triplets are: {{1, 0}, {0, 0}, {2, 0}} and {{1, 0}, {2, 0}, {0, 0}}" }, { "code": null, "e": 661, "s": 545, "text": "Input: arr[] = { {1, 0}, {1, -1}, {2, 3}, {4, 3}, {4, 4} } Output: 0 Explanation: There is no such triplets exists." }, { "code": null, "e": 672, "s": 661, "text": "Approach: " }, { "code": null, "e": 948, "s": 672, "text": "For each point calculate it’s distance to every other points.Store intermediate distances(say d) for point to other points in a Map.If Map has already same distance then count of triplets is twice the value stored for d in Map.Update the count of current distance in the Map." }, { "code": null, "e": 1010, "s": 948, "text": "For each point calculate it’s distance to every other points." }, { "code": null, "e": 1082, "s": 1010, "text": "Store intermediate distances(say d) for point to other points in a Map." }, { "code": null, "e": 1178, "s": 1082, "text": "If Map has already same distance then count of triplets is twice the value stored for d in Map." }, { "code": null, "e": 1227, "s": 1178, "text": "Update the count of current distance in the Map." }, { "code": null, "e": 1270, "s": 1227, "text": "Below is the implementation of the above: " }, { "code": null, "e": 1274, "s": 1270, "text": "C++" }, { "code": null, "e": 1279, "s": 1274, "text": "Java" }, { "code": null, "e": 1287, "s": 1279, "text": "Python3" }, { "code": null, "e": 1290, "s": 1287, "text": "C#" }, { "code": null, "e": 1301, "s": 1290, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count the tripletsint countTriplets(vector<vector<int> >& p){ // Initialise count int count = 0; // Traverse the arr[] for (int i = 0; i < p.size(); i++) { // Map to store the distance between // every pairs p[i] and p[j] unordered_map<int, int> d; for (int j = 0; j < p.size(); j++) { // Find the distance int dist = pow(p[j][1] - p[i][1], 2) + pow(p[j][0] - p[i][0], 2); // If count of distance is greater // than 0, then find the count if (d[dist] > 0) { count += 2 * d[dist]; } // Update the current count of the // distance d[dist]++; } } // Return the count of triplets return count;} // Driver Codeint main(){ // Set of points in plane vector<vector<int> > arr = { { 0, 0 }, { 1, 0 }, { 2, 0 } }; // Function call cout << countTriplets(arr); return 0;}", "e": 2439, "s": 1301, "text": null }, { "code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to count the triplets static int countTriplets(int p[][]) { // Initialise count int count = 0; // Traverse the arr[] for (int i = 0; i < p.length; i++) { // Map to store the distance between // every pairs p[i] and p[j] HashMap<Integer, Integer> d = new HashMap<Integer,Integer>(); for (int j = 0; j < p.length; j++) { // Find the distance int dist = (int)(Math.pow(p[j][1] - p[i][1], 2)+ Math.pow(p[j][0] - p[i][0], 2)); // If count of distance is greater // than 0, then find the count if (d.containsKey(dist) && d.get(dist) > 0) { count += 2 * d.get(dist); } // Update the current count of the // distance if (d.containsKey(dist)){ d.put(dist,d.get(dist)+1); } else d.put(dist,1); } } // Return the count of triplets return count; } // Driver Code public static void main(String args[]) { // Set of points in plane int arr[][] = { { 0, 0 }, { 1, 0 }, { 2, 0 } }; // Function call System.out.println(countTriplets(arr)); }} // This code is contributed by AbhiThakur", "e": 4017, "s": 2439, "text": null }, { "code": "# Python3 program for the above approach # Function to count the tripletsdef countTriplets(p) : # Initialise count count = 0; # Traverse the arr[] for i in range(len(p)) : # Map to store the distance between # every pairs p[i] and p[j] d = {}; for j in range(len(p)) : # Find the distance dist = pow(p[j][1] - p[i][1], 2) + \\ pow(p[j][0] - p[i][0], 2); if dist not in d : d[dist] = 0; # If count of distance is greater # than 0, then find the count if (d[dist] > 0) : count += 2 * d[dist]; # Update the current count of the # distance d[dist] += 1; # Return the count of triplets return count; # Driver Codeif __name__ == \"__main__\" : # Set of points in plane arr = [ [ 0, 0 ], [ 1, 0 ], [ 2, 0 ] ]; # Function call print(countTriplets(arr)); # This code is contributed by Yash_R", "e": 5073, "s": 4017, "text": null }, { "code": "// C# program for the above approach using System;using System.Collections.Generic; class GFG{ // Function to count the tripletsstatic int countTriplets(int[,] p){ // Initialise count int count = 0; // Traverse the arr[] for(int i = 0; i < p.GetLength(0); i++) { // Map to store the distance between // every pairs p[i] and p[j] Dictionary<int, int> d = new Dictionary<int, int>(); for(int j = 0; j < p.GetLength(0); j++) { // Find the distance int dist = (int)(Math.Pow(p[j, 1] - p[i, 1], 2) + Math.Pow(p[j, 0] - p[i, 0], 2)); // If count of distance is greater // than 0, then find the count if (d.ContainsKey(dist) && d[dist] > 0) { count += 2 * d[dist]; } // Update the current count of the // distance if (d.ContainsKey(dist)) { d[dist]++; } else d.Add(dist, 1); } } // Return the count of triplets return count;} // Driver codestatic void Main(){ // Set of points in plane int[,] arr = new int [3, 2]{ { 0, 0 }, { 1, 0 }, { 2, 0 } }; // Function call Console.WriteLine(countTriplets(arr));}} // This code is contributed by divyeshrabadiya07", "e": 6666, "s": 5073, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to count the triplets function countTriplets(p) { // Let initialise count let count = 0; // Traverse the arr[] for (let i = 0; i < p.length; i++) { // Map to store the distance between // every pairs p[i] and p[j] let d = new Map(); for (let j = 0; j < p.length; j++) { // Find the distance let dist = (Math.pow(p[j][1] - p[i][1], 2)+ Math.pow(p[j][0] - p[i][0], 2)); // If count of distance is greater // than 0, then find the count if (d.has(dist) && d.get(dist) > 0) { count += 2 * d.get(dist); } // Update the current count of the // distance if (d.has(dist)){ d.set(dist,d.get(dist)+1); } else d.set(dist,1); } } // Return the count of triplets return count; } // Driver code // Set of polets in plane let arr = [[ 0, 0 ], [ 1, 0 ], [ 2, 0 ]]; // Function call document.write(countTriplets(arr)); </script>", "e": 8113, "s": 6666, "text": null }, { "code": null, "e": 8115, "s": 8113, "text": "2" }, { "code": null, "e": 8124, "s": 8117, "text": "Yash_R" }, { "code": null, "e": 8141, "s": 8124, "text": "abhaysingh290895" }, { "code": null, "e": 8159, "s": 8141, "text": "divyeshrabadiya07" }, { "code": null, "e": 8169, "s": 8159, "text": "splevel62" }, { "code": null, "e": 8181, "s": 8169, "text": "anikaseth98" }, { "code": null, "e": 8186, "s": 8181, "text": "Hash" }, { "code": null, "e": 8202, "s": 8186, "text": "Write From Home" }, { "code": null, "e": 8207, "s": 8202, "text": "Hash" }, { "code": null, "e": 8305, "s": 8207, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8343, "s": 8305, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 8399, "s": 8343, "text": "Find k numbers with most occurrences in the given array" }, { "code": null, "e": 8440, "s": 8399, "text": "Real-time application of Data Structures" }, { "code": null, "e": 8462, "s": 8440, "text": "Non-Repeating Element" }, { "code": null, "e": 8509, "s": 8462, "text": "Find the length of largest subarray with 0 sum" }, { "code": null, "e": 8545, "s": 8509, "text": "Convert integer to string in Python" }, { "code": null, "e": 8581, "s": 8545, "text": "Convert string to integer in Python" }, { "code": null, "e": 8642, "s": 8581, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 8658, "s": 8642, "text": "Python infinity" } ]
Juspay Interview Experience for Internship | On-Campus 2020
21 Feb, 2022 Juspay is one of the largest firms in India in terms of providing Mobile payment solutions. Juspay visited our campus for hiring for an Internship. They have shortlisted around 600 students to give an online Coding Test at the Talscale Platform. Interview Round consists of 3 rounds on-campus and 2 rounds + 1 hackathon at their Juspay office-Bangalore. On-campus Rounds Round 1 (Coding Test): 3 Graph-based question Given the graph consist of pair and weight attached to it. Print out the node having the maximum number of inorder weights. (Node having maximum sum weight ).Given the graph, Print out the maximum weight Cycle of the graph. ( Cycle which has maximum sum weight ).Given the 2 nodes. Print the shortest path between them. ( Return the array containing the path). Given the graph consist of pair and weight attached to it. Print out the node having the maximum number of inorder weights. (Node having maximum sum weight ). Given the graph, Print out the maximum weight Cycle of the graph. ( Cycle which has maximum sum weight ). Given the 2 nodes. Print the shortest path between them. ( Return the array containing the path). I was able to solve 1 complete and 1 partial Around 23 students moving to the next round. Round 2 (Technical Interview): All student is given 2 coding questions and those who solved it are only able to give an interview. Write a Program to parse the JSON format file.Write a Program for basic Linux commands like – mkdir, cd, pwd, cp. Write a Program to parse the JSON format file. Write a Program for basic Linux commands like – mkdir, cd, pwd, cp. I was able to write a Program and given the Interview No Introduction or anything directly he started with Coding questions Check the given binary tree is BST or not – solved in 5 minutes, given a recursive approach O(n) solution Check the given binary tree is BST or not – solved in 5 minutes, given a recursive approach O(n) solution Seem to be Impressed, He started asking a question about machine learning as it is my minor What is Bayes theorem, write its formula and its application?What are the Naive Bayes Classifier and its importance? What is Bayes theorem, write its formula and its application? What are the Naive Bayes Classifier and its importance? Few questions from Operating questions like TCP belongs to which OSI Layer?Difference Between Thread and Process? TCP belongs to which OSI Layer? Difference Between Thread and Process? I was a Little nervous and giving answers taking breaks then He asks me to wait outside for the result. After they took a few more interviews for a student and selected 2 Students for the next round. Round 3 (Technical Interview): Only 1 coding question Given a K sorted array, Merge them in a sorted single 1d array in the least complexity Given a K sorted array, Merge them in a sorted single 1d array in the least complexity I solved it and was selected for the Final Interview at Juspay Office Bangalore with 1 other. They have taken care of our flight tickets and hotel rooms. Juspay Office – 1 Day Hackathon and 2 interviews round Hackathon: In the Hackathon, We have to make a Rotating Cube using Typescript as per given some conditions on angle and axis. I never heard this language before and didn’t know even how to declare a variable, Somehow they are given time to learn and code. I manage to take a reference from online resources and make a cube but it’s not rotating at all. Round 1: Technical Interview – Taken by senior Developer Theory Question is from Linked List, Arrays, String and Graphs and few questions on my projects and last about 2 hours Final Round – Taken by CEO of Juspay He asked questions from the N-ary tree Locking and Unlocking of Resources arranged in the form of n-ary Tree: https://www.geeksforgeeks.org/locking-and-unlocking-of-resources-in-the-form-of-n-ary-tree/ My Complexity isLock() O(1) Lock() O(N) unLock() O(1) I was not able to solve in the given Time limit which is O(Logn) for all operations. Hence, he rejected me. There was one more round of HR but not for me. Result: Rejected Although I enjoyed the whole interview process and get to learn so much from it and also a free trip to Bangalore. I would like to thank GeeksforGeeks. Initially, I practiced the topic wise, later when I was confident enough I started practicing company-wise. Also, I made it a habit to read at least one interview experience from gfg daily. Juspay Marketing On-Campus Internship Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Feb, 2022" }, { "code": null, "e": 298, "s": 52, "text": "Juspay is one of the largest firms in India in terms of providing Mobile payment solutions. Juspay visited our campus for hiring for an Internship. They have shortlisted around 600 students to give an online Coding Test at the Talscale Platform." }, { "code": null, "e": 406, "s": 298, "text": "Interview Round consists of 3 rounds on-campus and 2 rounds + 1 hackathon at their Juspay office-Bangalore." }, { "code": null, "e": 423, "s": 406, "text": "On-campus Rounds" }, { "code": null, "e": 469, "s": 423, "text": "Round 1 (Coding Test): 3 Graph-based question" }, { "code": null, "e": 830, "s": 469, "text": "Given the graph consist of pair and weight attached to it. Print out the node having the maximum number of inorder weights. (Node having maximum sum weight ).Given the graph, Print out the maximum weight Cycle of the graph. ( Cycle which has maximum sum weight ).Given the 2 nodes. Print the shortest path between them. ( Return the array containing the path)." }, { "code": null, "e": 989, "s": 830, "text": "Given the graph consist of pair and weight attached to it. Print out the node having the maximum number of inorder weights. (Node having maximum sum weight )." }, { "code": null, "e": 1095, "s": 989, "text": "Given the graph, Print out the maximum weight Cycle of the graph. ( Cycle which has maximum sum weight )." }, { "code": null, "e": 1193, "s": 1095, "text": "Given the 2 nodes. Print the shortest path between them. ( Return the array containing the path)." }, { "code": null, "e": 1239, "s": 1193, "text": "I was able to solve 1 complete and 1 partial " }, { "code": null, "e": 1284, "s": 1239, "text": "Around 23 students moving to the next round." }, { "code": null, "e": 1415, "s": 1284, "text": "Round 2 (Technical Interview): All student is given 2 coding questions and those who solved it are only able to give an interview." }, { "code": null, "e": 1529, "s": 1415, "text": "Write a Program to parse the JSON format file.Write a Program for basic Linux commands like – mkdir, cd, pwd, cp." }, { "code": null, "e": 1576, "s": 1529, "text": "Write a Program to parse the JSON format file." }, { "code": null, "e": 1644, "s": 1576, "text": "Write a Program for basic Linux commands like – mkdir, cd, pwd, cp." }, { "code": null, "e": 1698, "s": 1644, "text": "I was able to write a Program and given the Interview" }, { "code": null, "e": 1768, "s": 1698, "text": "No Introduction or anything directly he started with Coding questions" }, { "code": null, "e": 1874, "s": 1768, "text": "Check the given binary tree is BST or not – solved in 5 minutes, given a recursive approach O(n) solution" }, { "code": null, "e": 1980, "s": 1874, "text": "Check the given binary tree is BST or not – solved in 5 minutes, given a recursive approach O(n) solution" }, { "code": null, "e": 2072, "s": 1980, "text": "Seem to be Impressed, He started asking a question about machine learning as it is my minor" }, { "code": null, "e": 2189, "s": 2072, "text": "What is Bayes theorem, write its formula and its application?What are the Naive Bayes Classifier and its importance?" }, { "code": null, "e": 2251, "s": 2189, "text": "What is Bayes theorem, write its formula and its application?" }, { "code": null, "e": 2307, "s": 2251, "text": "What are the Naive Bayes Classifier and its importance?" }, { "code": null, "e": 2351, "s": 2307, "text": "Few questions from Operating questions like" }, { "code": null, "e": 2421, "s": 2351, "text": "TCP belongs to which OSI Layer?Difference Between Thread and Process?" }, { "code": null, "e": 2453, "s": 2421, "text": "TCP belongs to which OSI Layer?" }, { "code": null, "e": 2492, "s": 2453, "text": "Difference Between Thread and Process?" }, { "code": null, "e": 2596, "s": 2492, "text": "I was a Little nervous and giving answers taking breaks then He asks me to wait outside for the result." }, { "code": null, "e": 2692, "s": 2596, "text": "After they took a few more interviews for a student and selected 2 Students for the next round." }, { "code": null, "e": 2746, "s": 2692, "text": "Round 3 (Technical Interview): Only 1 coding question" }, { "code": null, "e": 2833, "s": 2746, "text": "Given a K sorted array, Merge them in a sorted single 1d array in the least complexity" }, { "code": null, "e": 2920, "s": 2833, "text": "Given a K sorted array, Merge them in a sorted single 1d array in the least complexity" }, { "code": null, "e": 3074, "s": 2920, "text": "I solved it and was selected for the Final Interview at Juspay Office Bangalore with 1 other. They have taken care of our flight tickets and hotel rooms." }, { "code": null, "e": 3129, "s": 3074, "text": "Juspay Office – 1 Day Hackathon and 2 interviews round" }, { "code": null, "e": 3255, "s": 3129, "text": "Hackathon: In the Hackathon, We have to make a Rotating Cube using Typescript as per given some conditions on angle and axis." }, { "code": null, "e": 3483, "s": 3255, "text": "I never heard this language before and didn’t know even how to declare a variable, Somehow they are given time to learn and code. I manage to take a reference from online resources and make a cube but it’s not rotating at all. " }, { "code": null, "e": 3540, "s": 3483, "text": "Round 1: Technical Interview – Taken by senior Developer" }, { "code": null, "e": 3659, "s": 3540, "text": "Theory Question is from Linked List, Arrays, String and Graphs and few questions on my projects and last about 2 hours" }, { "code": null, "e": 3696, "s": 3659, "text": "Final Round – Taken by CEO of Juspay" }, { "code": null, "e": 3735, "s": 3696, "text": "He asked questions from the N-ary tree" }, { "code": null, "e": 3899, "s": 3735, "text": "Locking and Unlocking of Resources arranged in the form of n-ary Tree: https://www.geeksforgeeks.org/locking-and-unlocking-of-resources-in-the-form-of-n-ary-tree/ " }, { "code": null, "e": 3959, "s": 3899, "text": "My Complexity\nisLock() O(1) \nLock() O(N)\nunLock() O(1)" }, { "code": null, "e": 4067, "s": 3959, "text": "I was not able to solve in the given Time limit which is O(Logn) for all operations. Hence, he rejected me." }, { "code": null, "e": 4114, "s": 4067, "text": "There was one more round of HR but not for me." }, { "code": null, "e": 4131, "s": 4114, "text": "Result: Rejected" }, { "code": null, "e": 4246, "s": 4131, "text": "Although I enjoyed the whole interview process and get to learn so much from it and also a free trip to Bangalore." }, { "code": null, "e": 4473, "s": 4246, "text": "I would like to thank GeeksforGeeks. Initially, I practiced the topic wise, later when I was confident enough I started practicing company-wise. Also, I made it a habit to read at least one interview experience from gfg daily." }, { "code": null, "e": 4480, "s": 4473, "text": "Juspay" }, { "code": null, "e": 4490, "s": 4480, "text": "Marketing" }, { "code": null, "e": 4500, "s": 4490, "text": "On-Campus" }, { "code": null, "e": 4511, "s": 4500, "text": "Internship" }, { "code": null, "e": 4533, "s": 4511, "text": "Interview Experiences" } ]
Type Hints in Python
26 Aug, 2019 Python is a dynamically typed language, which means you never have to explicitly indicate what kind of types variable has. But in some cases, dynamic typing can lead to some bugs that are very difficult to debug and in those cases, Type Hints or Static Typing can be convenient. Type Hints has been introduced as a new feature in Python 3.5. Let’s look at this factorial function to understand this clearly: # factorial functiondef factorial(i): if i<0: return None if i == 0: return 1 return i * factorial(i-1) # passing an integer to the functionprint(factorial(4)) # passing a string to the functionprint(factorial("4")) # passing a floating point number to the functionprint(factorial(5.01)) If we try to pass an integer to the function it works correctly. Now, if we try to pass a string to the factorial function, we will get an error, as we can’t do a mathematical comparison with string.Also, if we try to pass a floating point number, let’s say 5.01 we will also get an error here, as we are decrementing the number by 1 according to our logic in each iteration and it becomes -0.99 in the last iteration which returns “None”, which leads to an error as we are trying to multiply “None” with other floating point numbers. The Type-Hints code looks as follows:We have to specify the type of argument & also the type of the factorial function. # factorial functiondef factorial(i: int) -> int: if i<0: return None if i == 0: return 1 return i * factorial(i-1) # passing a fraction to the functionprint(factorial(5.01)) The Type-Hint is completely ignored by the Python interpreter. So, if we run this code again, we still get the same error. So, we have to use a static type checker that analyzes our code and tries to detect if we are violating our Type-Hints or not.The best known type checker is “mypy“. We can install it by simply using pip . pip install mypy To run the code now, we have to simply call the Python interpreter and we have to specify “-m” to indicate that we want to load a module and then specify the script which we want to check. For example: mypy program.py Now, if we run this it will not actually execute our “program.py” script but it will analyze it and will give us an error as like “Argument 1 to factorial has incompatible type float; expected int ” and which is a very clear message and that makes us much easier to debug our code as previously without mypy type checker the error message was not that much specific. And if we run the code again with an integer, it will work as fine. Python-Data Type Python-datatype Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n26 Aug, 2019" }, { "code": null, "e": 394, "s": 52, "text": "Python is a dynamically typed language, which means you never have to explicitly indicate what kind of types variable has. But in some cases, dynamic typing can lead to some bugs that are very difficult to debug and in those cases, Type Hints or Static Typing can be convenient. Type Hints has been introduced as a new feature in Python 3.5." }, { "code": null, "e": 460, "s": 394, "text": "Let’s look at this factorial function to understand this clearly:" }, { "code": "# factorial functiondef factorial(i): if i<0: return None if i == 0: return 1 return i * factorial(i-1) # passing an integer to the functionprint(factorial(4)) # passing a string to the functionprint(factorial(\"4\")) # passing a floating point number to the functionprint(factorial(5.01))", "e": 760, "s": 460, "text": null }, { "code": null, "e": 1295, "s": 760, "text": "If we try to pass an integer to the function it works correctly. Now, if we try to pass a string to the factorial function, we will get an error, as we can’t do a mathematical comparison with string.Also, if we try to pass a floating point number, let’s say 5.01 we will also get an error here, as we are decrementing the number by 1 according to our logic in each iteration and it becomes -0.99 in the last iteration which returns “None”, which leads to an error as we are trying to multiply “None” with other floating point numbers." }, { "code": null, "e": 1415, "s": 1295, "text": "The Type-Hints code looks as follows:We have to specify the type of argument & also the type of the factorial function." }, { "code": "# factorial functiondef factorial(i: int) -> int: if i<0: return None if i == 0: return 1 return i * factorial(i-1) # passing a fraction to the functionprint(factorial(5.01))", "e": 1600, "s": 1415, "text": null }, { "code": null, "e": 1723, "s": 1600, "text": "The Type-Hint is completely ignored by the Python interpreter. So, if we run this code again, we still get the same error." }, { "code": null, "e": 1928, "s": 1723, "text": "So, we have to use a static type checker that analyzes our code and tries to detect if we are violating our Type-Hints or not.The best known type checker is “mypy“. We can install it by simply using pip ." }, { "code": null, "e": 1945, "s": 1928, "text": "pip install mypy" }, { "code": null, "e": 2147, "s": 1945, "text": "To run the code now, we have to simply call the Python interpreter and we have to specify “-m” to indicate that we want to load a module and then specify the script which we want to check. For example:" }, { "code": null, "e": 2163, "s": 2147, "text": "mypy program.py" }, { "code": null, "e": 2598, "s": 2163, "text": "Now, if we run this it will not actually execute our “program.py” script but it will analyze it and will give us an error as like “Argument 1 to factorial has incompatible type float; expected int ” and which is a very clear message and that makes us much easier to debug our code as previously without mypy type checker the error message was not that much specific. And if we run the code again with an integer, it will work as fine." }, { "code": null, "e": 2615, "s": 2598, "text": "Python-Data Type" }, { "code": null, "e": 2631, "s": 2615, "text": "Python-datatype" }, { "code": null, "e": 2638, "s": 2631, "text": "Python" } ]
Set value of unsigned char array in C during runtime
31 Oct, 2019 This article explains how to set or change the value of unsigned char array during runtime in C. Given:Suppose we have an unsigned char array of size n unsigned char arr[n] = {}; // currently arr = {'', '', '', ...} To do:We want to set or change the values of this array during runtime. For example, we want to make the array arr = {'1', '2', '3', ...} Solution:This can be achieved with the help of memcpy() method. memcpy() is used to copy a block of memory from a location to another. It is declared in string.h Syntax: // Copies "numBytes" bytes from address "from" to address "to" void * memcpy(void *to, const void *from, size_t numBytes); Below is the implementation of the above program: // C program to set the value// of unsigned char array during runtime #include <stdio.h>#include <string.h> int main(){ // Initial unsigned char array unsigned char arr[3] = { 0 }; // Print the initial array printf("Initial unsigned char array:\n"); for (size_t i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) { printf("%c ", arr[i]); } printf("\n"); // Using memcpy() to change the values // during runtime memcpy(arr, (unsigned char[]){ '1', '2', '3' }, sizeof arr); // Print the updated array printf("Updated unsigned char array:\n"); for (size_t i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) { printf("%c ", arr[i]); } printf("\n"); return 0;} Arrays C Programs Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Arrow operator -> in C/C++ with Examples Basics of File Handling in C Header files in C/C++ and its uses UDP Server-Client implementation in C C Program to read contents of Whole File
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Oct, 2019" }, { "code": null, "e": 125, "s": 28, "text": "This article explains how to set or change the value of unsigned char array during runtime in C." }, { "code": null, "e": 180, "s": 125, "text": "Given:Suppose we have an unsigned char array of size n" }, { "code": null, "e": 246, "s": 180, "text": "unsigned char arr[n] = {};\n\n// currently arr = {'', '', '', ...}\n" }, { "code": null, "e": 318, "s": 246, "text": "To do:We want to set or change the values of this array during runtime." }, { "code": null, "e": 357, "s": 318, "text": "For example, we want to make the array" }, { "code": null, "e": 385, "s": 357, "text": "arr = {'1', '2', '3', ...}\n" }, { "code": null, "e": 547, "s": 385, "text": "Solution:This can be achieved with the help of memcpy() method. memcpy() is used to copy a block of memory from a location to another. It is declared in string.h" }, { "code": null, "e": 555, "s": 547, "text": "Syntax:" }, { "code": null, "e": 679, "s": 555, "text": "// Copies \"numBytes\" bytes from address \"from\" to address \"to\"\nvoid * memcpy(void *to, const void *from, size_t numBytes);\n" }, { "code": null, "e": 729, "s": 679, "text": "Below is the implementation of the above program:" }, { "code": "// C program to set the value// of unsigned char array during runtime #include <stdio.h>#include <string.h> int main(){ // Initial unsigned char array unsigned char arr[3] = { 0 }; // Print the initial array printf(\"Initial unsigned char array:\\n\"); for (size_t i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) { printf(\"%c \", arr[i]); } printf(\"\\n\"); // Using memcpy() to change the values // during runtime memcpy(arr, (unsigned char[]){ '1', '2', '3' }, sizeof arr); // Print the updated array printf(\"Updated unsigned char array:\\n\"); for (size_t i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) { printf(\"%c \", arr[i]); } printf(\"\\n\"); return 0;}", "e": 1469, "s": 729, "text": null }, { "code": null, "e": 1476, "s": 1469, "text": "Arrays" }, { "code": null, "e": 1487, "s": 1476, "text": "C Programs" }, { "code": null, "e": 1494, "s": 1487, "text": "Arrays" }, { "code": null, "e": 1592, "s": 1494, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1660, "s": 1592, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 1704, "s": 1660, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 1736, "s": 1704, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 1784, "s": 1736, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 1798, "s": 1784, "text": "Linear Search" }, { "code": null, "e": 1839, "s": 1798, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 1868, "s": 1839, "text": "Basics of File Handling in C" }, { "code": null, "e": 1903, "s": 1868, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 1941, "s": 1903, "text": "UDP Server-Client implementation in C" } ]
Minimum number of moves to make all elements equal
19 Apr, 2022 Given an array containing N elements and an integer K. It is allowed to perform the following operation any number of times on the given array: Insert the K-th element at the end of the array and delete the first element of the array. The task is to find the minimum number of moves needed to make all elements of the array equal. Print -1 if it is not possible.Examples: Input : arr[] = {1, 2, 3, 4}, K = 4 Output : 3 Step 1: 2 3 4 4 Step 2: 3 4 4 4 Step 3: 4 4 4 4 Input : arr[] = {2, 1}, K = 1 Output : -1 The array will keep alternating between 1, 2 and 2, 1 regardless of how many moves you apply. Let’s look at the operations with respect to the original array, first, we copy a[k] to the end, then a[k+1], and so on. To make sure that we only copy equal elements, all elements in the range K to N should be equal. So, to find the minimum number of moves, we need to remove all elements in range 1 to K that are not equal to a[k]. Hence, we need to keep applying operations until we reach the rightmost term in range 1 to K that is not equal to a[k].Below is the implementation of the above approach: C++ C Java Python3 C# PHP Javascript // C++ Program to find minimum number of operations to make// all array Elements equal #include <bits/stdc++.h>using namespace std; // Function to find minimum number of operationsto make all// array Elements equalint countMinimumMoves(int arr[], int n, int k){ int i; // Check if it is possible or not i.e., if all the // elements from index K to N are not equal for (i = k - 1; i < n; i++) if (arr[i] != arr[k - 1]) return -1; // Find minimum number of moves for (i = k - 1; i >= 0; i--) if (arr[i] != arr[k - 1]) return i + 1; // Elements are already equal return 0;} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4 }; int K = 4; int n = sizeof(arr) / sizeof(arr[0]); cout << countMinimumMoves(arr, n, K); return 0;} // This code is contributed by Sania Kumari Gupta // C Program to find minimum number of operations to make// all array Elements equal #include <stdio.h> // Function to find minimum number of operations to make all// array Elements equalint countMinimumMoves(int arr[], int n, int k){ int i; // Check if it is possible or not i.e., if all the // elements from index K to N are not equal for (i = k - 1; i < n; i++) if (arr[i] != arr[k - 1]) return -1; // Find minimum number of moves for (i = k - 1; i >= 0; i--) if (arr[i] != arr[k - 1]) return i + 1; // Elements are already equal return 0;} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4 }; int K = 4; int n = sizeof(arr) / sizeof(arr[0]); printf("%d", countMinimumMoves(arr, n, K)); return 0;} // This code is contributed by Sania Kumari Gupta // Java Program to find minimum number of operations to make// all array Elements equal import java.io.*; class GFG { // Function to find minimum number of operations to make // all array Elements equal static int countMinimumMoves(int arr[], int n, int k) { int i; // Check if it is possible or not i.e., if all the // elements from index K to N are not equal for (i = k - 1; i < n; i++) if (arr[i] != arr[k - 1]) return -1; // Find minimum number of moves for (i = k - 1; i >= 0; i--) if (arr[i] != arr[k - 1]) return i + 1; // Elements are already equal return 0; } // Driver Code public static void main(String[] args) { int arr[] = { 1, 2, 3, 4 }; int K = 4; int n = arr.length; System.out.print(countMinimumMoves(arr, n, K)); }} // This code is contributed by Sania Kumari Gupta # Python3 Program to find minimum# number of operations to make all# array Elements equal # Function to find minimum number# of operations to make all array# Elements equaldef countMinimumMoves(arr, n, k) : # Check if it is possible or not # That is if all the elements from # index K to N are not equal for i in range(k - 1, n) : if (arr[i] != arr[k - 1]) : return -1 # Find minimum number of moves for i in range(k - 1, -1, -1) : if (arr[i] != arr[k - 1]) : return i + 1 # Elements are already equal return 0 # Driver Codeif __name__ == "__main__" : arr = [ 1, 2, 3, 4 ] K = 4 n = len(arr) print(countMinimumMoves(arr, n, K)) # This code is contributed by Ryuga // C# Program to find minimum number of// operations to make all array Elements// equalusing System; class GFG{ // Function to find minimum number// of operations to make all array// Elements equalstatic int countMinimumMoves(int []arr, int n, int k){ int i; // Check if it is possible or not // That is if all the elements from // index K to N are not equal for (i = k - 1; i < n; i++) if (arr[i] != arr[k - 1]) return -1; // Find minimum number of moves for (i = k - 1; i >= 0; i--) if (arr[i] != arr[k - 1]) return i + 1; // Elements are already equal return 0;} // Driver Codepublic static void Main (){ int []arr = { 1, 2, 3, 4 }; int K = 4; int n = arr.Length; Console.Write(countMinimumMoves(arr, n, K));}} // This code is contributed// by 29AjayKumar <?php// PHP Program to find minimum number of// operations to make all array Elements// equal // Function to find minimum number// of operations to make all array// Elements equalfunction countMinimumMoves($arr, $n, $k){ // Check if it is possible or not // That is if all the elements from // index K to N are not equal for ($i = $k - 1; $i < $n; $i++) if ($arr[$i] != $arr[$k - 1]) return -1; // Find minimum number of moves for ($i = $k - 1; $i >= 0; $i--) if ($arr[$i] != $arr[$k - 1]) return $i + 1; // Elements are already equal return 0;} // Driver Code$arr = array(1, 2, 3, 4);$K = 4; $n = sizeof($arr); echo countMinimumMoves($arr, $n, $K); // This code is contributed// by Akanksha Rai?> <script> // JavaScript Program to find minimum number of// operations to make all array Elements// equal // Function to find minimum number of operations// to make all array Elements equalfunction countMinimumMoves(arr, n, k){ let i; // Check if it is possible or not // That is if all the elements from // index K to N are not equal for (i = k - 1; i < n; i++) if (arr[i] != arr[k - 1]) return -1; // Find minimum number of moves for (i = k - 1; i >= 0; i--) if (arr[i] != arr[k - 1]) return i + 1; // Elements are already equal return 0;} // Driver Code let arr = [ 1, 2, 3, 4 ]; let K = 4; let n = arr.length; document.write(countMinimumMoves(arr, n, K)); // This code is contributed by Surbhi Tyagi. </script> 3 Time Complexity: O(N)Auxiliary Space: O(1) Shashank12 29AjayKumar Akanksha_Rai ankthon surbhityagi15 pankajsharmagfg krisania804 Constructive Algorithms Algorithms Arrays Arrays Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation What is Hashing | A Complete Tutorial Understanding Time Complexity with Simple Examples CPU Scheduling in Operating Systems 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": "\n19 Apr, 2022" }, { "code": null, "e": 198, "s": 52, "text": "Given an array containing N elements and an integer K. It is allowed to perform the following operation any number of times on the given array: " }, { "code": null, "e": 289, "s": 198, "text": "Insert the K-th element at the end of the array and delete the first element of the array." }, { "code": null, "e": 428, "s": 289, "text": "The task is to find the minimum number of moves needed to make all elements of the array equal. Print -1 if it is not possible.Examples: " }, { "code": null, "e": 661, "s": 428, "text": "Input : arr[] = {1, 2, 3, 4}, K = 4\nOutput : 3\nStep 1: 2 3 4 4\nStep 2: 3 4 4 4\nStep 3: 4 4 4 4\n\nInput : arr[] = {2, 1}, K = 1\nOutput : -1\nThe array will keep alternating between 1, 2 and \n2, 1 regardless of how many moves you apply." }, { "code": null, "e": 1167, "s": 661, "text": "Let’s look at the operations with respect to the original array, first, we copy a[k] to the end, then a[k+1], and so on. To make sure that we only copy equal elements, all elements in the range K to N should be equal. So, to find the minimum number of moves, we need to remove all elements in range 1 to K that are not equal to a[k]. Hence, we need to keep applying operations until we reach the rightmost term in range 1 to K that is not equal to a[k].Below is the implementation of the above approach: " }, { "code": null, "e": 1171, "s": 1167, "text": "C++" }, { "code": null, "e": 1173, "s": 1171, "text": "C" }, { "code": null, "e": 1178, "s": 1173, "text": "Java" }, { "code": null, "e": 1186, "s": 1178, "text": "Python3" }, { "code": null, "e": 1189, "s": 1186, "text": "C#" }, { "code": null, "e": 1193, "s": 1189, "text": "PHP" }, { "code": null, "e": 1204, "s": 1193, "text": "Javascript" }, { "code": "// C++ Program to find minimum number of operations to make// all array Elements equal #include <bits/stdc++.h>using namespace std; // Function to find minimum number of operationsto make all// array Elements equalint countMinimumMoves(int arr[], int n, int k){ int i; // Check if it is possible or not i.e., if all the // elements from index K to N are not equal for (i = k - 1; i < n; i++) if (arr[i] != arr[k - 1]) return -1; // Find minimum number of moves for (i = k - 1; i >= 0; i--) if (arr[i] != arr[k - 1]) return i + 1; // Elements are already equal return 0;} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4 }; int K = 4; int n = sizeof(arr) / sizeof(arr[0]); cout << countMinimumMoves(arr, n, K); return 0;} // This code is contributed by Sania Kumari Gupta", "e": 2052, "s": 1204, "text": null }, { "code": "// C Program to find minimum number of operations to make// all array Elements equal #include <stdio.h> // Function to find minimum number of operations to make all// array Elements equalint countMinimumMoves(int arr[], int n, int k){ int i; // Check if it is possible or not i.e., if all the // elements from index K to N are not equal for (i = k - 1; i < n; i++) if (arr[i] != arr[k - 1]) return -1; // Find minimum number of moves for (i = k - 1; i >= 0; i--) if (arr[i] != arr[k - 1]) return i + 1; // Elements are already equal return 0;} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4 }; int K = 4; int n = sizeof(arr) / sizeof(arr[0]); printf(\"%d\", countMinimumMoves(arr, n, K)); return 0;} // This code is contributed by Sania Kumari Gupta", "e": 2879, "s": 2052, "text": null }, { "code": "// Java Program to find minimum number of operations to make// all array Elements equal import java.io.*; class GFG { // Function to find minimum number of operations to make // all array Elements equal static int countMinimumMoves(int arr[], int n, int k) { int i; // Check if it is possible or not i.e., if all the // elements from index K to N are not equal for (i = k - 1; i < n; i++) if (arr[i] != arr[k - 1]) return -1; // Find minimum number of moves for (i = k - 1; i >= 0; i--) if (arr[i] != arr[k - 1]) return i + 1; // Elements are already equal return 0; } // Driver Code public static void main(String[] args) { int arr[] = { 1, 2, 3, 4 }; int K = 4; int n = arr.length; System.out.print(countMinimumMoves(arr, n, K)); }} // This code is contributed by Sania Kumari Gupta", "e": 3829, "s": 2879, "text": null }, { "code": "# Python3 Program to find minimum# number of operations to make all# array Elements equal # Function to find minimum number# of operations to make all array# Elements equaldef countMinimumMoves(arr, n, k) : # Check if it is possible or not # That is if all the elements from # index K to N are not equal for i in range(k - 1, n) : if (arr[i] != arr[k - 1]) : return -1 # Find minimum number of moves for i in range(k - 1, -1, -1) : if (arr[i] != arr[k - 1]) : return i + 1 # Elements are already equal return 0 # Driver Codeif __name__ == \"__main__\" : arr = [ 1, 2, 3, 4 ] K = 4 n = len(arr) print(countMinimumMoves(arr, n, K)) # This code is contributed by Ryuga", "e": 4571, "s": 3829, "text": null }, { "code": "// C# Program to find minimum number of// operations to make all array Elements// equalusing System; class GFG{ // Function to find minimum number// of operations to make all array// Elements equalstatic int countMinimumMoves(int []arr, int n, int k){ int i; // Check if it is possible or not // That is if all the elements from // index K to N are not equal for (i = k - 1; i < n; i++) if (arr[i] != arr[k - 1]) return -1; // Find minimum number of moves for (i = k - 1; i >= 0; i--) if (arr[i] != arr[k - 1]) return i + 1; // Elements are already equal return 0;} // Driver Codepublic static void Main (){ int []arr = { 1, 2, 3, 4 }; int K = 4; int n = arr.Length; Console.Write(countMinimumMoves(arr, n, K));}} // This code is contributed// by 29AjayKumar", "e": 5450, "s": 4571, "text": null }, { "code": "<?php// PHP Program to find minimum number of// operations to make all array Elements// equal // Function to find minimum number// of operations to make all array// Elements equalfunction countMinimumMoves($arr, $n, $k){ // Check if it is possible or not // That is if all the elements from // index K to N are not equal for ($i = $k - 1; $i < $n; $i++) if ($arr[$i] != $arr[$k - 1]) return -1; // Find minimum number of moves for ($i = $k - 1; $i >= 0; $i--) if ($arr[$i] != $arr[$k - 1]) return $i + 1; // Elements are already equal return 0;} // Driver Code$arr = array(1, 2, 3, 4);$K = 4; $n = sizeof($arr); echo countMinimumMoves($arr, $n, $K); // This code is contributed// by Akanksha Rai?>", "e": 6211, "s": 5450, "text": null }, { "code": "<script> // JavaScript Program to find minimum number of// operations to make all array Elements// equal // Function to find minimum number of operations// to make all array Elements equalfunction countMinimumMoves(arr, n, k){ let i; // Check if it is possible or not // That is if all the elements from // index K to N are not equal for (i = k - 1; i < n; i++) if (arr[i] != arr[k - 1]) return -1; // Find minimum number of moves for (i = k - 1; i >= 0; i--) if (arr[i] != arr[k - 1]) return i + 1; // Elements are already equal return 0;} // Driver Code let arr = [ 1, 2, 3, 4 ]; let K = 4; let n = arr.length; document.write(countMinimumMoves(arr, n, K)); // This code is contributed by Surbhi Tyagi. </script>", "e": 7008, "s": 6211, "text": null }, { "code": null, "e": 7010, "s": 7008, "text": "3" }, { "code": null, "e": 7056, "s": 7012, "text": "Time Complexity: O(N)Auxiliary Space: O(1) " }, { "code": null, "e": 7067, "s": 7056, "text": "Shashank12" }, { "code": null, "e": 7079, "s": 7067, "text": "29AjayKumar" }, { "code": null, "e": 7092, "s": 7079, "text": "Akanksha_Rai" }, { "code": null, "e": 7100, "s": 7092, "text": "ankthon" }, { "code": null, "e": 7114, "s": 7100, "text": "surbhityagi15" }, { "code": null, "e": 7130, "s": 7114, "text": "pankajsharmagfg" }, { "code": null, "e": 7142, "s": 7130, "text": "krisania804" }, { "code": null, "e": 7166, "s": 7142, "text": "Constructive Algorithms" }, { "code": null, "e": 7177, "s": 7166, "text": "Algorithms" }, { "code": null, "e": 7184, "s": 7177, "text": "Arrays" }, { "code": null, "e": 7191, "s": 7184, "text": "Arrays" }, { "code": null, "e": 7202, "s": 7191, "text": "Algorithms" }, { "code": null, "e": 7300, "s": 7202, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7325, "s": 7300, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 7374, "s": 7325, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 7412, "s": 7374, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 7463, "s": 7412, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 7499, "s": 7463, "text": "CPU Scheduling in Operating Systems" }, { "code": null, "e": 7514, "s": 7499, "text": "Arrays in Java" }, { "code": null, "e": 7560, "s": 7514, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 7628, "s": 7560, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 7660, "s": 7628, "text": "Largest Sum Contiguous Subarray" } ]
RESTfull routes on Node.js and MongoDB
30 Jun, 2020 REST stands for representational state transfer which basically provides a way of mapping HTTP verbs such as (GET, POST, PUT, DELETE) with CRUD actions such as (CREATE, READ, UPDATE, DELETE). Whenever we click on a link on the webpage we are basically making a state transfer from one page to another. For example, when we click for the homepage of the blog website we want to get all the blogs that are stored on the server’s database which is basically a mapping of HTTP GET request with the READ request of database. Similarly, there are more HTTP requests where we are interacting with the database like creating a blog, editing a blog, deleting a blog, and much more. RESTfull routes are standard conventions of how to implement these mapping. It’s not necessary that you can’t implement such functionality without RESTfull routes but these are the simplest and standard route which are followed by most of the developer. We are going to understand how they work by creating a simple blog application where we can delete, add, create, edit, and display the blog. We are going to use node.js which will serve the webpage and MongoDB for storing the data. The entire code is available at Github which includes how to interact with the database and configure all dependency. Just to give little idea about the data schema below is Schema for our blog post. Note: Entire code is available at Github var blogSchema = new mongoose.Schema({ title: String, image: String, body: String, created: {type: Date, default: Date.now}}); var Blog = mongoose.model("Blog", blogSchema); Index Page(GET): For the index page, we want to display all the blogs which are stored in the database. To do so first we will get all data from the database using find() function of MongoDB and then send the result to a page that will show those posts. We are finding all the blog posts stored in the database which we are retrieving and handling using the function inside and if an error occurred we are sending to console ERROR! message and if everything works fine then we are rendering the index page where we are passing all blogs as data(blogs) which basically contain all blog info. Which is further used by the index page to display those data. // Routesapp.get("/blogs", function(req, res){ Blog.find({}, function(err, blogs){ if (err) { console.log("ERROR!"); } else { res.render("index.ejs", {blogs: blogs}); } });}); Filename: index.ejs <% blogs.forEach(function(blog){ %> <img src="<%= blog.image %>"> <a href="/blogs/<%= blog._id %>"><%= blog.title %></a> <%= blog.created.toDateString() %>...</span> <%- blog.body.substring(0, 50) %> <a href="/blogs/<%= blog._id %>">Read More</a> <% }) %> New Blog(GET) and Create Blog(POST): We want to add a new blog so we need to get the form that will take input from the user. Hence first we will use new.ejs to render the form after that we will fill all the information and after that, we want to save it into the database which we will do by performing a POST request. Observe that, we have the same route as above but here only request type is changed which will be handled separately. We are creating a new blog post by using MongoDB create() function. If we don’t get any error, we will direct to the home page where the user can see that blog has been added and confirms that operation executes successfully. // Render the new.ejs page that contains// the form for adding a blogapp.get("/blogs/new", function (req, res) { res.render("new.ejs");}); // Add data to database and redirect to// home page where we see the new page// with updationapp.post("/blogs", function (req, res) { Blog.create(req.body.blog, function (err, newBlog) { if (err) { console.log("ERROR!"); } else { res.redirect("/blogs"); } });}); Filename: new.ejs <form action="/blogs" method="POST"> <label>Title</label> <input type="text" name="blog[title]" placeholder="Title"> <label>Image</label> <input type="text" name="blog[image]" placeholder="Image"> <label>Blog Content</label> <textarea name="blog[body]"></textarea> <input type="submit"></form> Show(GET): Generally, the blog home page doesn’t show all blogs entirely it only shows starting few lines and if a user wants to read it based on its title and preview, we want to direct to a new page where the entire blog is shown in our case we will redirect to show.ejs HTML file. To do so all the blogs have unique id associated with it and if we want to display a particular blog, we will simply get the id of that blog and use findById() to get data and send it to show.ejs HTML file where data will be shown. // Routesapp.get("/blogs/:id", function(req, res){ Blog.findById(req.params.id, function(err, foundBlog){ if (err) { console.log("ERROR!"); } else { res.render("show.ejs", {blog: foundBlog}); } });}); Filename: show.ejs <%= blog.title %><img c src=" <%= blog.image %>"><span><%= blog.created.toDateString() %></span><p><%- blog.body %></p><a href="/blogs/<%= blog._id %>/edit">Edit</a><form action="/blogs/<%= blog._id %>?_method=DELETE" method="POST"> <button class="ui red inverted button"> Delete </button></form> Edit(GET) and UPDATE(PUT): Sometimes we want to edit a blog, we first need a unique id of the blog after that sent user to a different page where a form is shown which is prefilled with the previous data and the user will update its data after that user will send to updated blog. To do so first get a request to go edit.ejs page then we will use PUT request which will use the findByIdAndUpdate() function of MongoDB to update the data with data that was already in the database under given id. app.get("/blogs/:id/edit", function(req, res){ Blog.findById(req.params.id, function(err, foundBlog){ if (err){ console.log("ERROR!"); } else { res.render("edit.ejs", {blog: foundBlog}); } });}); app.put("/blogs/:id", function(req, res){ Blog.findByIdAndUpdate(req.params.id, req.body.blog, function(err,updatedBlog){ if (err) { console.log("ERROR!"); } else { res.redirect("/blogs/"+req.params.id); } });}); Edit <%= blog.title %><form action= "/blogs/<%= blog._id %>?_method=PUT" method="POST"> <label>Title</label> <input type="text" name="blog[title]" value="<%= blog.title %>"> <label>Image</label> <input type="text" name="blog[image]" value="<%= blog.image%>"> <label>Blog Content</label> <textarea name="blog[body]"> <%= blog.body%> </textarea> <input type="submit"></form> Destroy(DELETE): Lastly, if we want to delete a specific blog, we will simply use the ID of the blog and use the findByIdAndRemove() function of MongoDB to delete a specific blog from the database. app.delete("/blogs/:id", function(req, res){ Blog.findByIdAndRemove(req.params.id, function(err){ if (err) { res.redirect("/blogs"); } else { res.redirect("/blogs"); } });}); MongoDB Node.js-Misc MongoDB Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to connect MongoDB with ReactJS ? MongoDB - limit() Method MongoDB - sort() Method MongoDB - FindOne() Method MongoDB updateOne() Method - db.Collection.updateOne() How to update Node.js and NPM to next version ? Installation of Node.js on Linux Node.js fs.readFileSync() Method How to install the previous version of node.js and npm ? Node.js fs.writeFile() Method
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2020" }, { "code": null, "e": 548, "s": 28, "text": "REST stands for representational state transfer which basically provides a way of mapping HTTP verbs such as (GET, POST, PUT, DELETE) with CRUD actions such as (CREATE, READ, UPDATE, DELETE). Whenever we click on a link on the webpage we are basically making a state transfer from one page to another. For example, when we click for the homepage of the blog website we want to get all the blogs that are stored on the server’s database which is basically a mapping of HTTP GET request with the READ request of database." }, { "code": null, "e": 1096, "s": 548, "text": "Similarly, there are more HTTP requests where we are interacting with the database like creating a blog, editing a blog, deleting a blog, and much more. RESTfull routes are standard conventions of how to implement these mapping. It’s not necessary that you can’t implement such functionality without RESTfull routes but these are the simplest and standard route which are followed by most of the developer. We are going to understand how they work by creating a simple blog application where we can delete, add, create, edit, and display the blog." }, { "code": null, "e": 1387, "s": 1096, "text": "We are going to use node.js which will serve the webpage and MongoDB for storing the data. The entire code is available at Github which includes how to interact with the database and configure all dependency. Just to give little idea about the data schema below is Schema for our blog post." }, { "code": null, "e": 1428, "s": 1387, "text": "Note: Entire code is available at Github" }, { "code": "var blogSchema = new mongoose.Schema({ title: String, image: String, body: String, created: {type: Date, default: Date.now}}); var Blog = mongoose.model(\"Blog\", blogSchema);", "e": 1615, "s": 1428, "text": null }, { "code": null, "e": 2269, "s": 1615, "text": "Index Page(GET): For the index page, we want to display all the blogs which are stored in the database. To do so first we will get all data from the database using find() function of MongoDB and then send the result to a page that will show those posts. We are finding all the blog posts stored in the database which we are retrieving and handling using the function inside and if an error occurred we are sending to console ERROR! message and if everything works fine then we are rendering the index page where we are passing all blogs as data(blogs) which basically contain all blog info. Which is further used by the index page to display those data." }, { "code": "// Routesapp.get(\"/blogs\", function(req, res){ Blog.find({}, function(err, blogs){ if (err) { console.log(\"ERROR!\"); } else { res.render(\"index.ejs\", {blogs: blogs}); } });});", "e": 2494, "s": 2269, "text": null }, { "code": null, "e": 2514, "s": 2494, "text": "Filename: index.ejs" }, { "code": "<% blogs.forEach(function(blog){ %> <img src=\"<%= blog.image %>\"> <a href=\"/blogs/<%= blog._id %>\"><%= blog.title %></a> <%= blog.created.toDateString() %>...</span> <%- blog.body.substring(0, 50) %> <a href=\"/blogs/<%= blog._id %>\">Read More</a> <% }) %>", "e": 2787, "s": 2514, "text": null }, { "code": null, "e": 3452, "s": 2787, "text": "New Blog(GET) and Create Blog(POST): We want to add a new blog so we need to get the form that will take input from the user. Hence first we will use new.ejs to render the form after that we will fill all the information and after that, we want to save it into the database which we will do by performing a POST request. Observe that, we have the same route as above but here only request type is changed which will be handled separately. We are creating a new blog post by using MongoDB create() function. If we don’t get any error, we will direct to the home page where the user can see that blog has been added and confirms that operation executes successfully." }, { "code": "// Render the new.ejs page that contains// the form for adding a blogapp.get(\"/blogs/new\", function (req, res) { res.render(\"new.ejs\");}); // Add data to database and redirect to// home page where we see the new page// with updationapp.post(\"/blogs\", function (req, res) { Blog.create(req.body.blog, function (err, newBlog) { if (err) { console.log(\"ERROR!\"); } else { res.redirect(\"/blogs\"); } });});", "e": 3907, "s": 3452, "text": null }, { "code": null, "e": 3925, "s": 3907, "text": "Filename: new.ejs" }, { "code": "<form action=\"/blogs\" method=\"POST\"> <label>Title</label> <input type=\"text\" name=\"blog[title]\" placeholder=\"Title\"> <label>Image</label> <input type=\"text\" name=\"blog[image]\" placeholder=\"Image\"> <label>Blog Content</label> <textarea name=\"blog[body]\"></textarea> <input type=\"submit\"></form>", "e": 4271, "s": 3925, "text": null }, { "code": null, "e": 4787, "s": 4271, "text": "Show(GET): Generally, the blog home page doesn’t show all blogs entirely it only shows starting few lines and if a user wants to read it based on its title and preview, we want to direct to a new page where the entire blog is shown in our case we will redirect to show.ejs HTML file. To do so all the blogs have unique id associated with it and if we want to display a particular blog, we will simply get the id of that blog and use findById() to get data and send it to show.ejs HTML file where data will be shown." }, { "code": "// Routesapp.get(\"/blogs/:id\", function(req, res){ Blog.findById(req.params.id, function(err, foundBlog){ if (err) { console.log(\"ERROR!\"); } else { res.render(\"show.ejs\", {blog: foundBlog}); } });});", "e": 5061, "s": 4787, "text": null }, { "code": null, "e": 5080, "s": 5061, "text": "Filename: show.ejs" }, { "code": "<%= blog.title %><img c src=\" <%= blog.image %>\"><span><%= blog.created.toDateString() %></span><p><%- blog.body %></p><a href=\"/blogs/<%= blog._id %>/edit\">Edit</a><form action=\"/blogs/<%= blog._id %>?_method=DELETE\" method=\"POST\"> <button class=\"ui red inverted button\"> Delete </button></form>", "e": 5401, "s": 5080, "text": null }, { "code": null, "e": 5897, "s": 5401, "text": "Edit(GET) and UPDATE(PUT): Sometimes we want to edit a blog, we first need a unique id of the blog after that sent user to a different page where a form is shown which is prefilled with the previous data and the user will update its data after that user will send to updated blog. To do so first get a request to go edit.ejs page then we will use PUT request which will use the findByIdAndUpdate() function of MongoDB to update the data with data that was already in the database under given id." }, { "code": "app.get(\"/blogs/:id/edit\", function(req, res){ Blog.findById(req.params.id, function(err, foundBlog){ if (err){ console.log(\"ERROR!\"); } else { res.render(\"edit.ejs\", {blog: foundBlog}); } });}); app.put(\"/blogs/:id\", function(req, res){ Blog.findByIdAndUpdate(req.params.id, req.body.blog, function(err,updatedBlog){ if (err) { console.log(\"ERROR!\"); } else { res.redirect(\"/blogs/\"+req.params.id); } });});", "e": 6402, "s": 5897, "text": null }, { "code": "Edit <%= blog.title %><form action= \"/blogs/<%= blog._id %>?_method=PUT\" method=\"POST\"> <label>Title</label> <input type=\"text\" name=\"blog[title]\" value=\"<%= blog.title %>\"> <label>Image</label> <input type=\"text\" name=\"blog[image]\" value=\"<%= blog.image%>\"> <label>Blog Content</label> <textarea name=\"blog[body]\"> <%= blog.body%> </textarea> <input type=\"submit\"></form>", "e": 6842, "s": 6402, "text": null }, { "code": null, "e": 7040, "s": 6842, "text": "Destroy(DELETE): Lastly, if we want to delete a specific blog, we will simply use the ID of the blog and use the findByIdAndRemove() function of MongoDB to delete a specific blog from the database." }, { "code": "app.delete(\"/blogs/:id\", function(req, res){ Blog.findByIdAndRemove(req.params.id, function(err){ if (err) { res.redirect(\"/blogs\"); } else { res.redirect(\"/blogs\"); } });});", "e": 7264, "s": 7040, "text": null }, { "code": null, "e": 7272, "s": 7264, "text": "MongoDB" }, { "code": null, "e": 7285, "s": 7272, "text": "Node.js-Misc" }, { "code": null, "e": 7293, "s": 7285, "text": "MongoDB" }, { "code": null, "e": 7301, "s": 7293, "text": "Node.js" }, { "code": null, "e": 7318, "s": 7301, "text": "Web Technologies" }, { "code": null, "e": 7416, "s": 7318, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7454, "s": 7416, "text": "How to connect MongoDB with ReactJS ?" }, { "code": null, "e": 7479, "s": 7454, "text": "MongoDB - limit() Method" }, { "code": null, "e": 7503, "s": 7479, "text": "MongoDB - sort() Method" }, { "code": null, "e": 7530, "s": 7503, "text": "MongoDB - FindOne() Method" }, { "code": null, "e": 7585, "s": 7530, "text": "MongoDB updateOne() Method - db.Collection.updateOne()" }, { "code": null, "e": 7633, "s": 7585, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 7666, "s": 7633, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 7699, "s": 7666, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 7756, "s": 7699, "text": "How to install the previous version of node.js and npm ?" } ]
GATE-CS-2001 - GeeksforGeeks
22 Nov, 2021 S1: The sum of two singular n × n matrices may be non-singular S2: The sum of two n × n non-singular matrices may be singular. M1 and M2 are singular M1 = 1 1 1 1 M2 = 1 -1 -1 1 But M1+M2 is non-singular M1+M2 = 2 0 0 2 M1 and M2 are non-singular M1 = 1 0 0 1 M2 = -1 0 0 -1 But M1+M2 is singular M1+M2 = 0 0 0 0 R1(a,b) iff (a+b) is even over the set of integers R2(a,b) iff (a+b) is odd over the set of integers R3(a,b) iff a.b > 0 over the set of non-zero rational numbers R4(a,b) iff |a - b| <= 2 over the set of natural numbers R1(a,b)Reflexive : Yes, because (a+a) is even.Symmetrix : Yes, (a+b) is even ⟹ (b+a) is even.Transitive : Yes, because (a+b) is even and (b+c) is even ⟹ (a+c) is even.So R1 is equivalence relation.R2(a,b)Reflexive : No, because (a+a) is even.So R2 is not equivalence relation.R3(a,b)Reflexive : Yes, because a.a > 0.Symmetrix : Yes, a.b > 0 ⟹ b.a > 0.Transitive : Yes, because a.b > 0 and b.c > 0 ⟹ a.c > 0.So R3 is equivalence relation.R4(a,b)Reflexive : Yes, because |a-a| ≤ 2.Symmetrix : Yes, |a-b| ≤ 2 ⟹ |b-a| ≤ 2.Transitive : No, because |a-b| ≤ 2 and |b-c| ≤ 2 ⇏ (a-c) is even.So R4 is not equivalence relation. R1(a,b)Reflexive : Yes, because (a+a) is even.Symmetrix : Yes, (a+b) is even ⟹ (b+a) is even.Transitive : Yes, because (a+b) is even and (b+c) is even ⟹ (a+c) is even.So R1 is equivalence relation. Reflexive : Yes, because (a+a) is even. Symmetrix : Yes, (a+b) is even ⟹ (b+a) is even. Transitive : Yes, because (a+b) is even and (b+c) is even ⟹ (a+c) is even. R2(a,b)Reflexive : No, because (a+a) is even.So R2 is not equivalence relation. Reflexive : No, because (a+a) is even. R3(a,b)Reflexive : Yes, because a.a > 0.Symmetrix : Yes, a.b > 0 ⟹ b.a > 0.Transitive : Yes, because a.b > 0 and b.c > 0 ⟹ a.c > 0.So R3 is equivalence relation. Reflexive : Yes, because a.a > 0. Symmetrix : Yes, a.b > 0 ⟹ b.a > 0. Transitive : Yes, because a.b > 0 and b.c > 0 ⟹ a.c > 0. R4(a,b)Reflexive : Yes, because |a-a| ≤ 2.Symmetrix : Yes, |a-b| ≤ 2 ⟹ |b-a| ≤ 2.Transitive : No, because |a-b| ≤ 2 and |b-c| ≤ 2 ⇏ (a-c) is even.So R4 is not equivalence relation. Reflexive : Yes, because |a-a| ≤ 2. Symmetrix : Yes, |a-b| ≤ 2 ⟹ |b-a| ≤ 2. Transitive : No, because |a-b| ≤ 2 and |b-c| ≤ 2 ⇏ (a-c) is even. Consider two well-formed formulas in prepositional logic. F1 : P ⇒ ¬P F2 : ( P⇒¬P)∨(¬P⇒P) Which of the following statements is correct? F1 and F2 are both satisfiable F1 unsatisfiable, F2 is satisfiable F1 is unsatisfiable, F2 is valid F1 is satisfiable, F2 is valid The concept behind this solution is: a) Satisfiable If there is an assignment of truth values which makes that expression true. b) UnSatisfiable If there is no such assignment which makes the expression true c) Valid If the expression is Tautology Here, P => Q is nothing but –P v Q F1: P => -P = -P v –P = -P F1 will be true if P is false and F1 will be false when P is true so F1 is Satisfiable F2: (P => -P) v (-P => P) which is equals to (-P v-P) v (-(-P) v P) = (-P) v (P) = Tautology So, F1 is Satisfiable and F2 is valid Option (a) is correct. Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... Must Do Coding Questions for Product Based Companies Git - Difference Between Git Fetch and Git Pull SDE SHEET - A Complete Guide for SDE Preparation How to Install and Use NVM on Windows? DSA Sheet by Love Babbar Top 20 Puzzles Commonly Asked During SDE Interviews Spring Boot - Architecture Software Testing Metrics, its Types and Example Bash Scripting - If Statement
[ { "code": null, "e": 29577, "s": 29549, "text": "\n22 Nov, 2021" }, { "code": null, "e": 29705, "s": 29577, "text": "S1: The sum of two singular n × n matrices may be non-singular\nS2: The sum of two n × n non-singular matrices may be singular. " }, { "code": null, "e": 29842, "s": 29705, "text": "M1 and M2 are singular\nM1 = 1 1\n 1 1\n \nM2 = 1 -1\n -1 1\n\nBut M1+M2 is non-singular \nM1+M2 = 2 0\n 0 2\n" }, { "code": null, "e": 29980, "s": 29842, "text": "M1 and M2 are non-singular\nM1 = 1 0\n 0 1\n \nM2 = -1 0\n 0 -1\n\nBut M1+M2 is singular \nM1+M2 = 0 0\n 0 0\n" }, { "code": null, "e": 30200, "s": 29980, "text": "R1(a,b) iff (a+b) is even over the set of integers\nR2(a,b) iff (a+b) is odd over the set of integers\nR3(a,b) iff a.b > 0 over the set of non-zero rational numbers\nR4(a,b) iff |a - b| <= 2 over the set of natural numbers" }, { "code": null, "e": 30819, "s": 30200, "text": "R1(a,b)Reflexive : Yes, because (a+a) is even.Symmetrix : Yes, (a+b) is even ⟹ (b+a) is even.Transitive : Yes, because (a+b) is even and (b+c) is even ⟹ (a+c) is even.So R1 is equivalence relation.R2(a,b)Reflexive : No, because (a+a) is even.So R2 is not equivalence relation.R3(a,b)Reflexive : Yes, because a.a > 0.Symmetrix : Yes, a.b > 0 ⟹ b.a > 0.Transitive : Yes, because a.b > 0 and b.c > 0 ⟹ a.c > 0.So R3 is equivalence relation.R4(a,b)Reflexive : Yes, because |a-a| ≤ 2.Symmetrix : Yes, |a-b| ≤ 2 ⟹ |b-a| ≤ 2.Transitive : No, because |a-b| ≤ 2 and |b-c| ≤ 2 ⇏ (a-c) is even.So R4 is not equivalence relation." }, { "code": null, "e": 31017, "s": 30819, "text": "R1(a,b)Reflexive : Yes, because (a+a) is even.Symmetrix : Yes, (a+b) is even ⟹ (b+a) is even.Transitive : Yes, because (a+b) is even and (b+c) is even ⟹ (a+c) is even.So R1 is equivalence relation." }, { "code": null, "e": 31057, "s": 31017, "text": "Reflexive : Yes, because (a+a) is even." }, { "code": null, "e": 31105, "s": 31057, "text": "Symmetrix : Yes, (a+b) is even ⟹ (b+a) is even." }, { "code": null, "e": 31180, "s": 31105, "text": "Transitive : Yes, because (a+b) is even and (b+c) is even ⟹ (a+c) is even." }, { "code": null, "e": 31260, "s": 31180, "text": "R2(a,b)Reflexive : No, because (a+a) is even.So R2 is not equivalence relation." }, { "code": null, "e": 31299, "s": 31260, "text": "Reflexive : No, because (a+a) is even." }, { "code": null, "e": 31461, "s": 31299, "text": "R3(a,b)Reflexive : Yes, because a.a > 0.Symmetrix : Yes, a.b > 0 ⟹ b.a > 0.Transitive : Yes, because a.b > 0 and b.c > 0 ⟹ a.c > 0.So R3 is equivalence relation." }, { "code": null, "e": 31495, "s": 31461, "text": "Reflexive : Yes, because a.a > 0." }, { "code": null, "e": 31531, "s": 31495, "text": "Symmetrix : Yes, a.b > 0 ⟹ b.a > 0." }, { "code": null, "e": 31588, "s": 31531, "text": "Transitive : Yes, because a.b > 0 and b.c > 0 ⟹ a.c > 0." }, { "code": null, "e": 31770, "s": 31588, "text": "R4(a,b)Reflexive : Yes, because |a-a| ≤ 2.Symmetrix : Yes, |a-b| ≤ 2 ⟹ |b-a| ≤ 2.Transitive : No, because |a-b| ≤ 2 and |b-c| ≤ 2 ⇏ (a-c) is even.So R4 is not equivalence relation." }, { "code": null, "e": 31806, "s": 31770, "text": "Reflexive : Yes, because |a-a| ≤ 2." }, { "code": null, "e": 31846, "s": 31806, "text": "Symmetrix : Yes, |a-b| ≤ 2 ⟹ |b-a| ≤ 2." }, { "code": null, "e": 31913, "s": 31846, "text": "Transitive : No, because |a-b| ≤ 2 and |b-c| ≤ 2 ⇏ (a-c) is even." }, { "code": null, "e": 31983, "s": 31913, "text": "Consider two well-formed formulas in prepositional logic. F1 : P ⇒ ¬P" }, { "code": null, "e": 32003, "s": 31983, "text": "F2 : ( P⇒¬P)∨(¬P⇒P)" }, { "code": null, "e": 32054, "s": 32003, "text": "Which of the following statements is correct? " }, { "code": null, "e": 32086, "s": 32054, "text": "F1 and F2 are both satisfiable " }, { "code": null, "e": 32123, "s": 32086, "text": "F1 unsatisfiable, F2 is satisfiable " }, { "code": null, "e": 32158, "s": 32123, "text": "F1 is unsatisfiable, F2 is valid " }, { "code": null, "e": 32190, "s": 32158, "text": "F1 is satisfiable, F2 is valid " }, { "code": null, "e": 32743, "s": 32190, "text": "The concept behind this solution is: a) Satisfiable If there is an assignment of truth values which makes that expression true. b) UnSatisfiable If there is no such assignment which makes the expression true c) Valid If the expression is Tautology Here, P => Q is nothing but –P v Q F1: P => -P = -P v –P = -P F1 will be true if P is false and F1 will be false when P is true so F1 is Satisfiable F2: (P => -P) v (-P => P) which is equals to (-P v-P) v (-(-P) v P) = (-P) v (P) = Tautology So, F1 is Satisfiable and F2 is valid Option (a) is correct. " }, { "code": null, "e": 32841, "s": 32743, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 32915, "s": 32841, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 32968, "s": 32915, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 33016, "s": 32968, "text": "Git - Difference Between Git Fetch and Git Pull" }, { "code": null, "e": 33065, "s": 33016, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 33104, "s": 33065, "text": "How to Install and Use NVM on Windows?" }, { "code": null, "e": 33129, "s": 33104, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 33181, "s": 33129, "text": "Top 20 Puzzles Commonly Asked During SDE Interviews" }, { "code": null, "e": 33208, "s": 33181, "text": "Spring Boot - Architecture" }, { "code": null, "e": 33256, "s": 33208, "text": "Software Testing Metrics, its Types and Example" } ]
Find the winner in nim-game
14 Jun, 2022 You are given an array A[] of n-elements. There are two players Alice and Bob. A Player can choose any of element from array and remove it. If the bitwise XOR of all remaining elements equals 0 after removal of selected element, then that player loses. This problem is variation of nim-game. Note: Each player play game alternately. Find out winner if both of the players play optimally. Alice starts the game first. In case one-element in array consider its value as the XOR of array. Examples : Input : A[] = {3, 3, 2} Output : Winner = Bob Explanation : Alice can select 2 and remove it that make XOR of array equals to zero also if Alice choose 3 to remove than Bob can choose any of 2/3 and finally Alice have to make his steps. Input : A[] = {3, 3} Output : Winner = Alice Explanation : As XOR of array is already zero Alice can’t select any element to remove and hence Alice is winner. Let’s start the solution step by step. We have total of three option for the XOR of array and this game. XOR of array is already 0: In this case Alice will unable to make a move and hence Alice is winner.XOR of array is not zero: Now, in this case we have two options, either size of array will be odd or even.CASE A: If the array size is odd then for sure Bob will win the game.CASE B: If the array size is even then Alice will win the game. XOR of array is already 0: In this case Alice will unable to make a move and hence Alice is winner. XOR of array is not zero: Now, in this case we have two options, either size of array will be odd or even.CASE A: If the array size is odd then for sure Bob will win the game.CASE B: If the array size is even then Alice will win the game. CASE A: If the array size is odd then for sure Bob will win the game. CASE B: If the array size is even then Alice will win the game. Above conclusion can be proved with the help of mathematical induction.Let A[] = {1} i.e. size of array is odd and XOR of array is non-zero: In this case Alice can select element 1 and then A[] will become empty and hence XOR of array can be considered as zero. Resulting Bob as winner.Let size of array is even and XOR of array is non-zero. Now we can prove that Alice can always find an element to remove such that XOR of remaining elements of array will be non-zero. To prove this lets start from the contradiction i.e. suppose whatever element you should choose XOR of remaining array must be zero. So, let A1 Xor A2 Xor ... An = X and n is even. As per our contradiction hypothesis, Ai Xor X = 0 for 1<= i <= n. Calculate XOR of all X Xor Ai (i.e. n equations), After taking XOR of all n equations we have X Xor X...Xor X (n-times) = 0 as N is even. Now, also we have A1 Xor A2 Xor.. An = 0 but we know A1 Xor A2...Xor = X. This means we have at least one element in even-size array such that after its removal XOR of remaining elements in non-zero. Let size of array is even and XOR of array is non-zero. Alice can not remove an element Ai such that xor of remaining number is zero, because that will make Bob win. Now, take the other case when the xor of remaining N?1 number is non-zero. As we know that N?1 is even and from the induction hypothesis, we can say that the position after the current move will be a winning position for Bob. Hence, it is a losing position for Alice. int res = 0; for (int i = 1; i <= N; i++) { res ^= a[i]; } if (res == 0) return "ALice"; if (N%2 == 0) return "Alice"; else return "Bob"; C++ Java Python3 C# PHP Javascript // CPP to find nim-game winner#include <bits/stdc++.h>using namespace std; // function to find winner of NIM-gamestring findWinner(int A[], int n){ int res = 0; for (int i = 0; i < n; i++) res ^= A[i]; // case when Alice is winner if (res == 0 || n % 2 == 0) return "Alice"; // when Bob is winner else return "Bob";} // driver programint main(){ int A[] = { 1, 4, 3, 5 }; int n = sizeof(A) / sizeof(A[0]); cout << "Winner = " << findWinner(A, n); return 0;} // Java to find nim-game winnerclass GFG { // function to find winner of NIM-game static String findWinner(int A[], int n) { int res = 0; for (int i = 0; i < n; i++) res ^= A[i]; // case when Alice is winner if (res == 0 || n % 2 == 0) return "Alice"; // when Bob is winner else return "Bob"; } //Driver code public static void main (String[] args) { int A[] = { 1, 4, 3, 5 }; int n =A.length; System.out.print("Winner = " + findWinner(A, n)); }} // This code is contributed by Anant Agarwal. # Python3 program to find nim-game winner # Function to find winner of NIM-gamedef findWinner(A, n): res = 0 for i in range(n): res ^= A[i] # case when Alice is winner if (res == 0 or n % 2 == 0): return "Alice" # when Bob is winner else: return "Bob" # Driver codeA = [ 1, 4, 3, 5 ]n = len(A)print("Winner = ", findWinner(A, n)) # This code is contributed by Anant Agarwal. // C# to find nim-game winnerusing System; class GFG { // function to find winner of NIM-game static String findWinner(int []A, int n) { int res = 0; for (int i = 0; i < n; i++) res ^= A[i]; // case when Alice is winner if (res == 0 || n % 2 == 0) return "Alice"; // when Bob is winner else return "Bob"; } //Driver code public static void Main () { int []A = { 1, 4, 3, 5 }; int n =A.Length; Console.WriteLine("Winner = " + findWinner(A, n)); }} // This code is contributed by vt_m. <?php// PHP to find nim-game winner // function to find// winner of NIM-gamefunction findWinner($A, $n){ $res = 0; for ($i = 0; $i < $n; $i++) $res ^= $A[$i]; // case when Alice is winner if ($res == 0 or $n % 2 == 0) return "Alice"; // when Bob is winner else return "Bob";} // Driver Code$A = array(1, 4, 3, 5 );$n = count($A);echo "Winner = " , findWinner($A, $n); // This code is contributed by vt_m.?> <script> // JavaScript program to find nim-game winner // function to find winner of NIM-game function findWinner(A, n) { let res = 0; for (let i = 0; i < n; i++) res ^= A[i]; // case when Alice is winner if (res == 0 || n % 2 == 0) return "Alice"; // when Bob is winner else return "Bob"; } // Driver Code let A = [ 1, 4, 3, 5 ]; let n = A.length; document.write("Winner = " + findWinner(A, n)); </script> Output : Winner = Alice Time Complexity : O(N) Where N is the given size of the array. As we are traversing the array in a single for loop for N elements. Hence time complexity is O(N). Auxiliary Space : O( 1 ) as we are not utilizing any extra space in memory so space needed is constant vt_m avijitmondal1998 arorakashish0911 SauravKumarGupta simmytarika5 devendrasalunke Bitwise-XOR Bit Magic Game Theory Bit Magic Game Theory Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Divide two integers without using multiplication, division and mod operator Bit Fields in C Set, Clear and Toggle a given bit of a number in C Find the two non-repeating elements in an array of repeating elements/ Unique Numbers 2 Count total set bits in all numbers from 1 to n Implementation of Tic-Tac-Toe game Minimax Algorithm in Game Theory | Set 2 (Introduction to Evaluation Function) Card Shuffle Problem | TCS Digital Advanced Coding Question Chessboard Pawn-Pawn game Expectimax Algorithm in Game Theory
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Jun, 2022" }, { "code": null, "e": 345, "s": 52, "text": "You are given an array A[] of n-elements. There are two players Alice and Bob. A Player can choose any of element from array and remove it. If the bitwise XOR of all remaining elements equals 0 after removal of selected element, then that player loses. This problem is variation of nim-game. " }, { "code": null, "e": 540, "s": 345, "text": "Note: Each player play game alternately. Find out winner if both of the players play optimally. Alice starts the game first. In case one-element in array consider its value as the XOR of array. " }, { "code": null, "e": 553, "s": 540, "text": "Examples : " }, { "code": null, "e": 790, "s": 553, "text": "Input : A[] = {3, 3, 2} Output : Winner = Bob Explanation : Alice can select 2 and remove it that make XOR of array equals to zero also if Alice choose 3 to remove than Bob can choose any of 2/3 and finally Alice have to make his steps." }, { "code": null, "e": 951, "s": 790, "text": "Input : A[] = {3, 3} Output : Winner = Alice Explanation : As XOR of array is already zero Alice can’t select any element to remove and hence Alice is winner. " }, { "code": null, "e": 1058, "s": 951, "text": "Let’s start the solution step by step. We have total of three option for the XOR of array and this game. " }, { "code": null, "e": 1396, "s": 1058, "text": "XOR of array is already 0: In this case Alice will unable to make a move and hence Alice is winner.XOR of array is not zero: Now, in this case we have two options, either size of array will be odd or even.CASE A: If the array size is odd then for sure Bob will win the game.CASE B: If the array size is even then Alice will win the game." }, { "code": null, "e": 1496, "s": 1396, "text": "XOR of array is already 0: In this case Alice will unable to make a move and hence Alice is winner." }, { "code": null, "e": 1735, "s": 1496, "text": "XOR of array is not zero: Now, in this case we have two options, either size of array will be odd or even.CASE A: If the array size is odd then for sure Bob will win the game.CASE B: If the array size is even then Alice will win the game." }, { "code": null, "e": 1805, "s": 1735, "text": "CASE A: If the array size is odd then for sure Bob will win the game." }, { "code": null, "e": 1869, "s": 1805, "text": "CASE B: If the array size is even then Alice will win the game." }, { "code": null, "e": 2340, "s": 1869, "text": "Above conclusion can be proved with the help of mathematical induction.Let A[] = {1} i.e. size of array is odd and XOR of array is non-zero: In this case Alice can select element 1 and then A[] will become empty and hence XOR of array can be considered as zero. Resulting Bob as winner.Let size of array is even and XOR of array is non-zero. Now we can prove that Alice can always find an element to remove such that XOR of remaining elements of array will be non-zero. " }, { "code": null, "e": 2925, "s": 2340, "text": "To prove this lets start from the contradiction i.e. suppose whatever element you should choose XOR of remaining array must be zero. So, let A1 Xor A2 Xor ... An = X and n is even. As per our contradiction hypothesis, Ai Xor X = 0 for 1<= i <= n. Calculate XOR of all X Xor Ai (i.e. n equations), After taking XOR of all n equations we have X Xor X...Xor X (n-times) = 0 as N is even. Now, also we have A1 Xor A2 Xor.. An = 0 but we know A1 Xor A2...Xor = X. This means we have at least one element in even-size array such that after its removal XOR of remaining elements in non-zero." }, { "code": null, "e": 3359, "s": 2925, "text": "Let size of array is even and XOR of array is non-zero. Alice can not remove an element Ai such that xor of remaining number is zero, because that will make Bob win. Now, take the other case when the xor of remaining N?1 number is non-zero. As we know that N?1 is even and from the induction hypothesis, we can say that the position after the current move will be a winning position for Bob. Hence, it is a losing position for Alice." }, { "code": null, "e": 3514, "s": 3359, "text": "int res = 0;\nfor (int i = 1; i <= N; i++) {\n res ^= a[i];\n}\n\nif (res == 0)\n return \"ALice\";\nif (N%2 == 0)\n return \"Alice\";\nelse\n return \"Bob\";" }, { "code": null, "e": 3518, "s": 3514, "text": "C++" }, { "code": null, "e": 3523, "s": 3518, "text": "Java" }, { "code": null, "e": 3531, "s": 3523, "text": "Python3" }, { "code": null, "e": 3534, "s": 3531, "text": "C#" }, { "code": null, "e": 3538, "s": 3534, "text": "PHP" }, { "code": null, "e": 3549, "s": 3538, "text": "Javascript" }, { "code": "// CPP to find nim-game winner#include <bits/stdc++.h>using namespace std; // function to find winner of NIM-gamestring findWinner(int A[], int n){ int res = 0; for (int i = 0; i < n; i++) res ^= A[i]; // case when Alice is winner if (res == 0 || n % 2 == 0) return \"Alice\"; // when Bob is winner else return \"Bob\";} // driver programint main(){ int A[] = { 1, 4, 3, 5 }; int n = sizeof(A) / sizeof(A[0]); cout << \"Winner = \" << findWinner(A, n); return 0;}", "e": 4060, "s": 3549, "text": null }, { "code": "// Java to find nim-game winnerclass GFG { // function to find winner of NIM-game static String findWinner(int A[], int n) { int res = 0; for (int i = 0; i < n; i++) res ^= A[i]; // case when Alice is winner if (res == 0 || n % 2 == 0) return \"Alice\"; // when Bob is winner else return \"Bob\"; } //Driver code public static void main (String[] args) { int A[] = { 1, 4, 3, 5 }; int n =A.length; System.out.print(\"Winner = \" + findWinner(A, n)); }} // This code is contributed by Anant Agarwal.", "e": 4730, "s": 4060, "text": null }, { "code": "# Python3 program to find nim-game winner # Function to find winner of NIM-gamedef findWinner(A, n): res = 0 for i in range(n): res ^= A[i] # case when Alice is winner if (res == 0 or n % 2 == 0): return \"Alice\" # when Bob is winner else: return \"Bob\" # Driver codeA = [ 1, 4, 3, 5 ]n = len(A)print(\"Winner = \", findWinner(A, n)) # This code is contributed by Anant Agarwal.", "e": 5147, "s": 4730, "text": null }, { "code": "// C# to find nim-game winnerusing System; class GFG { // function to find winner of NIM-game static String findWinner(int []A, int n) { int res = 0; for (int i = 0; i < n; i++) res ^= A[i]; // case when Alice is winner if (res == 0 || n % 2 == 0) return \"Alice\"; // when Bob is winner else return \"Bob\"; } //Driver code public static void Main () { int []A = { 1, 4, 3, 5 }; int n =A.Length; Console.WriteLine(\"Winner = \" + findWinner(A, n)); }} // This code is contributed by vt_m.", "e": 5808, "s": 5147, "text": null }, { "code": "<?php// PHP to find nim-game winner // function to find// winner of NIM-gamefunction findWinner($A, $n){ $res = 0; for ($i = 0; $i < $n; $i++) $res ^= $A[$i]; // case when Alice is winner if ($res == 0 or $n % 2 == 0) return \"Alice\"; // when Bob is winner else return \"Bob\";} // Driver Code$A = array(1, 4, 3, 5 );$n = count($A);echo \"Winner = \" , findWinner($A, $n); // This code is contributed by vt_m.?>", "e": 6256, "s": 5808, "text": null }, { "code": "<script> // JavaScript program to find nim-game winner // function to find winner of NIM-game function findWinner(A, n) { let res = 0; for (let i = 0; i < n; i++) res ^= A[i]; // case when Alice is winner if (res == 0 || n % 2 == 0) return \"Alice\"; // when Bob is winner else return \"Bob\"; } // Driver Code let A = [ 1, 4, 3, 5 ]; let n = A.length; document.write(\"Winner = \" + findWinner(A, n)); </script>", "e": 6831, "s": 6256, "text": null }, { "code": null, "e": 6841, "s": 6831, "text": "Output : " }, { "code": null, "e": 6856, "s": 6841, "text": "Winner = Alice" }, { "code": null, "e": 7019, "s": 6856, "text": "Time Complexity : O(N) Where N is the given size of the array. As we are traversing the array in a single for loop for N elements. Hence time complexity is O(N)." }, { "code": null, "e": 7122, "s": 7019, "text": "Auxiliary Space : O( 1 ) as we are not utilizing any extra space in memory so space needed is constant" }, { "code": null, "e": 7127, "s": 7122, "text": "vt_m" }, { "code": null, "e": 7144, "s": 7127, "text": "avijitmondal1998" }, { "code": null, "e": 7161, "s": 7144, "text": "arorakashish0911" }, { "code": null, "e": 7178, "s": 7161, "text": "SauravKumarGupta" }, { "code": null, "e": 7191, "s": 7178, "text": "simmytarika5" }, { "code": null, "e": 7207, "s": 7191, "text": "devendrasalunke" }, { "code": null, "e": 7219, "s": 7207, "text": "Bitwise-XOR" }, { "code": null, "e": 7229, "s": 7219, "text": "Bit Magic" }, { "code": null, "e": 7241, "s": 7229, "text": "Game Theory" }, { "code": null, "e": 7251, "s": 7241, "text": "Bit Magic" }, { "code": null, "e": 7263, "s": 7251, "text": "Game Theory" }, { "code": null, "e": 7361, "s": 7263, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7437, "s": 7361, "text": "Divide two integers without using multiplication, division and mod operator" }, { "code": null, "e": 7453, "s": 7437, "text": "Bit Fields in C" }, { "code": null, "e": 7504, "s": 7453, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 7592, "s": 7504, "text": "Find the two non-repeating elements in an array of repeating elements/ Unique Numbers 2" }, { "code": null, "e": 7640, "s": 7592, "text": "Count total set bits in all numbers from 1 to n" }, { "code": null, "e": 7675, "s": 7640, "text": "Implementation of Tic-Tac-Toe game" }, { "code": null, "e": 7754, "s": 7675, "text": "Minimax Algorithm in Game Theory | Set 2 (Introduction to Evaluation Function)" }, { "code": null, "e": 7814, "s": 7754, "text": "Card Shuffle Problem | TCS Digital Advanced Coding Question" }, { "code": null, "e": 7840, "s": 7814, "text": "Chessboard Pawn-Pawn game" } ]
Fabric.js | Rect moveCursor Property
25 May, 2020 In this article, we are going to see how to set the moveCursor property of a rectangle canvas using FabricJS. When we move the canvas object then the cursor will be changed. The canvas rectangle means rectangle is movable and can be stretched according to requirement. Further, the rectangle can be customized when it comes to initial stroke color, height, width, fill color, or stroke width. To make it possible, we are going to use a JavaScript library called FabricJS. After importing the library, we will create a canvas block in the body tag which will contain the rectangle. After this, we will initialize instances of Canvas and Rectangle provided by FabricJS and set the move cursor value of canvas rectangle using moveCursor property and render the Rectangle on the Canvas as given in the below example. Syntax: fabric.Rect({ width: number, height: number, moveCursor: string }); Parameters: This function accepts three parameters as mentioned above and described below: width: It specifies the width of rectangle. height: It specifies the height of rectangle. moveCursor: It specifies that the cursor value when moving the canvas object. Example: This example uses FabricJS to set the moveCursor value that will works when the object moving. <!DOCTYPE html> <html> <head> <title> Fabric.js | Rect moveCursor Property </title> <!-- Adding the FabricJS library --> <script src= "https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"> </script> </head> <body> <div style="text-align: center;width: 600px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <b> Fabric.js | Rect moveCursor Property </b> </div> <canvas id="canvas" width="600" height="200" style="border:1px solid #000000"> </canvas> <script> // Initiate a Canvas instance var canvas = new fabric.Canvas("canvas"); // Initiate a Rect instance var rectangle = new fabric.Rect({ width: 200, height: 100, fill: '', stroke: 'green', strokeWidth: 3, moveCursor: 'pointer' }); // Render the Rect in canvas canvas.add(rectangle); canvas.centerObject(rectangle); </script> </body> </html> Output: Fabric.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": "\n25 May, 2020" }, { "code": null, "e": 421, "s": 28, "text": "In this article, we are going to see how to set the moveCursor property of a rectangle canvas using FabricJS. When we move the canvas object then the cursor will be changed. The canvas rectangle means rectangle is movable and can be stretched according to requirement. Further, the rectangle can be customized when it comes to initial stroke color, height, width, fill color, or stroke width." }, { "code": null, "e": 841, "s": 421, "text": "To make it possible, we are going to use a JavaScript library called FabricJS. After importing the library, we will create a canvas block in the body tag which will contain the rectangle. After this, we will initialize instances of Canvas and Rectangle provided by FabricJS and set the move cursor value of canvas rectangle using moveCursor property and render the Rectangle on the Canvas as given in the below example." }, { "code": null, "e": 849, "s": 841, "text": "Syntax:" }, { "code": null, "e": 929, "s": 849, "text": "fabric.Rect({\n width: number,\n height: number,\n moveCursor: string\n});" }, { "code": null, "e": 1020, "s": 929, "text": "Parameters: This function accepts three parameters as mentioned above and described below:" }, { "code": null, "e": 1064, "s": 1020, "text": "width: It specifies the width of rectangle." }, { "code": null, "e": 1110, "s": 1064, "text": "height: It specifies the height of rectangle." }, { "code": null, "e": 1188, "s": 1110, "text": "moveCursor: It specifies that the cursor value when moving the canvas object." }, { "code": null, "e": 1292, "s": 1188, "text": "Example: This example uses FabricJS to set the moveCursor value that will works when the object moving." }, { "code": "<!DOCTYPE html> <html> <head> <title> Fabric.js | Rect moveCursor Property </title> <!-- Adding the FabricJS library --> <script src= \"https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js\"> </script> </head> <body> <div style=\"text-align: center;width: 600px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <b> Fabric.js | Rect moveCursor Property </b> </div> <canvas id=\"canvas\" width=\"600\" height=\"200\" style=\"border:1px solid #000000\"> </canvas> <script> // Initiate a Canvas instance var canvas = new fabric.Canvas(\"canvas\"); // Initiate a Rect instance var rectangle = new fabric.Rect({ width: 200, height: 100, fill: '', stroke: 'green', strokeWidth: 3, moveCursor: 'pointer' }); // Render the Rect in canvas canvas.add(rectangle); canvas.centerObject(rectangle); </script> </body> </html>", "e": 2384, "s": 1292, "text": null }, { "code": null, "e": 2392, "s": 2384, "text": "Output:" }, { "code": null, "e": 2402, "s": 2392, "text": "Fabric.js" }, { "code": null, "e": 2413, "s": 2402, "text": "JavaScript" }, { "code": null, "e": 2430, "s": 2413, "text": "Web Technologies" } ]
Maximise the number of toys that can be purchased with amount K
27 May, 2021 Given an array consisting of the cost of toys. Given an integer K depicting the amount of money available to purchase toys. Write a program to find the maximum number of toys one can buy with the amount K. Note: One can buy only 1 quantity of a particular toy. Examples: Input: N = 10, K = 50 cost = { 1, 12, 5, 111, 200, 1000, 10, 9, 12, 15 } Output: 6 Explanation: Toys with amount 1, 5, 9, 10, 12, and 12 can be purchased resulting in a total amount of 49. Hence, maximum number of toys is 6. Input: N = 7, K = 50 cost = { 1, 12, 5, 111, 200, 1000, 10 } Output: 4 The idea to solve this problem is to first sort the cost array in ascending order. This will arrange the toys in increasing order of cost. Now iterate over the cost array and keep calculating the sum of costs until the sum is less than or equal to K. Finally, return the number of toys used to calculate the sum which is just less than or equals to K. The image below is an illustration of the above approach: Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ Program to maximize the// number of toys with K amount#include <bits/stdc++.h>using namespace std; // This functions returns the required// number of toysint maximum_toys(int cost[], int N, int K){ int count = 0, sum = 0; // sort the cost array sort(cost, cost + N); for (int i = 0; i < N; i++) { // Check if we can buy ith toy or not if (sum +cost[i] <= K) { sum = sum + cost[i]; // Increment count count++; } } return count;} // Driver Codeint main(){ int K = 50; int cost[] = { 1, 12, 5, 111, 200, 1000, 10, 9, 12, 15 }; int N = sizeof(cost) / sizeof(cost[0]); cout << maximum_toys(cost, N, K) << endl; return 0;} // Java Program to maximize the// number of toys with K amountimport java.io.*;import java .util.*; class GFG{// This functions returns// the required number of toysstatic int maximum_toys(int cost[], int N, int K){ int count = 0, sum = 0; // sort the cost array Arrays.sort(cost); for (int i = 0; i < N; i++) { // Check if we can buy ith toy or not if (sum +cost[i] <= K) { sum = sum + cost[i]; // Increment count count++; } } return count;} // Driver Codepublic static void main (String[] args){int K = 50;int cost[] = {1, 12, 5, 111, 200, 1000, 10, 9, 12, 15};int N = cost.length; System.out.print( maximum_toys(cost, N, K));}} // This code is contributed by anuj_67. # Python 3 Program to maximize the# number of toys with K amount # This functions returns the required# number of toysdef maximum_toys(cost, N, K): count = 0 sum = 0 # sort the cost array cost.sort(reverse = False) for i in range(0, N, 1): # Check if we can buy ith toy or not if (sum+cost[i] <= K): sum = sum + cost[i] # Increment the count variable count += 1 return count # Driver Codeif __name__ == '__main__': K = 50 cost = [1, 12, 5, 111, 200, 1000, 10, 9, 12, 15] N = len(cost) print(maximum_toys(cost, N, K)) # This code is contributed by# Sanjit_Prasad // C# Program to maximize the// number of toys with K amountusing System; class GFG{// This functions returns// the required number of toysstatic int maximum_toys(int []cost, int N, int K){ int count = 0, sum = 0; // sort the cost array Array.Sort(cost); for (int i = 0; i < N; i++) { // Check if we can buy ith toy or not if (sum +cost[i] <= K) { sum = sum + cost[i]; // Increment count count++; } } return count;} // Driver Codepublic static void Main (){int K = 50;int []cost = {1, 12, 5, 111, 200, 1000, 10, 9, 12, 15};int N = cost.Length; Console.Write( maximum_toys(cost, N, K));}} // This code is contributed by anuj_67. <?php// PHP Program to maximize the// number of toys with K amount // This functions returns// the required number of toysfunction maximum_toys($cost, $N, $K){ $count = 0; $sum = 0; // sort the cost array sort($cost); for ($i = 0; $i < $N; $i++) { // Check if we can buy ith toy or not if ($sum + $cost[$i] <= $K) { $sum = $sum + $cost[$i]; // Increment the count variable $count++; } } return $count;} // Driver Code$K = 50;$cost = array(1, 12, 5, 111, 200, 1000, 10, 9, 12, 15 );$N = count($cost); echo maximum_toys($cost, $N, $K),"\n"; // This code is contributed by anuj_67?> <script> // Javascript Program to maximize the // number of toys with K amount // This functions returns // the required number of toys function maximum_toys(cost, N, K) { let count = 0, sum = 0; // sort the cost array cost.sort(function(a, b){return a - b}); for (let i = 0; i < N; i++) { // Check if we can buy ith toy or not if (sum +cost[i] <= K) { sum = sum + cost[i]; // Increment count count++; } } return count; } let K = 50; let cost = [1, 12, 5, 111, 200, 1000, 10, 9, 12, 15]; let N = cost.length; document.write(maximum_toys(cost, N, K)); </script> 6 Time Complexity: O(N * logN), where N is the size of the cost array. vt_m Sanjit_Prasad divyeshrabadiya07 Sorting Quiz Arrays Sorting Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Merge Sort Bubble Sort Algorithm QuickSort Insertion Sort Selection Sort Algorithm
[ { "code": null, "e": 52, "s": 24, "text": "\n27 May, 2021" }, { "code": null, "e": 313, "s": 52, "text": "Given an array consisting of the cost of toys. Given an integer K depicting the amount of money available to purchase toys. Write a program to find the maximum number of toys one can buy with the amount K. Note: One can buy only 1 quantity of a particular toy." }, { "code": null, "e": 325, "s": 313, "text": "Examples: " }, { "code": null, "e": 641, "s": 325, "text": "Input: N = 10, K = 50\n cost = { 1, 12, 5, 111, 200, 1000, 10, 9, 12, 15 }\nOutput: 6\nExplanation: Toys with amount 1, 5, 9, 10, 12, and 12 \ncan be purchased resulting in a total amount of 49. Hence,\nmaximum number of toys is 6.\n\nInput: N = 7, K = 50\n cost = { 1, 12, 5, 111, 200, 1000, 10 }\nOutput: 4 " }, { "code": null, "e": 993, "s": 641, "text": "The idea to solve this problem is to first sort the cost array in ascending order. This will arrange the toys in increasing order of cost. Now iterate over the cost array and keep calculating the sum of costs until the sum is less than or equal to K. Finally, return the number of toys used to calculate the sum which is just less than or equals to K." }, { "code": null, "e": 1053, "s": 993, "text": "The image below is an illustration of the above approach: " }, { "code": null, "e": 1106, "s": 1053, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1110, "s": 1106, "text": "C++" }, { "code": null, "e": 1115, "s": 1110, "text": "Java" }, { "code": null, "e": 1123, "s": 1115, "text": "Python3" }, { "code": null, "e": 1126, "s": 1123, "text": "C#" }, { "code": null, "e": 1130, "s": 1126, "text": "PHP" }, { "code": null, "e": 1141, "s": 1130, "text": "Javascript" }, { "code": "// C++ Program to maximize the// number of toys with K amount#include <bits/stdc++.h>using namespace std; // This functions returns the required// number of toysint maximum_toys(int cost[], int N, int K){ int count = 0, sum = 0; // sort the cost array sort(cost, cost + N); for (int i = 0; i < N; i++) { // Check if we can buy ith toy or not if (sum +cost[i] <= K) { sum = sum + cost[i]; // Increment count count++; } } return count;} // Driver Codeint main(){ int K = 50; int cost[] = { 1, 12, 5, 111, 200, 1000, 10, 9, 12, 15 }; int N = sizeof(cost) / sizeof(cost[0]); cout << maximum_toys(cost, N, K) << endl; return 0;}", "e": 1862, "s": 1141, "text": null }, { "code": "// Java Program to maximize the// number of toys with K amountimport java.io.*;import java .util.*; class GFG{// This functions returns// the required number of toysstatic int maximum_toys(int cost[], int N, int K){ int count = 0, sum = 0; // sort the cost array Arrays.sort(cost); for (int i = 0; i < N; i++) { // Check if we can buy ith toy or not if (sum +cost[i] <= K) { sum = sum + cost[i]; // Increment count count++; } } return count;} // Driver Codepublic static void main (String[] args){int K = 50;int cost[] = {1, 12, 5, 111, 200, 1000, 10, 9, 12, 15};int N = cost.length; System.out.print( maximum_toys(cost, N, K));}} // This code is contributed by anuj_67.", "e": 2651, "s": 1862, "text": null }, { "code": "# Python 3 Program to maximize the# number of toys with K amount # This functions returns the required# number of toysdef maximum_toys(cost, N, K): count = 0 sum = 0 # sort the cost array cost.sort(reverse = False) for i in range(0, N, 1): # Check if we can buy ith toy or not if (sum+cost[i] <= K): sum = sum + cost[i] # Increment the count variable count += 1 return count # Driver Codeif __name__ == '__main__': K = 50 cost = [1, 12, 5, 111, 200, 1000, 10, 9, 12, 15] N = len(cost) print(maximum_toys(cost, N, K)) # This code is contributed by# Sanjit_Prasad", "e": 3317, "s": 2651, "text": null }, { "code": "// C# Program to maximize the// number of toys with K amountusing System; class GFG{// This functions returns// the required number of toysstatic int maximum_toys(int []cost, int N, int K){ int count = 0, sum = 0; // sort the cost array Array.Sort(cost); for (int i = 0; i < N; i++) { // Check if we can buy ith toy or not if (sum +cost[i] <= K) { sum = sum + cost[i]; // Increment count count++; } } return count;} // Driver Codepublic static void Main (){int K = 50;int []cost = {1, 12, 5, 111, 200, 1000, 10, 9, 12, 15};int N = cost.Length; Console.Write( maximum_toys(cost, N, K));}} // This code is contributed by anuj_67.", "e": 4063, "s": 3317, "text": null }, { "code": "<?php// PHP Program to maximize the// number of toys with K amount // This functions returns// the required number of toysfunction maximum_toys($cost, $N, $K){ $count = 0; $sum = 0; // sort the cost array sort($cost); for ($i = 0; $i < $N; $i++) { // Check if we can buy ith toy or not if ($sum + $cost[$i] <= $K) { $sum = $sum + $cost[$i]; // Increment the count variable $count++; } } return $count;} // Driver Code$K = 50;$cost = array(1, 12, 5, 111, 200, 1000, 10, 9, 12, 15 );$N = count($cost); echo maximum_toys($cost, $N, $K),\"\\n\"; // This code is contributed by anuj_67?>", "e": 4746, "s": 4063, "text": null }, { "code": "<script> // Javascript Program to maximize the // number of toys with K amount // This functions returns // the required number of toys function maximum_toys(cost, N, K) { let count = 0, sum = 0; // sort the cost array cost.sort(function(a, b){return a - b}); for (let i = 0; i < N; i++) { // Check if we can buy ith toy or not if (sum +cost[i] <= K) { sum = sum + cost[i]; // Increment count count++; } } return count; } let K = 50; let cost = [1, 12, 5, 111, 200, 1000, 10, 9, 12, 15]; let N = cost.length; document.write(maximum_toys(cost, N, K)); </script>", "e": 5491, "s": 4746, "text": null }, { "code": null, "e": 5493, "s": 5491, "text": "6" }, { "code": null, "e": 5565, "s": 5495, "text": "Time Complexity: O(N * logN), where N is the size of the cost array. " }, { "code": null, "e": 5570, "s": 5565, "text": "vt_m" }, { "code": null, "e": 5584, "s": 5570, "text": "Sanjit_Prasad" }, { "code": null, "e": 5602, "s": 5584, "text": "divyeshrabadiya07" }, { "code": null, "e": 5615, "s": 5602, "text": "Sorting Quiz" }, { "code": null, "e": 5622, "s": 5615, "text": "Arrays" }, { "code": null, "e": 5630, "s": 5622, "text": "Sorting" }, { "code": null, "e": 5637, "s": 5630, "text": "Arrays" }, { "code": null, "e": 5645, "s": 5637, "text": "Sorting" }, { "code": null, "e": 5743, "s": 5645, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5811, "s": 5743, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 5855, "s": 5811, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 5887, "s": 5855, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 5935, "s": 5887, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 5949, "s": 5935, "text": "Linear Search" }, { "code": null, "e": 5960, "s": 5949, "text": "Merge Sort" }, { "code": null, "e": 5982, "s": 5960, "text": "Bubble Sort Algorithm" }, { "code": null, "e": 5992, "s": 5982, "text": "QuickSort" }, { "code": null, "e": 6007, "s": 5992, "text": "Insertion Sort" } ]
C++ Program to convert Octal Number to Decimal and vice-versa
In a computer system, the octal number is expressed in the octal numeral system while the decimal number is in the decimal numeral system. The octal number is in base 8 while the decimal number is in base 10. Examples of decimal numbers and their corresponding octal numbers are as follows. A program that converts the octal numbers into decimal and the decimal numbers into octal is as follows − Live Demo #include <iostream> #include <cmath> using namespace std; void DecimalToOctal(int decimalNum) { int octalNum = 0, placeValue = 1; int dNo = decimalNum; while (decimalNum != 0) { octalNum += (decimalNum % 8) * placeValue; decimalNum /= 8; placeValue *= 10; } cout<<"Octal form of decimal number "<<dNo<<" is "<<octalNum<<endl; } void OctalToDecimal(int octalNum) { int decimalNum = 0, power = 0; int oNo = octalNum; while(octalNum != 0) { decimalNum += (octalNum%10) * pow(8,power); ++power; octalNum/=10; } cout<<"Decimal form of octal number "<<oNo<<" is "<<decimalNum<<endl; } int main() { DecimalToOctal(20); OctalToDecimal(32); return 0; } Octal form of decimal number 20 is 24 Decimal form of octal number 32 is 26 In the above program, the function DecimalToOctal convert the decimal numbers into octal and the function OctalToDecimal converts octal numbers into decimal. In the function DecimalToOctal, initially the variable octalNum is initialized to zero. The variable placeValue denotes the location of the digit in the number. The value of octalNum is found using a while loop. For each iteration of the while loop, the decimalNum is divided by 8 and the remainder is multiplied by placeValue. This is added to the previous value of octalNum. Also decimalNum is divided by 8 and the quotient is stored back. placeValue is multiplied by 10. A code snippet that demonstrates this is as follows. while (decimalNum != 0) { octalNum += (decimalNum % 8) * placeValue; decimalNum /= 8; placeValue *= 10; } After the Octal value i.e octalNum is ovbtained, it is displayed. This is given below − cout<<"Octal form of decimal number "<<dNo<<" is "<<octalNum<<endl; In the function OctalToDecimal, in each iteration of the while loop octalNum is divided by 8 and the remainder is multiplied by 8 raised to power. This is added to the previous value of decimalNum. Power is incremented by 1 and octalNum is divided by 10. This is demonstrated as follows. while(octalNum != 0) { decimalNum += (octalNum%10) * pow(8,power); ++power; octalNum/=10; } After the value of decimalNum is found, it is displayed. This is seen as follows. cout<<"Decimal form of octal number "<<oNo<<" is "<<decimalNum<<endl; The main() function only contains the function calls to DecimalToOctal() and OctalToDecimal() with the required values. This is demonstrated by the following code snippet. DecimalToOctal(20); OctalToDecimal(32);
[ { "code": null, "e": 1271, "s": 1062, "text": "In a computer system, the octal number is expressed in the octal numeral system while the decimal number is in the decimal numeral system. The octal number is in base 8 while the decimal number is in base 10." }, { "code": null, "e": 1353, "s": 1271, "text": "Examples of decimal numbers and their corresponding octal numbers are as follows." }, { "code": null, "e": 1459, "s": 1353, "text": "A program that converts the octal numbers into decimal and the decimal numbers into octal is as follows −" }, { "code": null, "e": 1470, "s": 1459, "text": " Live Demo" }, { "code": null, "e": 2186, "s": 1470, "text": "#include <iostream>\n#include <cmath>\nusing namespace std;\nvoid DecimalToOctal(int decimalNum) {\n int octalNum = 0, placeValue = 1;\n int dNo = decimalNum;\n while (decimalNum != 0) {\n octalNum += (decimalNum % 8) * placeValue;\n decimalNum /= 8;\n placeValue *= 10;\n }\ncout<<\"Octal form of decimal number \"<<dNo<<\" is \"<<octalNum<<endl;\n}\nvoid OctalToDecimal(int octalNum) {\n int decimalNum = 0, power = 0;\n int oNo = octalNum;\n while(octalNum != 0) {\n decimalNum += (octalNum%10) * pow(8,power);\n ++power;\n octalNum/=10;\n }\n cout<<\"Decimal form of octal number \"<<oNo<<\" is \"<<decimalNum<<endl;\n}\nint main() {\n DecimalToOctal(20);\n OctalToDecimal(32);\n return 0;\n}" }, { "code": null, "e": 2262, "s": 2186, "text": "Octal form of decimal number 20 is 24\nDecimal form of octal number 32 is 26" }, { "code": null, "e": 2420, "s": 2262, "text": "In the above program, the function DecimalToOctal convert the decimal numbers into octal and the function OctalToDecimal converts octal numbers into decimal." }, { "code": null, "e": 2632, "s": 2420, "text": "In the function DecimalToOctal, initially the variable octalNum is initialized to zero. The variable placeValue denotes the location of the digit in the number. The value of octalNum is found using a while loop." }, { "code": null, "e": 2894, "s": 2632, "text": "For each iteration of the while loop, the decimalNum is divided by 8 and the remainder is multiplied by placeValue. This is added to the previous value of octalNum. Also decimalNum is divided by 8 and the quotient is stored back. placeValue is multiplied by 10." }, { "code": null, "e": 2947, "s": 2894, "text": "A code snippet that demonstrates this is as follows." }, { "code": null, "e": 3062, "s": 2947, "text": "while (decimalNum != 0) {\n octalNum += (decimalNum % 8) * placeValue;\n decimalNum /= 8;\n placeValue *= 10;\n}" }, { "code": null, "e": 3150, "s": 3062, "text": "After the Octal value i.e octalNum is ovbtained, it is displayed. This is given below −" }, { "code": null, "e": 3218, "s": 3150, "text": "cout<<\"Octal form of decimal number \"<<dNo<<\" is \"<<octalNum<<endl;" }, { "code": null, "e": 3506, "s": 3218, "text": "In the function OctalToDecimal, in each iteration of the while loop octalNum is divided by 8 and the remainder is multiplied by 8 raised to power. This is added to the previous value of decimalNum. Power is incremented by 1 and octalNum is divided by 10. This is demonstrated as follows." }, { "code": null, "e": 3607, "s": 3506, "text": "while(octalNum != 0) {\n decimalNum += (octalNum%10) * pow(8,power);\n ++power;\n octalNum/=10;\n}" }, { "code": null, "e": 3689, "s": 3607, "text": "After the value of decimalNum is found, it is displayed. This is seen as follows." }, { "code": null, "e": 3759, "s": 3689, "text": "cout<<\"Decimal form of octal number \"<<oNo<<\" is \"<<decimalNum<<endl;" }, { "code": null, "e": 3931, "s": 3759, "text": "The main() function only contains the function calls to DecimalToOctal() and OctalToDecimal() with the required values. This is demonstrated by the following code snippet." }, { "code": null, "e": 3971, "s": 3931, "text": "DecimalToOctal(20);\nOctalToDecimal(32);" } ]
Angular 4 - Routing
Routing basically means navigating between pages. You have seen many sites with links that direct you to a new page. This can be achieved using routing. Here the pages that we are referring to will be in the form of components. We have already seen how to create a component. Let us now create a component and see how to use routing with it. In the main parent component app.module.ts, we have to now include the router module as shown below − import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RouterModule} from '@angular/router'; import { AppComponent } from './app.component'; import { NewCmpComponent } from './new-cmp/new-cmp.component'; import { ChangeTextDirective } from './change-text.directive'; import { SqrtPipe } from './app.sqrt'; @NgModule({ declarations: [ SqrtPipe, AppComponent, NewCmpComponent, ChangeTextDirective ], imports: [ BrowserModule, RouterModule.forRoot([ { path: 'new-cmp', component: NewCmpComponent } ]) ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Here, the RouterModule is imported from angular/router. The module is included in the imports as shown below − RouterModule.forRoot([ { path: 'new-cmp', component: NewCmpComponent } ]) RouterModule refers to the forRoot which takes an input as an array, which in turn has the object of the path and the component. Path is the name of the router and component is the name of the class, i.e., the component created. Let us now see the component created file − import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-new-cmp', templateUrl: './new-cmp.component.html', styleUrls: ['./new-cmp.component.css'] }) export class NewCmpComponent implements OnInit { newcomponent = "Entered in new component created"; constructor() {} ngOnInit() { } } The highlighted class is mentioned in the imports of the main module. <p> {{newcomponent}} </p> <p> new-cmp works! </p> Now, we need the above content from the html file to be displayed whenever required or clicked from the main module. For this, we need to add the router details in the app.component.html. <h1>Custom Pipe</h1> <b>Square root of 25 is: {{25 | sqrt}}</b><br/> <b>Square root of 729 is: {{729 | sqrt}}</b> <br /> <br /> <br /> <a routerLink = "new-cmp">New component</a> <br /> <br/> <router-outlet></router-outlet> In the above code, we have created the anchor link tag and given routerLink as “new-cmp”. This is referred in app.module.ts as the path. When a user clicks new component, the page should display the content. For this, we need the following tag - <router-outlet> </router-outlet>. The above tag ensures that the content in the new-cmp.component.html will be displayed on the page when a user clicks new component. Let us now see how the output is displayed on the browser. When a user clicks New component, you will see the following in the browser. The url contains http://localhost:4200/new-cmp. Here, the new-cmp gets appended to the original url, which is the path given in the app.module.ts and the router-link in the app.component.html. When a user clicks New component, the page is not refreshed and the contents are shown to the user without any reloading. Only a particular piece of the site code will be reloaded when clicked. This feature helps when we have heavy content on the page and needs to be loaded based on the user interaction. The feature also gives a good user experience as the page is not reloaded. 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": 2334, "s": 1992, "text": "Routing basically means navigating between pages. You have seen many sites with links that direct you to a new page. This can be achieved using routing. Here the pages that we are referring to will be in the form of components. We have already seen how to create a component. Let us now create a component and see how to use routing with it." }, { "code": null, "e": 2436, "s": 2334, "text": "In the main parent component app.module.ts, we have to now include the router module as shown below −" }, { "code": null, "e": 3167, "s": 2436, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { RouterModule} from '@angular/router';\n\nimport { AppComponent } from './app.component';\nimport { NewCmpComponent } from './new-cmp/new-cmp.component';\nimport { ChangeTextDirective } from './change-text.directive';\nimport { SqrtPipe } from './app.sqrt';\n@NgModule({\n declarations: [\n SqrtPipe,\n AppComponent,\n NewCmpComponent,\n ChangeTextDirective\n ],\n imports: [\n BrowserModule,\n RouterModule.forRoot([\n {\n path: 'new-cmp',\n component: NewCmpComponent\n }\n ])\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }\n" }, { "code": null, "e": 3278, "s": 3167, "text": "Here, the RouterModule is imported from angular/router. The module is included in the imports as shown below −" }, { "code": null, "e": 3371, "s": 3278, "text": "RouterModule.forRoot([\n {\n path: 'new-cmp',\n component: NewCmpComponent\n }\n])\n" }, { "code": null, "e": 3600, "s": 3371, "text": "RouterModule refers to the forRoot which takes an input as an array, which in turn has the object of the path and the component. Path is the name of the router and component is the name of the class, i.e., the component created." }, { "code": null, "e": 3644, "s": 3600, "text": "Let us now see the component created file −" }, { "code": null, "e": 3971, "s": 3644, "text": "import { Component, OnInit } from '@angular/core';\n\n@Component({\n selector: 'app-new-cmp',\n templateUrl: './new-cmp.component.html',\n styleUrls: ['./new-cmp.component.css']\n})\n\nexport class NewCmpComponent implements OnInit {\n newcomponent = \"Entered in new component created\";\n constructor() {}\n ngOnInit() { }\n}\n" }, { "code": null, "e": 4041, "s": 3971, "text": "The highlighted class is mentioned in the imports of the main module." }, { "code": null, "e": 4099, "s": 4041, "text": "<p>\n {{newcomponent}}\n</p>\n\n<p>\n new-cmp works!\n</p>\n" }, { "code": null, "e": 4287, "s": 4099, "text": "Now, we need the above content from the html file to be displayed whenever required or clicked from the main module. For this, we need to add the router details in the app.component.html." }, { "code": null, "e": 4514, "s": 4287, "text": "<h1>Custom Pipe</h1>\n<b>Square root of 25 is: {{25 | sqrt}}</b><br/>\n<b>Square root of 729 is: {{729 | sqrt}}</b>\n\n<br />\n<br />\n<br />\n<a routerLink = \"new-cmp\">New component</a>\n\n<br />\n<br/>\n<router-outlet></router-outlet>\n" }, { "code": null, "e": 4651, "s": 4514, "text": "In the above code, we have created the anchor link tag and given routerLink as “new-cmp”. This is referred in app.module.ts as the path." }, { "code": null, "e": 4794, "s": 4651, "text": "When a user clicks new component, the page should display the content. For this, we need the following tag - <router-outlet> </router-outlet>." }, { "code": null, "e": 4927, "s": 4794, "text": "The above tag ensures that the content in the new-cmp.component.html will be displayed on the page when a user clicks new component." }, { "code": null, "e": 4986, "s": 4927, "text": "Let us now see how the output is displayed on the browser." }, { "code": null, "e": 5063, "s": 4986, "text": "When a user clicks New component, you will see the following in the browser." }, { "code": null, "e": 5256, "s": 5063, "text": "The url contains http://localhost:4200/new-cmp. Here, the new-cmp gets appended to the original url, which is the path given in the app.module.ts and the router-link in the app.component.html." }, { "code": null, "e": 5637, "s": 5256, "text": "When a user clicks New component, the page is not refreshed and the contents are shown to the user without any reloading. Only a particular piece of the site code will be reloaded when clicked. This feature helps when we have heavy content on the page and needs to be loaded based on the user interaction. The feature also gives a good user experience as the page is not reloaded." }, { "code": null, "e": 5672, "s": 5637, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5686, "s": 5672, "text": " Anadi Sharma" }, { "code": null, "e": 5721, "s": 5686, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5735, "s": 5721, "text": " Anadi Sharma" }, { "code": null, "e": 5770, "s": 5735, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 5790, "s": 5770, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 5825, "s": 5790, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5842, "s": 5825, "text": " Frahaan Hussain" }, { "code": null, "e": 5875, "s": 5842, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 5887, "s": 5875, "text": " Senol Atac" }, { "code": null, "e": 5922, "s": 5887, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5934, "s": 5922, "text": " Senol Atac" }, { "code": null, "e": 5941, "s": 5934, "text": " Print" }, { "code": null, "e": 5952, "s": 5941, "text": " Add Notes" } ]
Bootstrap Form select
A select is used when you want to allow the user to pick from multiple options, but by default, it only allows one. Use <select> for list options with which the user is familiar, such as states or numbers. Use multiple = "multiple" to allow the users to select more than one option. You can try to run the following code to implement Bootstrap form select Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <meta name = "viewport" content="width = device-width, initial-scale = 1"> <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> </head> <body> <form role = "form"> <div class = "form-group"> <label for = "name">Country</label> <select class = "form-control"> <option>India</option> <option>Australia</option> <option>US</option> </select> </div> </form> </body> </html>
[ { "code": null, "e": 1178, "s": 1062, "text": "A select is used when you want to allow the user to pick from multiple options, but by default, it only allows one." }, { "code": null, "e": 1268, "s": 1178, "text": "Use <select> for list options with which the user is familiar, such as states or numbers." }, { "code": null, "e": 1345, "s": 1268, "text": "Use multiple = \"multiple\" to allow the users to select more than one option." }, { "code": null, "e": 1418, "s": 1345, "text": "You can try to run the following code to implement Bootstrap form select" }, { "code": null, "e": 1428, "s": 1418, "text": "Live Demo" }, { "code": null, "e": 2257, "s": 1428, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <meta name = \"viewport\" content=\"width = device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <form role = \"form\">\n <div class = \"form-group\">\n <label for = \"name\">Country</label>\n <select class = \"form-control\">\n <option>India</option>\n <option>Australia</option>\n <option>US</option>\n </select>\n </div>\n </form>\n </body>\n</html>" } ]
Java Math nextAfter() method with Example - GeeksforGeeks
15 Apr, 2018 The java.lang.Math.nextAfter() returns the floating-point number adjacent to the first argument in the direction of the second argument. If both arguments are equal then the second argument is returned. Syntax :// datatype can be float or double.public static dataType nextAfter(dataType st, dataType dir) Parameter :st :starting floating-point value.dir :value indicating which of start’s neighbors or start should be returned. Return :This method returns the floating-point number adjacent to start in the direction of direction. Note : If one of the arguments is NaN, Output is NaN If both arguments are signed zeros, direction is returned unchanged(as implied by the requirement of returning the second argument if the arguments compare as equal). If start is Double.MIN_VALUE or Float.MIN_VALUE and direction has a value such that the result should have a smaller magnitude, then a zero with the same sign as start is returned. If start is infinite and direction has a value such that the result should have a smaller magnitude, Double.MAX_VALUE or Float.MAX_VALUE with the same sign as start is returned. If start is equal to Double.MAX_VALUE or Float.MAX_VALUE and direction has a value such that the result should have a larger magnitude, an infinity with same sign as start is returned. Example 1 :To show working of java.lang.Math.nextAfter() method. // Java program to demonstrate working// of java.lang.Math.nextAfter() methodimport java.lang.Math; class GfG { // driver code public static void main(String args[]) { double a = 0.0 / 0; double b = 12.2; // Input a is NaN, Output NaN System.out.println(Math.nextAfter(a, b)); double c = 0.0; double d = 0.0; // Both Input are signed zeros, Output zero System.out.println(Math.nextAfter(c, d)); float e = Float.MIN_VALUE; float f = 12.2f; System.out.println(Math.nextAfter(e, f)); float g = 1.0f / 0f; float h = 1.0f; System.out.println(Math.nextAfter(g, h)); double i = Double.MAX_VALUE; double j = 12344.2; System.out.println(Math.nextAfter(i, j)); }} Output: NaN 0.0 2.8E-45 3.4028235E38 1.7976931348623155E308 java-math Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Constructors in Java Exceptions in Java Functional Interfaces in Java Stream In Java Different ways of Reading a text file in Java Internal Working of HashMap in Java Iterators in Java Java Programming Examples Comparator Interface in Java with Examples Strings in Java
[ { "code": null, "e": 23557, "s": 23529, "text": "\n15 Apr, 2018" }, { "code": null, "e": 23760, "s": 23557, "text": "The java.lang.Math.nextAfter() returns the floating-point number adjacent to the first argument in the direction of the second argument. If both arguments are equal then the second argument is returned." }, { "code": null, "e": 23863, "s": 23760, "text": "Syntax :// datatype can be float or double.public static dataType nextAfter(dataType st, dataType dir)" }, { "code": null, "e": 23986, "s": 23863, "text": "Parameter :st :starting floating-point value.dir :value indicating which of start’s neighbors or start should be returned." }, { "code": null, "e": 24089, "s": 23986, "text": "Return :This method returns the floating-point number adjacent to start in the direction of direction." }, { "code": null, "e": 24096, "s": 24089, "text": "Note :" }, { "code": null, "e": 24142, "s": 24096, "text": "If one of the arguments is NaN, Output is NaN" }, { "code": null, "e": 24309, "s": 24142, "text": "If both arguments are signed zeros, direction is returned unchanged(as implied by the requirement of returning the second argument if the arguments compare as equal)." }, { "code": null, "e": 24490, "s": 24309, "text": "If start is Double.MIN_VALUE or Float.MIN_VALUE and direction has a value such that the result should have a smaller magnitude, then a zero with the same sign as start is returned." }, { "code": null, "e": 24668, "s": 24490, "text": "If start is infinite and direction has a value such that the result should have a smaller magnitude, Double.MAX_VALUE or Float.MAX_VALUE with the same sign as start is returned." }, { "code": null, "e": 24853, "s": 24668, "text": "If start is equal to Double.MAX_VALUE or Float.MAX_VALUE and direction has a value such that the result should have a larger magnitude, an infinity with same sign as start is returned." }, { "code": null, "e": 24918, "s": 24853, "text": "Example 1 :To show working of java.lang.Math.nextAfter() method." }, { "code": "// Java program to demonstrate working// of java.lang.Math.nextAfter() methodimport java.lang.Math; class GfG { // driver code public static void main(String args[]) { double a = 0.0 / 0; double b = 12.2; // Input a is NaN, Output NaN System.out.println(Math.nextAfter(a, b)); double c = 0.0; double d = 0.0; // Both Input are signed zeros, Output zero System.out.println(Math.nextAfter(c, d)); float e = Float.MIN_VALUE; float f = 12.2f; System.out.println(Math.nextAfter(e, f)); float g = 1.0f / 0f; float h = 1.0f; System.out.println(Math.nextAfter(g, h)); double i = Double.MAX_VALUE; double j = 12344.2; System.out.println(Math.nextAfter(i, j)); }}", "e": 25724, "s": 24918, "text": null }, { "code": null, "e": 25732, "s": 25724, "text": "Output:" }, { "code": null, "e": 25785, "s": 25732, "text": "NaN\n0.0\n2.8E-45\n3.4028235E38\n1.7976931348623155E308\n" }, { "code": null, "e": 25795, "s": 25785, "text": "java-math" }, { "code": null, "e": 25800, "s": 25795, "text": "Java" }, { "code": null, "e": 25805, "s": 25800, "text": "Java" }, { "code": null, "e": 25903, "s": 25805, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25912, "s": 25903, "text": "Comments" }, { "code": null, "e": 25925, "s": 25912, "text": "Old Comments" }, { "code": null, "e": 25946, "s": 25925, "text": "Constructors in Java" }, { "code": null, "e": 25965, "s": 25946, "text": "Exceptions in Java" }, { "code": null, "e": 25995, "s": 25965, "text": "Functional Interfaces in Java" }, { "code": null, "e": 26010, "s": 25995, "text": "Stream In Java" }, { "code": null, "e": 26056, "s": 26010, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26092, "s": 26056, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 26110, "s": 26092, "text": "Iterators in Java" }, { "code": null, "e": 26136, "s": 26110, "text": "Java Programming Examples" }, { "code": null, "e": 26179, "s": 26136, "text": "Comparator Interface in Java with Examples" } ]
Difference between Work area, global structure and internal table in SAP ABAP
Internal tables let you read data from a fixed structure and stores it in-memory (working memory) in ABAP. The data is stored in a sequential manner in memory. They are basically equivalent to arrays but dynamic in nature. Since they are dynamic in nature, memory management is already taken care by ABAP. Usually, data read from database tables are stored in the internal table to exactly replicate the database tables. Work Area refers to a single row of a fixed structure. It is basically used for storing temporary data. It is commonly used while iterating over a loop. For ex. If you need to loop over an internal table, you can store the current record in a work area. --------------- LOOP AT INTAB INTO WORKAREA. ENDLOOP. -------------- Here INTAB refers to an internal table and WORKAREA refers to a work area. Global Structure as the name reflects is global in nature. It is a structure which is created for an info provider and then can be reused across all queries for the same info provider.
[ { "code": null, "e": 1484, "s": 1062, "text": "Internal tables let you read data from a fixed structure and stores it in-memory (working memory) in ABAP. The data is stored in a sequential manner in memory. They are basically equivalent to arrays but dynamic in nature. Since they are dynamic in nature, memory management is already taken care by ABAP. Usually, data read from database tables are stored in the internal table to exactly replicate the database tables. " }, { "code": null, "e": 1637, "s": 1484, "text": "Work Area refers to a single row of a fixed structure. It is basically used for storing temporary data. It is commonly used while iterating over a loop." }, { "code": null, "e": 1738, "s": 1637, "text": "For ex. If you need to loop over an internal table, you can store the current record in a work area." }, { "code": null, "e": 1807, "s": 1738, "text": "---------------\nLOOP AT INTAB INTO WORKAREA.\nENDLOOP.\n--------------" }, { "code": null, "e": 1883, "s": 1807, "text": "Here INTAB refers to an internal table and WORKAREA refers to a work area. " }, { "code": null, "e": 2068, "s": 1883, "text": "Global Structure as the name reflects is global in nature. It is a structure which is created for an info provider and then can be reused across all queries for the same info provider." } ]
PL/SQL - IF-THEN-ELSIF Statement
The IF-THEN-ELSIF statement allows you to choose between several alternatives. An IF-THEN statement can be followed by an optional ELSIF...ELSE statement. The ELSIF clause lets you add additional conditions. When using IF-THEN-ELSIF statements there are a few points to keep in mind. It's ELSIF, not ELSEIF. It's ELSIF, not ELSEIF. An IF-THEN statement can have zero or one ELSE's and it must come after any ELSIF's. An IF-THEN statement can have zero or one ELSE's and it must come after any ELSIF's. An IF-THEN statement can have zero to many ELSIF's and they must come before the ELSE. An IF-THEN statement can have zero to many ELSIF's and they must come before the ELSE. Once an ELSIF succeeds, none of the remaining ELSIF's or ELSE's will be tested. Once an ELSIF succeeds, none of the remaining ELSIF's or ELSE's will be tested. The syntax of an IF-THEN-ELSIF Statement in PL/SQL programming language is − IF(boolean_expression 1)THEN S1; -- Executes when the boolean expression 1 is true ELSIF( boolean_expression 2) THEN S2; -- Executes when the boolean expression 2 is true ELSIF( boolean_expression 3) THEN S3; -- Executes when the boolean expression 3 is true ELSE S4; -- executes when the none of the above condition is true END IF; DECLARE a number(3) := 100; BEGIN IF ( a = 10 ) THEN dbms_output.put_line('Value of a is 10' ); ELSIF ( a = 20 ) THEN dbms_output.put_line('Value of a is 20' ); ELSIF ( a = 30 ) THEN dbms_output.put_line('Value of a is 30' ); ELSE dbms_output.put_line('None of the values is matching'); END IF; dbms_output.put_line('Exact value of a is: '|| a ); END; / When the above code is executed at the SQL prompt, it produces the following result − None of the values is matching Exact value of a is: 100 PL/SQL procedure successfully completed. Print Add Notes Bookmark this page
[ { "code": null, "e": 2273, "s": 2065, "text": "The IF-THEN-ELSIF statement allows you to choose between several alternatives. An IF-THEN statement can be followed by an optional ELSIF...ELSE statement. The ELSIF clause lets you add additional conditions." }, { "code": null, "e": 2349, "s": 2273, "text": "When using IF-THEN-ELSIF statements there are a few points to keep in mind." }, { "code": null, "e": 2373, "s": 2349, "text": "It's ELSIF, not ELSEIF." }, { "code": null, "e": 2397, "s": 2373, "text": "It's ELSIF, not ELSEIF." }, { "code": null, "e": 2482, "s": 2397, "text": "An IF-THEN statement can have zero or one ELSE's and it must come after any ELSIF's." }, { "code": null, "e": 2567, "s": 2482, "text": "An IF-THEN statement can have zero or one ELSE's and it must come after any ELSIF's." }, { "code": null, "e": 2654, "s": 2567, "text": "An IF-THEN statement can have zero to many ELSIF's and they must come before the ELSE." }, { "code": null, "e": 2741, "s": 2654, "text": "An IF-THEN statement can have zero to many ELSIF's and they must come before the ELSE." }, { "code": null, "e": 2821, "s": 2741, "text": "Once an ELSIF succeeds, none of the remaining ELSIF's or ELSE's will be tested." }, { "code": null, "e": 2901, "s": 2821, "text": "Once an ELSIF succeeds, none of the remaining ELSIF's or ELSE's will be tested." }, { "code": null, "e": 2978, "s": 2901, "text": "The syntax of an IF-THEN-ELSIF Statement in PL/SQL programming language is −" }, { "code": null, "e": 3340, "s": 2978, "text": "IF(boolean_expression 1)THEN \n S1; -- Executes when the boolean expression 1 is true \nELSIF( boolean_expression 2) THEN \n S2; -- Executes when the boolean expression 2 is true \nELSIF( boolean_expression 3) THEN \n S3; -- Executes when the boolean expression 3 is true \nELSE \n S4; -- executes when the none of the above condition is true \nEND IF; \n" }, { "code": null, "e": 3756, "s": 3340, "text": "DECLARE \n a number(3) := 100; \nBEGIN \n IF ( a = 10 ) THEN \n dbms_output.put_line('Value of a is 10' ); \n ELSIF ( a = 20 ) THEN \n dbms_output.put_line('Value of a is 20' ); \n ELSIF ( a = 30 ) THEN \n dbms_output.put_line('Value of a is 30' ); \n ELSE \n dbms_output.put_line('None of the values is matching'); \n END IF; \n dbms_output.put_line('Exact value of a is: '|| a ); \nEND; \n/ " }, { "code": null, "e": 3842, "s": 3756, "text": "When the above code is executed at the SQL prompt, it produces the following result −" }, { "code": null, "e": 3945, "s": 3842, "text": "None of the values is matching \nExact value of a is: 100 \n\nPL/SQL procedure successfully completed. \n" }, { "code": null, "e": 3952, "s": 3945, "text": " Print" }, { "code": null, "e": 3963, "s": 3952, "text": " Add Notes" } ]
How to use RatingBar in android?
Before getting into an example, we should know what is rating bar in android. Rating bar is a subclass of absSeekbar class in android. It is used to show the rating on view Group or window manager. This example demonstrates how to use the rating bar in android. 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"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:id="@+id/layout" android:layout_height="match_parent" android:orientation="vertical"> <RatingBar android:id="@+id/rating" android:layout_width="wrap_content" android:layout_height="wrap_content" android:saveEnabled="true" android:numStars="5"/> <Button android:id="@+id/getRating" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Get Rating "/> </LinearLayout> In the above code, we have declared Rating bar and set numStars as 5 means it allows maximum number of stars 5 and button. User has to drag stars for rating and click on button when user click on button it will print stars rating on toast. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.RatingBar; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @TargetApi(Build.VERSION_CODES.O) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button getRating = findViewById(R.id.getRating); final RatingBar ratingBar = findViewById(R.id.rating); getRating.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String rating = "Rating is :" + ratingBar.getRating(); Toast.makeText(MainActivity.this, rating, Toast.LENGTH_LONG).show(); } }); } } In the above code, we have declare button onclick listener, when you click button it going to get rating as show below - String rating = "Rating is :" + ratingBar.getRating(); Step 4 − No need to change manifest.xml 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 − The above result indicates initial screen, User has to drag rating on rating bar and click on button as shown below- The above result we have selected rating as 3 and it is printed as 3. The above result we have selected rating 3.5 and printed as 3.5 Click here to download the project code
[ { "code": null, "e": 1260, "s": 1062, "text": "Before getting into an example, we should know what is rating bar in android. Rating bar is a subclass of absSeekbar class in android. It is used to show the rating on view Group or window manager." }, { "code": null, "e": 1324, "s": 1260, "text": "This example demonstrates how to use the rating bar in android." }, { "code": null, "e": 1453, "s": 1324, "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": 1518, "s": 1453, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2145, "s": 1518, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout 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 android:orientation=\"vertical\">\n <RatingBar\n android:id=\"@+id/rating\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:saveEnabled=\"true\"\n android:numStars=\"5\"/>\n <Button\n android:id=\"@+id/getRating\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Get Rating \"/>\n</LinearLayout>" }, { "code": null, "e": 2385, "s": 2145, "text": "In the above code, we have declared Rating bar and set numStars as 5 means it allows maximum number of stars 5 and button. User has to drag stars for rating and click on button when user click on button it will print stars rating on toast." }, { "code": null, "e": 2442, "s": 2385, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3396, "s": 2442, "text": "package com.example.andy.myapplication;\nimport android.annotation.TargetApi;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.RatingBar;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\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 Button getRating = findViewById(R.id.getRating);\n final RatingBar ratingBar = findViewById(R.id.rating);\n getRating.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n String rating = \"Rating is :\" + ratingBar.getRating();\n Toast.makeText(MainActivity.this, rating, Toast.LENGTH_LONG).show();\n }\n });\n}\n}" }, { "code": null, "e": 3517, "s": 3396, "text": "In the above code, we have declare button onclick listener, when you click button it going to get rating as show below -" }, { "code": null, "e": 3572, "s": 3517, "text": "String rating = \"Rating is :\" + ratingBar.getRating();" }, { "code": null, "e": 3612, "s": 3572, "text": "Step 4 − No need to change manifest.xml" }, { "code": null, "e": 3962, "s": 3612, "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": 4079, "s": 3962, "text": "The above result indicates initial screen, User has to drag rating on rating bar and click on button as shown below-" }, { "code": null, "e": 4149, "s": 4079, "text": "The above result we have selected rating as 3 and it is printed as 3." }, { "code": null, "e": 4213, "s": 4149, "text": "The above result we have selected rating 3.5 and printed as 3.5" }, { "code": null, "e": 4253, "s": 4213, "text": "Click here to download the project code" } ]
Tryit Editor v3.7
Tryit: HTML iframe
[]
How to combine lists in R?
When we have multiple lists but they have similar type of data then we might want to combine or merge those lists. This will be helpful to use because we can perform the calculations using one list name instead of applying them on multiple ones. We can combine multiple lists with the help of mapply function. Consider the below lists − > List1<-list(letters[1:5],1:5,5:1,25,c("A","B","C","D")) > List1 [[1]] [1] "a" "b" "c" "d" "e" [[2]] [1] 1 2 3 4 5 [[3]] [1] 5 4 3 2 1 [[4]] [1] 25 [[5]] [1] "A" "B" "C" "D" > List2<-list(letters[6:10],6:10,c(25,16,9,4,1),36,c("Andy","Boston","Caroline","Dinesh")) > List2 [[1]] [1] "f" "g" "h" "i" "j" [[2]] [1] 6 7 8 9 10 [[3]] [1] 25 16 9 4 1 [[4]] [1] 36 [[5]] [1] "Andy" "Boston" "Caroline" "Dinesh" > mapply(c, List1, List2, SIMPLIFY=FALSE) [[1]] [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" [[2]] [1] 1 2 3 4 5 6 7 8 9 10 [[3]] [1] 5 4 3 2 1 25 16 9 4 1 [[4]] [1] 25 36 [[5]] [1] "A" "B" "C" "D" "Andy" "Boston" "Caroline" "Dinesh" Now suppose, we have one more list that is List3 then it can be combined in the same way as shown below − > List3<-list(letters[11:15],11:15,c(6,7,8,9,10),49,c("Aaron","Betty","Corie","Donald")) > List3 [[1]] [1] "k" "l" "m" "n" "o" [[2]] [1] 11 12 13 14 15 [[3]] [1] 6 7 8 9 10 [[4]] [1] 49 [[5]] [1] "Aaron" "Betty" "Corie" "Donald" > mapply(c, List1, List2, List3, SIMPLIFY=FALSE) [[1]] [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" [[2]] [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [[3]] [1] 5 4 3 2 1 25 16 9 4 1 6 7 8 9 10 [[4]] [1] 25 36 49 [[5]] [1] "A" "B" "C" "D" "Andy" "Boston" "Caroline" "Dinesh" "Aaron" "Betty" "Corie" "Donald"
[ { "code": null, "e": 1372, "s": 1062, "text": "When we have multiple lists but they have similar type of data then we might want to combine or merge those lists. This will be helpful to use because we can perform the calculations using one list name instead of applying them on multiple ones. We can combine multiple lists with the help of mapply function." }, { "code": null, "e": 1399, "s": 1372, "text": "Consider the below lists −" }, { "code": null, "e": 2132, "s": 1399, "text": "> List1<-list(letters[1:5],1:5,5:1,25,c(\"A\",\"B\",\"C\",\"D\"))\n> List1\n[[1]]\n [1] \"a\" \"b\" \"c\" \"d\" \"e\"\n[[2]]\n [1] 1 2 3 4 5\n[[3]]\n [1] 5 4 3 2 1\n[[4]]\n [1] 25\n[[5]]\n [1] \"A\" \"B\" \"C\" \"D\"\n> List2<-list(letters[6:10],6:10,c(25,16,9,4,1),36,c(\"Andy\",\"Boston\",\"Caroline\",\"Dinesh\"))\n> List2\n[[1]]\n [1] \"f\" \"g\" \"h\" \"i\" \"j\"\n[[2]]\n [1] 6 7 8 9 10\n[[3]]\n [1] 25 16 9 4 1\n[[4]]\n [1] 36\n[[5]]\n [1] \"Andy\" \"Boston\" \"Caroline\" \"Dinesh\"\n> mapply(c, List1, List2, SIMPLIFY=FALSE)\n[[1]]\n [1] \"a\" \"b\" \"c\" \"d\" \"e\" \"f\" \"g\" \"h\" \"i\" \"j\"\n[[2]]\n [1] 1 2 3 4 5 6 7 8 9 10\n[[3]]\n [1] 5 4 3 2 1 25 16 9 4 1\n[[4]]\n[1] 25 36\n[[5]]\n[1] \"A\" \"B\" \"C\" \"D\" \"Andy\" \"Boston\" \"Caroline\" \"Dinesh\"" }, { "code": null, "e": 2238, "s": 2132, "text": "Now suppose, we have one more list that is List3 then it can be combined in the same way as shown below −" }, { "code": null, "e": 2872, "s": 2238, "text": "> List3<-list(letters[11:15],11:15,c(6,7,8,9,10),49,c(\"Aaron\",\"Betty\",\"Corie\",\"Donald\"))\n> List3\n[[1]]\n [1] \"k\" \"l\" \"m\" \"n\" \"o\"\n[[2]]\n [1] 11 12 13 14 15\n[[3]]\n [1] 6 7 8 9 10\n[[4]]\n [1] 49\n[[5]]\n [1] \"Aaron\" \"Betty\" \"Corie\" \"Donald\"\n> mapply(c, List1, List2, List3, SIMPLIFY=FALSE)\n[[1]]\n [1] \"a\" \"b\" \"c\" \"d\" \"e\" \"f\" \"g\" \"h\" \"i\" \"j\" \"k\" \"l\" \"m\" \"n\" \"o\"\n[[2]]\n [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15\n[[3]]\n [1] 5 4 3 2 1 25 16 9 4 1 6 7 8 9 10\n[[4]]\n [1] 25 36 49\n[[5]]\n[1] \"A\" \"B\" \"C\" \"D\" \"Andy\" \"Boston\" \"Caroline\" \"Dinesh\" \"Aaron\" \"Betty\" \"Corie\" \"Donald\"" } ]
Second Minimum Node In a Binary Tree in C++
Suppose there is a non-empty special binary tree with some non-negative value, here each node in this tree has exactly two or zero children. If the node has two children, then this node's value is the smaller value among its two children. In other words, we can say that [root.val = minimum of root.left.val, root.right.val]. If we have such binary tree, we have to find the second minimum value in the set made of all the nodes' value in the whole tree. If there is no such element, then return -1 instead. So, if the input is like then the output will be 5. The smallest value is 2, the second smallest value is 5. To solve this, we will follow these steps − Define a function TraverseNodes(), this will take node, min, nextMin, if node is null, then −return return if val of node > min, then −if nextMin is same as -1 or val of node < nextMin, then −nextMin := val of node if nextMin is same as -1 or val of node < nextMin, then −nextMin := val of node nextMin := val of node TraverseNodes(left of node, min, nextMin) TraverseNodes(right of node, min, nextMin) From the main method do the following − min := value of root when root is not null, otherwise -1 nextMin := -1 TraverseNodes(root, min, nextMin) return nextMin Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class TreeNode{ public: int val; TreeNode *left, *right; TreeNode(int data){ val = data; left = NULL; right = NULL; } }; void insert(TreeNode **root, int val){ queue<TreeNode*> q; q.push(*root); while(q.size()){ TreeNode *temp = q.front(); q.pop(); if(!temp->left){ if(val != NULL) temp->left = new TreeNode(val); else temp->left = new TreeNode(0); return; }else{ q.push(temp->left); } if(!temp->right){ if(val != NULL) temp->right = new TreeNode(val); else temp->right = new TreeNode(0); return; }else{ q.push(temp->right); } } } TreeNode *make_tree(vector<int> v){ TreeNode *root = new TreeNode(v[0]); for(int i = 1; i<v.size(); i++){ insert(&root, v[i]); } return root; } class Solution { public: int findSecondMinimumValue(TreeNode* root) { int min = (root && root->val != 0) ? root->val : -1; int nextMin = -1; TraverseNodes(root, min, nextMin); return nextMin; } void TraverseNodes(TreeNode* node, int min, int& nextMin) { if (!node || node->val == 0) { return; } if (node->val > min) { if (nextMin == -1 || node->val < nextMin) { nextMin = node->val; } } TraverseNodes(node->left, min, nextMin); TraverseNodes(node->right, min, nextMin); } }; main(){ Solution ob; vector<int> v = {2,2,5,NULL,NULL,5,7}; TreeNode *root = make_tree(v); cout << (ob.findSecondMinimumValue(root)); } {2,2,5,NULL,NULL,5,7} 5
[ { "code": null, "e": 1570, "s": 1062, "text": "Suppose there is a non-empty special binary tree with some non-negative value, here each\nnode in this tree has exactly two or zero children. If the node has two children, then this node's value is the smaller value among its two children. In other words, we can say that [root.val = minimum of root.left.val, root.right.val]. If we have such binary tree, we have to find the second minimum value in the set made of all the nodes' value in the whole tree. If there is no such element, then return -1 instead." }, { "code": null, "e": 1595, "s": 1570, "text": "So, if the input is like" }, { "code": null, "e": 1679, "s": 1595, "text": "then the output will be 5. The smallest value is 2, the second smallest value is 5." }, { "code": null, "e": 1723, "s": 1679, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1793, "s": 1723, "text": "Define a function TraverseNodes(), this will take node, min, nextMin," }, { "code": null, "e": 1823, "s": 1793, "text": "if node is null, then −return" }, { "code": null, "e": 1830, "s": 1823, "text": "return" }, { "code": null, "e": 1938, "s": 1830, "text": "if val of node > min, then −if nextMin is same as -1 or val of node < nextMin, then −nextMin := val of node" }, { "code": null, "e": 2018, "s": 1938, "text": "if nextMin is same as -1 or val of node < nextMin, then −nextMin := val of node" }, { "code": null, "e": 2041, "s": 2018, "text": "nextMin := val of node" }, { "code": null, "e": 2083, "s": 2041, "text": "TraverseNodes(left of node, min, nextMin)" }, { "code": null, "e": 2126, "s": 2083, "text": "TraverseNodes(right of node, min, nextMin)" }, { "code": null, "e": 2166, "s": 2126, "text": "From the main method do the following −" }, { "code": null, "e": 2223, "s": 2166, "text": "min := value of root when root is not null, otherwise -1" }, { "code": null, "e": 2237, "s": 2223, "text": "nextMin := -1" }, { "code": null, "e": 2271, "s": 2237, "text": "TraverseNodes(root, min, nextMin)" }, { "code": null, "e": 2286, "s": 2271, "text": "return nextMin" }, { "code": null, "e": 2356, "s": 2286, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2367, "s": 2356, "text": " Live Demo" }, { "code": null, "e": 4098, "s": 2367, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass TreeNode{\n public:\n int val;\n TreeNode *left, *right;\n TreeNode(int data){\n val = data;\n left = NULL;\n right = NULL;\n }\n};\nvoid insert(TreeNode **root, int val){\n queue<TreeNode*> q;\n q.push(*root);\n while(q.size()){\n TreeNode *temp = q.front();\n q.pop();\n if(!temp->left){\n if(val != NULL)\n temp->left = new TreeNode(val);\n else\n temp->left = new TreeNode(0);\n return;\n }else{\n q.push(temp->left);\n }\n if(!temp->right){\n if(val != NULL)\n temp->right = new TreeNode(val);\n else\n temp->right = new TreeNode(0);\n return;\n }else{\n q.push(temp->right);\n }\n }\n}\nTreeNode *make_tree(vector<int> v){\n TreeNode *root = new TreeNode(v[0]);\n for(int i = 1; i<v.size(); i++){\n insert(&root, v[i]);\n }\n return root;\n}\nclass Solution {\npublic:\n int findSecondMinimumValue(TreeNode* root) {\n int min = (root && root->val != 0) ? root->val : -1;\n int nextMin = -1;\n TraverseNodes(root, min, nextMin);\n return nextMin;\n }\n void TraverseNodes(TreeNode* node, int min, int& nextMin) {\n if (!node || node->val == 0) {\n return;\n }\n if (node->val > min) {\n if (nextMin == -1 || node->val < nextMin) {\n nextMin = node->val;\n }\n }\n TraverseNodes(node->left, min, nextMin);\n TraverseNodes(node->right, min, nextMin);\n }\n};\nmain(){\n Solution ob;\n vector<int> v = {2,2,5,NULL,NULL,5,7};\n TreeNode *root = make_tree(v);\n cout << (ob.findSecondMinimumValue(root));\n}" }, { "code": null, "e": 4120, "s": 4098, "text": "{2,2,5,NULL,NULL,5,7}" }, { "code": null, "e": 4122, "s": 4120, "text": "5" } ]
How React and ReactDOM works? - GeeksforGeeks
19 Nov, 2021 When you work with React, it is more than likely that you will build your apps with JSX. The JSX is a tag-based JavaScript syntax like looks familiar with HTML. React element is the atomic and most basic unit that you need to master before JSX and before moving forward with React. Note: In order to work with React in the browsers, we need to include 2 libraries: React and ReactDOM. React library is responsible for creating views and ReactDOM library is responsible to actually render UI in the browser. Including Scripts: Following are the CDN links for React and ReactDOM: React: https://cdnjs.com/libraries/react ReactDOM: https://cdnjs.com/libraries/react-dom Include these two libraries before your main JavaScript file. While learning How React works, we’ll build a small application using react and ReactDOM. For the sake of simplicity, It contains only 2 files index.html and main.js in the same folder. You should use the React development version to get error messages and warnings in the browser console. HTML <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>React | How React works</title></head><body> <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"> </script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"> </script> <script src="./main.js"></script></body></html> React Elements: HTML is just a set of instructions that eventually become DOM elements. Let’s say you have to build an HTML hierarchy of JavaScript libraries and Frameworks. Following HTML commands to make HTML hierarchies for JavaScript Libraries and Frameworks. HTML <section class="js-section"> <h1>JavaScript Libraries and Frameworks</h1> <ul class="list-lib-frameworks"> <li>React.js</li> <li>Angular</li> <li>Vue.js</li> <li>Node.js</li> <li>underscore.js</li> </ul></section> In the browser, HTML represents a tree-like structure where the section is the root node, and it contains 2 child nodes i.e. h1 and ul. The ul also has some children i.e. 5 li nodes. In DOM it will represent as: DOM representation in the browser In the past, websites consisted of multiple pages, and when the user clicks on a link then the browser requests a new HTML page and builds DOM again. But after the invention of AJAX(Asynchronous JavaScript and XML) brought us a single Page Application(SPA). In SPA, the browser first loads the initial HTML document. When a user navigates by clicking the links, the browser sends the request and then the browser updates the part of a DOM. It feels like the user is jumping from page to page. But the user always stays on the same page. JavaScript destroys the old and creates a new UI. It is JavaScript that is doing heavy lifting under the hood. How JavaScript updates the DOM? JavaScript uses DOM API to updates and manipulates DOM nodes. The DOM API is just a collection of objects that JavaScript uses to manipulate the DOM. The manipulation here means CRUD(create, read, update, and delete) operations in DOM nodes. If you want to build the HTML page, we can also build with vanilla JavaScript. Javascript const root = document.querySelector( 'body' ); function createListElement() { const libsAndFrameworksNames = ['React.js', 'Angular', 'Vue.js', 'Node.js', 'Underscore.js']; const ul = document.createElement( 'ul' ); ul.classList.add( "list-lib-frameworks" ); libsAndFrameworksNames.forEach( function appoendToUnorderedList( name ) { const listElement = document.createElement( 'li' ); listElement.innerText = name; ul.appendChild( listElement ); } ); return ul;} function createWebPageWithJavaScript( root ) { // PARENT ELEMENT const parent = document.createElement( 'section' ); parent.classList.add( 'js-section' ); // HEADING ELEMENT const heading = document.createElement( 'h1' ); heading.innerText = 'JavaScript Libraries and Frameworks'; // UNORDERED LIST ELEMENT const unorderedListElement = createListElement(); // APPEND HEADING AND UNORDERED LIST ELEMENT TO PARENT parent.appendChild(heading) parent.appendChild( unorderedListElement ); // APPEND PARENT TO ROOT ELEMENT root.appendChild( parent );} createWebPageWithJavaScript( root ); Output: Output exactly the same as earlier But as our application grows, complexity grows, and it is hard to maintain. So to overcome complexity we’re going to use React to handle complexity for us. React is a library that is specifically designed to interact with DOM for us. From now onwards we don’t update DOM directly instead we’re going to tell react to update the DOM for us. React will take care of rendering and reconciling the element for us through the command we give to react. There are some similarities between DOM and React. Both are made up of nodes. DOM is made up of DOM nodes/elements and React is made up of React nodes/elements. Both look exactly the same, but they are quite different. Creating React Element: As already described earlier, the React element is the smallest entity. The React element is just a JavaScript object that describes the DOM element in memory. We can create a React element using React’s createElement method. Syntax: React.createElement(type, [props], [...children]); Parameters: Above method accepts the following parameters: type: It is the type of element you want to create i.e. div, ul, li, section, etc. It could also be another react element. props: It is a JavaScript object that contains properties or data required to construct a DOM. children or content: There are children or content to display other nested elements. It could be the content of a node. Example: How to create a li element in our application: const listElement = React.createElement( 'li', null, 'React.js' ); console.log( listElement ); The output of the createReact element Explanation: In the above code, we passed 3 arguments to createElement which are as follows: li: It defines the type of element we want to create. In this case, is the list element.null: We don’t want to define any property in the list element. We could have passed the className property to it, to define the class property on the list node. But in our case, we don’t. So we’ve to externally pass null if there is no property.React.js: The third element represents the element’s children. Any node that is inserted in between the starting tag and ending tag should be defined in the third parameter. In the list node, we don’t have children to insert, but we do have the text. So we pass the text as a string. li: It defines the type of element we want to create. In this case, is the list element. null: We don’t want to define any property in the list element. We could have passed the className property to it, to define the class property on the list node. But in our case, we don’t. So we’ve to externally pass null if there is no property. React.js: The third element represents the element’s children. Any node that is inserted in between the starting tag and ending tag should be defined in the third parameter. In the list node, we don’t have children to insert, but we do have the text. So we pass the text as a string. During the rendering process, React converts the React element to the actual DOM element. <li> React.js </li> But if you want to add a class in the list(<li>) element then we could’ve added the second property as: const listElement = React.createElement( 'li', { className: 'list' }, 'React.js' ); console.log( listElement ); If we’ve used class in place of className then we would’ve gotten the warning message from React. This error message can differ from version to version. The class attribute becomes the className property of props to React. The following could be the two reasons: The React element/node we get from createElement is DOM nodes not HTML element. As we know class is the name of the HTML attribute. As soon as Browser sees the class attribute on HTML elements then it converts to a property i.e. className. In order to test it, write down the following code: const ele = document.createElement('li'); ele.classList.add('list'); console.log( ele.className ); // list Since the class is a reserved property in JavaScript, so we can’t use the class as a property. The className is added in props property of ‘li’ React element. The property we define in the second argument is to get assigned to the props property of that React element. So React convert the above list element into a DOM element as shown below: <li class="list"> React.js </li> Once you’ve created the React element. Then you want to see it in the Browser. But Browser doesn’t understand the React element. ReactDOM is the middleman that renders the React element in the browser. ReactDOM comes with some useful methods but the method in which we are interested is render. It takes 2 parameters describe as what(element you want to render) and where(the location where you want to render). Example: To render the above list element(listElement) in DOM. const listElement = React.createElement( 'li', { className: 'list' }, 'React.js' ); ReactDOM.render( listElement, document.querySelector( '#root' ) ); Here the second argument to render method is the location or element under which we want to render the listElement. We could’ve used a body tag as shown below: document.querySelector('body'); It works, but not recommended. React warns us in development mode with the following message: Error if we want to render React element in body. Implementation: Following are our final main.js file for our example. Filename-main.js: Javascript const mainReactElement = React.createElement( "section", { className: "js-section" }, React.createElement( "h1", null, "JavaScript Libraries and Frameworks" ), React.createElement( "ul", { className: 'list-lib-frameworks' }, React.createElement('li', null, 'React.js'), React.createElement('li', null, 'Angular'), React.createElement('li', null, 'Vue.js'), React.createElement('li', null, 'Node.js'), React.createElement('li', null, 'underscore.js'), )); ReactDOM.render(mainReactElement, document.querySelector( '#root' )); If you’ve provided more than 3 arguments to createElement method. Then React considered additional arguments as children. So React creates an array of these child elements. This newly created array will get assigned to the props.children array. We can also use the array method to make our code more succinct as shown below: Javascript const listOfLibAndFrameworks = ['React.js', 'Angular', 'Vue.js','Node.js', 'underscore.js']; const mainReactElement = React.createElement( "section", { className: "js-section" }, React.createElement( "h1", null, "JavaScript Libraries and Frameworks" ), React.createElement( "ul", { className: 'list-lib-frameworks' }, listOfLibAndFrameworks.map((element, index) => React.createElement('li', { key: index }, element)) )); console.log( mainReactElement ); ReactDOM.render(mainReactElement, document.querySelector( '#root' )); React is just JavaScript. So whatever you can do with JavaScript, you can also do with React. When working with an array in React you come across a time when react complains about the unique key. To remove this warning we can use the key as shown above. It is used to identify the unique list by React to re-render it again if used. It makes our code more efficient. It is highly recommended adding key property while working with the list. If you don’t add the key then React throws the following warning: So don’t forget to add the key attribute in props. If we log the mainReactElement then we can see the array created with additional arguments passed to the createElement method of React. clintra sumitgumber28 ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to navigate on path by button click in react router ? How to create a table in ReactJS ? How to check the version of ReactJS ? Explain the purpose of render() in ReactJS How to set background images in ReactJS ? Express.js express.Router() Function Installation of Node.js on Linux How to set input type date in dd-mm-yyyy format using HTML ? Differences between Functional Components and Class Components in React How to create footer to stay at the bottom of a Web page?
[ { "code": null, "e": 24397, "s": 24369, "text": "\n19 Nov, 2021" }, { "code": null, "e": 24679, "s": 24397, "text": "When you work with React, it is more than likely that you will build your apps with JSX. The JSX is a tag-based JavaScript syntax like looks familiar with HTML. React element is the atomic and most basic unit that you need to master before JSX and before moving forward with React." }, { "code": null, "e": 24904, "s": 24679, "text": "Note: In order to work with React in the browsers, we need to include 2 libraries: React and ReactDOM. React library is responsible for creating views and ReactDOM library is responsible to actually render UI in the browser." }, { "code": null, "e": 24975, "s": 24904, "text": "Including Scripts: Following are the CDN links for React and ReactDOM:" }, { "code": null, "e": 25064, "s": 24975, "text": "React: https://cdnjs.com/libraries/react\nReactDOM: https://cdnjs.com/libraries/react-dom" }, { "code": null, "e": 25416, "s": 25064, "text": "Include these two libraries before your main JavaScript file. While learning How React works, we’ll build a small application using react and ReactDOM. For the sake of simplicity, It contains only 2 files index.html and main.js in the same folder. You should use the React development version to get error messages and warnings in the browser console." }, { "code": null, "e": 25421, "s": 25416, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>React | How React works</title></head><body> <script crossorigin src=\"https://unpkg.com/react@17/umd/react.development.js\"> </script> <script crossorigin src=\"https://unpkg.com/react-dom@17/umd/react-dom.development.js\"> </script> <script src=\"./main.js\"></script></body></html>", "e": 25847, "s": 25421, "text": null }, { "code": null, "e": 25864, "s": 25847, "text": " React Elements:" }, { "code": null, "e": 26112, "s": 25864, "text": "HTML is just a set of instructions that eventually become DOM elements. Let’s say you have to build an HTML hierarchy of JavaScript libraries and Frameworks. Following HTML commands to make HTML hierarchies for JavaScript Libraries and Frameworks." }, { "code": null, "e": 26119, "s": 26114, "text": "HTML" }, { "code": "<section class=\"js-section\"> <h1>JavaScript Libraries and Frameworks</h1> <ul class=\"list-lib-frameworks\"> <li>React.js</li> <li>Angular</li> <li>Vue.js</li> <li>Node.js</li> <li>underscore.js</li> </ul></section>", "e": 26351, "s": 26119, "text": null }, { "code": null, "e": 26566, "s": 26354, "text": "In the browser, HTML represents a tree-like structure where the section is the root node, and it contains 2 child nodes i.e. h1 and ul. The ul also has some children i.e. 5 li nodes. In DOM it will represent as:" }, { "code": null, "e": 26602, "s": 26568, "text": "DOM representation in the browser" }, { "code": null, "e": 27250, "s": 26602, "text": "In the past, websites consisted of multiple pages, and when the user clicks on a link then the browser requests a new HTML page and builds DOM again. But after the invention of AJAX(Asynchronous JavaScript and XML) brought us a single Page Application(SPA). In SPA, the browser first loads the initial HTML document. When a user navigates by clicking the links, the browser sends the request and then the browser updates the part of a DOM. It feels like the user is jumping from page to page. But the user always stays on the same page. JavaScript destroys the old and creates a new UI. It is JavaScript that is doing heavy lifting under the hood." }, { "code": null, "e": 27284, "s": 27252, "text": "How JavaScript updates the DOM?" }, { "code": null, "e": 27605, "s": 27284, "text": "JavaScript uses DOM API to updates and manipulates DOM nodes. The DOM API is just a collection of objects that JavaScript uses to manipulate the DOM. The manipulation here means CRUD(create, read, update, and delete) operations in DOM nodes. If you want to build the HTML page, we can also build with vanilla JavaScript." }, { "code": null, "e": 27618, "s": 27607, "text": "Javascript" }, { "code": "const root = document.querySelector( 'body' ); function createListElement() { const libsAndFrameworksNames = ['React.js', 'Angular', 'Vue.js', 'Node.js', 'Underscore.js']; const ul = document.createElement( 'ul' ); ul.classList.add( \"list-lib-frameworks\" ); libsAndFrameworksNames.forEach( function appoendToUnorderedList( name ) { const listElement = document.createElement( 'li' ); listElement.innerText = name; ul.appendChild( listElement ); } ); return ul;} function createWebPageWithJavaScript( root ) { // PARENT ELEMENT const parent = document.createElement( 'section' ); parent.classList.add( 'js-section' ); // HEADING ELEMENT const heading = document.createElement( 'h1' ); heading.innerText = 'JavaScript Libraries and Frameworks'; // UNORDERED LIST ELEMENT const unorderedListElement = createListElement(); // APPEND HEADING AND UNORDERED LIST ELEMENT TO PARENT parent.appendChild(heading) parent.appendChild( unorderedListElement ); // APPEND PARENT TO ROOT ELEMENT root.appendChild( parent );} createWebPageWithJavaScript( root );", "e": 28759, "s": 27618, "text": null }, { "code": null, "e": 28770, "s": 28762, "text": "Output:" }, { "code": null, "e": 28807, "s": 28772, "text": "Output exactly the same as earlier" }, { "code": null, "e": 28964, "s": 28807, "text": "But as our application grows, complexity grows, and it is hard to maintain. So to overcome complexity we’re going to use React to handle complexity for us. " }, { "code": null, "e": 29257, "s": 28966, "text": "React is a library that is specifically designed to interact with DOM for us. From now onwards we don’t update DOM directly instead we’re going to tell react to update the DOM for us. React will take care of rendering and reconciling the element for us through the command we give to react." }, { "code": null, "e": 29478, "s": 29259, "text": "There are some similarities between DOM and React. Both are made up of nodes. DOM is made up of DOM nodes/elements and React is made up of React nodes/elements. Both look exactly the same, but they are quite different." }, { "code": null, "e": 29502, "s": 29478, "text": "Creating React Element:" }, { "code": null, "e": 29729, "s": 29502, "text": "As already described earlier, the React element is the smallest entity. The React element is just a JavaScript object that describes the DOM element in memory. We can create a React element using React’s createElement method. " }, { "code": null, "e": 29737, "s": 29729, "text": "Syntax:" }, { "code": null, "e": 29788, "s": 29737, "text": "React.createElement(type, [props], [...children]);" }, { "code": null, "e": 29847, "s": 29788, "text": "Parameters: Above method accepts the following parameters:" }, { "code": null, "e": 29970, "s": 29847, "text": "type: It is the type of element you want to create i.e. div, ul, li, section, etc. It could also be another react element." }, { "code": null, "e": 30065, "s": 29970, "text": "props: It is a JavaScript object that contains properties or data required to construct a DOM." }, { "code": null, "e": 30185, "s": 30065, "text": "children or content: There are children or content to display other nested elements. It could be the content of a node." }, { "code": null, "e": 30241, "s": 30185, "text": "Example: How to create a li element in our application:" }, { "code": null, "e": 30336, "s": 30241, "text": "const listElement = React.createElement( 'li', null, 'React.js' );\nconsole.log( listElement );" }, { "code": null, "e": 30374, "s": 30336, "text": "The output of the createReact element" }, { "code": null, "e": 30469, "s": 30374, "text": "Explanation: In the above code, we passed 3 arguments to createElement which are as follows: " }, { "code": null, "e": 31087, "s": 30469, "text": "li: It defines the type of element we want to create. In this case, is the list element.null: We don’t want to define any property in the list element. We could have passed the className property to it, to define the class property on the list node. But in our case, we don’t. So we’ve to externally pass null if there is no property.React.js: The third element represents the element’s children. Any node that is inserted in between the starting tag and ending tag should be defined in the third parameter. In the list node, we don’t have children to insert, but we do have the text. So we pass the text as a string." }, { "code": null, "e": 31176, "s": 31087, "text": "li: It defines the type of element we want to create. In this case, is the list element." }, { "code": null, "e": 31423, "s": 31176, "text": "null: We don’t want to define any property in the list element. We could have passed the className property to it, to define the class property on the list node. But in our case, we don’t. So we’ve to externally pass null if there is no property." }, { "code": null, "e": 31707, "s": 31423, "text": "React.js: The third element represents the element’s children. Any node that is inserted in between the starting tag and ending tag should be defined in the third parameter. In the list node, we don’t have children to insert, but we do have the text. So we pass the text as a string." }, { "code": null, "e": 31797, "s": 31707, "text": "During the rendering process, React converts the React element to the actual DOM element." }, { "code": null, "e": 31817, "s": 31797, "text": "<li> React.js </li>" }, { "code": null, "e": 31921, "s": 31817, "text": "But if you want to add a class in the list(<li>) element then we could’ve added the second property as:" }, { "code": null, "e": 32038, "s": 31921, "text": "const listElement = React.createElement( 'li', {\n className: 'list'\n}, 'React.js' );\n\nconsole.log( listElement );" }, { "code": null, "e": 32191, "s": 32038, "text": "If we’ve used class in place of className then we would’ve gotten the warning message from React. This error message can differ from version to version." }, { "code": null, "e": 32301, "s": 32191, "text": "The class attribute becomes the className property of props to React. The following could be the two reasons:" }, { "code": null, "e": 32595, "s": 32303, "text": "The React element/node we get from createElement is DOM nodes not HTML element. As we know class is the name of the HTML attribute. As soon as Browser sees the class attribute on HTML elements then it converts to a property i.e. className. In order to test it, write down the following code:" }, { "code": null, "e": 32703, "s": 32595, "text": "const ele = document.createElement('li');\nele.classList.add('list');\nconsole.log( ele.className ); // list" }, { "code": null, "e": 33047, "s": 32703, "text": "Since the class is a reserved property in JavaScript, so we can’t use the class as a property. The className is added in props property of ‘li’ React element. The property we define in the second argument is to get assigned to the props property of that React element. So React convert the above list element into a DOM element as shown below:" }, { "code": null, "e": 33080, "s": 33047, "text": "<li class=\"list\"> React.js </li>" }, { "code": null, "e": 33493, "s": 33080, "text": "Once you’ve created the React element. Then you want to see it in the Browser. But Browser doesn’t understand the React element. ReactDOM is the middleman that renders the React element in the browser. ReactDOM comes with some useful methods but the method in which we are interested is render. It takes 2 parameters describe as what(element you want to render) and where(the location where you want to render). " }, { "code": null, "e": 33557, "s": 33493, "text": "Example: To render the above list element(listElement) in DOM. " }, { "code": null, "e": 33713, "s": 33557, "text": "const listElement = React.createElement( 'li', {\n className: 'list'\n}, 'React.js' );\n\nReactDOM.render( listElement, document.querySelector( '#root' ) );" }, { "code": null, "e": 33874, "s": 33713, "text": "Here the second argument to render method is the location or element under which we want to render the listElement. We could’ve used a body tag as shown below: " }, { "code": null, "e": 33906, "s": 33874, "text": "document.querySelector('body');" }, { "code": null, "e": 34000, "s": 33906, "text": "It works, but not recommended. React warns us in development mode with the following message:" }, { "code": null, "e": 34050, "s": 34000, "text": "Error if we want to render React element in body." }, { "code": null, "e": 34121, "s": 34050, "text": "Implementation: Following are our final main.js file for our example. " }, { "code": null, "e": 34139, "s": 34121, "text": "Filename-main.js:" }, { "code": null, "e": 34150, "s": 34139, "text": "Javascript" }, { "code": "const mainReactElement = React.createElement( \"section\", { className: \"js-section\" }, React.createElement( \"h1\", null, \"JavaScript Libraries and Frameworks\" ), React.createElement( \"ul\", { className: 'list-lib-frameworks' }, React.createElement('li', null, 'React.js'), React.createElement('li', null, 'Angular'), React.createElement('li', null, 'Vue.js'), React.createElement('li', null, 'Node.js'), React.createElement('li', null, 'underscore.js'), )); ReactDOM.render(mainReactElement, document.querySelector( '#root' ));", "e": 34739, "s": 34150, "text": null }, { "code": null, "e": 35068, "s": 34742, "text": "If you’ve provided more than 3 arguments to createElement method. Then React considered additional arguments as children. So React creates an array of these child elements. This newly created array will get assigned to the props.children array. We can also use the array method to make our code more succinct as shown below: " }, { "code": null, "e": 35079, "s": 35068, "text": "Javascript" }, { "code": "const listOfLibAndFrameworks = ['React.js', 'Angular', 'Vue.js','Node.js', 'underscore.js']; const mainReactElement = React.createElement( \"section\", { className: \"js-section\" }, React.createElement( \"h1\", null, \"JavaScript Libraries and Frameworks\" ), React.createElement( \"ul\", { className: 'list-lib-frameworks' }, listOfLibAndFrameworks.map((element, index) => React.createElement('li', { key: index }, element)) )); console.log( mainReactElement ); ReactDOM.render(mainReactElement, document.querySelector( '#root' ));", "e": 35646, "s": 35079, "text": null }, { "code": null, "e": 36090, "s": 35649, "text": "React is just JavaScript. So whatever you can do with JavaScript, you can also do with React. When working with an array in React you come across a time when react complains about the unique key. To remove this warning we can use the key as shown above. It is used to identify the unique list by React to re-render it again if used. It makes our code more efficient. It is highly recommended adding key property while working with the list." }, { "code": null, "e": 36157, "s": 36090, "text": "If you don’t add the key then React throws the following warning: " }, { "code": null, "e": 36345, "s": 36157, "text": "So don’t forget to add the key attribute in props. If we log the mainReactElement then we can see the array created with additional arguments passed to the createElement method of React. " }, { "code": null, "e": 36353, "s": 36345, "text": "clintra" }, { "code": null, "e": 36367, "s": 36353, "text": "sumitgumber28" }, { "code": null, "e": 36375, "s": 36367, "text": "ReactJS" }, { "code": null, "e": 36392, "s": 36375, "text": "Web Technologies" }, { "code": null, "e": 36490, "s": 36392, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36499, "s": 36490, "text": "Comments" }, { "code": null, "e": 36512, "s": 36499, "text": "Old Comments" }, { "code": null, "e": 36570, "s": 36512, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 36605, "s": 36570, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 36643, "s": 36605, "text": "How to check the version of ReactJS ?" }, { "code": null, "e": 36686, "s": 36643, "text": "Explain the purpose of render() in ReactJS" }, { "code": null, "e": 36728, "s": 36686, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 36765, "s": 36728, "text": "Express.js express.Router() Function" }, { "code": null, "e": 36798, "s": 36765, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 36859, "s": 36798, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 36931, "s": 36859, "text": "Differences between Functional Components and Class Components in React" } ]
Apache Flink - Quick Guide
The advancement of data in the last 10 years has been enormous; this gave rise to a term 'Big Data'. There is no fixed size of data, which you can call as big data; any data that your traditional system (RDBMS) is not able to handle is Big Data. This Big Data can be in structured, semi-structured or un-structured format. Initially, there were three dimensions to data − Volume, Velocity, Variety. The dimensions have now gone beyond just the three Vs. We have now added other Vs − Veracity, Validity, Vulnerability, Value, Variability, etc. Big Data led to the emergence of multiple tools and frameworks that help in the storage and processing of data. There are a few popular big data frameworks such as Hadoop, Spark, Hive, Pig, Storm and Zookeeper. It also gave opportunity to create Next Gen products in multiple domains like Healthcare, Finance, Retail, E-Commerce and more. Whether it is an MNC or a start-up, everyone is leveraging Big Data to store and process it and take smarter decisions. In terms of Big Data, there are two types of processing − Batch Processing Real-time Processing Processing based on the data collected over time is called Batch Processing. For example, a bank manager wants to process past one-month data (collected over time) to know the number of cheques that got cancelled in the past 1 month. Processing based on immediate data for instant result is called Real-time Processing. For example, a bank manager getting a fraud alert immediately after a fraud transaction (instant result) has occurred. The table given below lists down the differences between Batch and Real-Time Processing − Static Files Event Streams Processed Periodically in minute, hour, day etc. Processed immediately nanoseconds Past data on disk storage In Memory Storage Example − Bill Generation Example − ATM Transaction Alert These days, real-time processing is being used a lot in every organization. Use cases like fraud detection, real-time alerts in healthcare and network attack alert require real-time processing of instant data; a delay of even few milliseconds can have a huge impact. An ideal tool for such real time use cases would be the one, which can input data as stream and not batch. Apache Flink is that real-time processing tool. Apache Flink is a real-time processing framework which can process streaming data. It is an open source stream processing framework for high-performance, scalable, and accurate real-time applications. It has true streaming model and does not take input data as batch or micro-batches. Apache Flink was founded by Data Artisans company and is now developed under Apache License by Apache Flink Community. This community has over 479 contributors and 15500 + commits so far. The diagram given below shows the different layers of Apache Flink Ecosystem − Apache Flink has multiple options from where it can Read/Write data. Below is a basic storage list − HDFS (Hadoop Distributed File System) Local File System S3 RDBMS (MySQL, Oracle, MS SQL etc.) MongoDB HBase Apache Kafka Apache Flume You can deploy Apache Fink in local mode, cluster mode or on cloud. Cluster mode can be standalone, YARN, MESOS. On cloud, Flink can be deployed on AWS or GCP. This is the runtime layer, which provides distributed processing, fault tolerance, reliability, native iterative processing capability and more. This is the top layer and most important layer of Apache Flink. It has Dataset API, which takes care of batch processing, and Datastream API, which takes care of stream processing. There are other libraries like Flink ML (for machine learning), Gelly (for graph processing ), Tables for SQL. This layer provides diverse capabilities to Apache Flink. Apache Flink works on Kappa architecture. Kappa architecture has a single processor - stream, which treats all input as stream and the streaming engine processes the data in real-time. Batch data in kappa architecture is a special case of streaming. The following diagram shows the Apache Flink Architecture. The key idea in Kappa architecture is to handle both batch and real-time data through a single stream processing engine. Most big data framework works on Lambda architecture, which has separate processors for batch and streaming data. In Lambda architecture, you have separate codebases for batch and stream views. For querying and getting the result, the codebases need to be merged. Not maintaining separate codebases/views and merging them is a pain, but Kappa architecture solves this issue as it has only one view − real-time, hence merging of codebase is not required. That does not mean Kappa architecture replaces Lambda architecture, it completely depends on the use-case and the application that decides which architecture would be preferable. The following diagram shows Apache Flink job execution architecture. It is a piece of code, which you run on the Flink Cluster. It is responsible for taking code (program) and constructing job dataflow graph, then passing it to JobManager. It also retrieves the Job results. After receiving the Job Dataflow Graph from Client, it is responsible for creating the execution graph. It assigns the job to TaskManagers in the cluster and supervises the execution of the job. It is responsible for executing all the tasks that have been assigned by JobManager. All the TaskManagers run the tasks in their separate slots in specified parallelism. It is responsible to send the status of the tasks to JobManager. The features of Apache Flink are as follows − It has a streaming processor, which can run both batch and stream programs. It has a streaming processor, which can run both batch and stream programs. It can process data at lightning fast speed. It can process data at lightning fast speed. APIs available in Java, Scala and Python. APIs available in Java, Scala and Python. Provides APIs for all the common operations, which is very easy for programmers to use. Provides APIs for all the common operations, which is very easy for programmers to use. Processes data in low latency (nanoseconds) and high throughput. Processes data in low latency (nanoseconds) and high throughput. Its fault tolerant. If a node, application or a hardware fails, it does not affect the cluster. Its fault tolerant. If a node, application or a hardware fails, it does not affect the cluster. Can easily integrate with Apache Hadoop, Apache MapReduce, Apache Spark, HBase and other big data tools. Can easily integrate with Apache Hadoop, Apache MapReduce, Apache Spark, HBase and other big data tools. In-memory management can be customized for better computation. In-memory management can be customized for better computation. It is highly scalable and can scale upto thousands of node in a cluster. It is highly scalable and can scale upto thousands of node in a cluster. Windowing is very flexible in Apache Flink. Windowing is very flexible in Apache Flink. Provides Graph Processing, Machine Learning, Complex Event Processing libraries. Provides Graph Processing, Machine Learning, Complex Event Processing libraries. The following are the system requirements to download and work on Apache Flink − Microsoft Windows 10 Ubuntu 16.04 LTS Apple macOS 10.13/High Sierra Memory - Minimum 4 GB, Recommended 8 GB Storage Space - 30 GB Note − Java 8 must be available with environment variables already set. Before the start with the setup/ installation of Apache Flink, let us check whether we have Java 8 installed in our system. We will now proceed by downloading Apache Flink. wget http://mirrors.estointernet.in/apache/flink/flink-1.7.1/flink-1.7.1-bin-scala_2.11.tgz Now, uncompress the tar file. tar -xzf flink-1.7.1-bin-scala_2.11.tgz Go to Flink's home directory. cd flink-1.7.1/ Start the Flink Cluster. ./bin/start-cluster.sh Open the Mozilla browser and go to the below URL, it will open the Flink Web Dashboard. http://localhost:8081 This is how the User Interface of Apache Flink Dashboard looks like. Now the Flink cluster is up and running. Flink has a rich set of APIs using which developers can perform transformations on both batch and real-time data. A variety of transformations includes mapping, filtering, sorting, joining, grouping and aggregating. These transformations by Apache Flink are performed on distributed data. Let us discuss the different APIs Apache Flink offers. Dataset API in Apache Flink is used to perform batch operations on the data over a period. This API can be used in Java, Scala and Python. It can apply different kinds of transformations on the datasets like filtering, mapping, aggregating, joining and grouping. Datasets are created from sources like local files or by reading a file from a particular sourse and the result data can be written on different sinks like distributed files or command line terminal. This API is supported by both Java and Scala programming languages. Here is a Wordcount program of Dataset API − public class WordCountProg { public static void main(String[] args) throws Exception { final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); DataSet<String> text = env.fromElements( "Hello", "My Dataset API Flink Program"); DataSet<Tuple2<String, Integer>> wordCounts = text .flatMap(new LineSplitter()) .groupBy(0) .sum(1); wordCounts.print(); } public static class LineSplitter implements FlatMapFunction<String, Tuple2<String, Integer>> { @Override public void flatMap(String line, Collector<Tuple2<String, Integer>> out) { for (String word : line.split(" ")) { out.collect(new Tuple2<String, Integer>(word, 1)); } } } } This API is used for handling data in continuous stream. You can perform various operations like filtering, mapping, windowing, aggregating on the stream data. There are various sources on this data stream like message queues, files, socket streams and the result data can be written on different sinks like command line terminal. Both Java and Scala programming languages support this API. Here is a streaming Wordcount program of DataStream API, where you have continuous stream of word counts and the data is grouped in the second window. import org.apache.flink.api.common.functions.FlatMapFunction; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.windowing.time.Time; import org.apache.flink.util.Collector; public class WindowWordCountProg { public static void main(String[] args) throws Exception { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); DataStream<Tuple2<String, Integer>> dataStream = env .socketTextStream("localhost", 9999) .flatMap(new Splitter()) .keyBy(0) .timeWindow(Time.seconds(5)) .sum(1); dataStream.print(); env.execute("Streaming WordCount Example"); } public static class Splitter implements FlatMapFunction<String, Tuple2<String, Integer>> { @Override public void flatMap(String sentence, Collector<Tuple2<String, Integer>> out) throws Exception { for (String word: sentence.split(" ")) { out.collect(new Tuple2<String, Integer>(word, 1)); } } } } Table API is a relational API with SQL like expression language. This API can do both batch and stream processing. It can be embedded with Java and Scala Dataset and Datastream APIs. You can create tables from existing Datasets and Datastreams or from external data sources. Through this relational API, you can perform operations like join, aggregate, select and filter. Whether the input is batch or stream, the semantics of the query remains the same. Here is a sample Table API program − // for batch programs use ExecutionEnvironment instead of StreamExecutionEnvironment val env = StreamExecutionEnvironment.getExecutionEnvironment // create a TableEnvironment val tableEnv = TableEnvironment.getTableEnvironment(env) // register a Table tableEnv.registerTable("table1", ...) // or tableEnv.registerTableSource("table2", ...) // or tableEnv.registerExternalCatalog("extCat", ...) // register an output Table tableEnv.registerTableSink("outputTable", ...); // create a Table from a Table API query val tapiResult = tableEnv.scan("table1").select(...) // Create a Table from a SQL query val sqlResult = tableEnv.sqlQuery("SELECT ... FROM table2 ...") // emit a Table API result Table to a TableSink, same for SQL result tapiResult.insertInto("outputTable") // execute env.execute() In this chapter, we will learn how to create a Flink application. Open Eclipse IDE, click on New Project and Select Java Project. Give Project Name and click on Finish. Now, click on Finish as shown in the following screenshot. Now, right-click on src and go to New >> Class. Give a class name and click on Finish. Copy and paste the below code in the Editor. import org.apache.flink.api.common.functions.FlatMapFunction; import org.apache.flink.api.java.DataSet; import org.apache.flink.api.java.ExecutionEnvironment; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.api.java.utils.ParameterTool; import org.apache.flink.util.Collector; public class WordCount { // ************************************************************************* // PROGRAM // ************************************************************************* public static void main(String[] args) throws Exception { final ParameterTool params = ParameterTool.fromArgs(args); // set up the execution environment final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); // make parameters available in the web interface env.getConfig().setGlobalJobParameters(params); // get input data DataSet<String> text = env.readTextFile(params.get("input")); DataSet<Tuple2<String, Integer>> counts = // split up the lines in pairs (2-tuples) containing: (word,1) text.flatMap(new Tokenizer()) // group by the tuple field "0" and sum up tuple field "1" .groupBy(0) .sum(1); // emit result if (params.has("output")) { counts.writeAsCsv(params.get("output"), "\n", " "); // execute program env.execute("WordCount Example"); } else { System.out.println("Printing result to stdout. Use --output to specify output path."); counts.print(); } } // ************************************************************************* // USER FUNCTIONS // ************************************************************************* public static final class Tokenizer implements FlatMapFunction<String, Tuple2<String, Integer>> { public void flatMap(String value, Collector<Tuple2<String, Integer>> out) { // normalize and split the line String[] tokens = value.toLowerCase().split("\\W+"); // emit the pairs for (String token : tokens) { if (token.length() > 0) { out.collect(new Tuple2<>(token, 1)); } } } } } You will get many errors in the editor, because Flink libraries need to be added to this project. Right-click on the project >> Build Path >> Configure Build Path. Select the Libraries tab and click on Add External JARs. Go to Flink's lib directory, select all the 4 libraries and click on OK. Go to the Order and Export tab, select all the libraries and click on OK. You will see that the errors are no more there. Now, let us export this application. Right-click on the project and click on Export. Select JAR file and click Next Give a destination path and click on Next Click on Next> Click on Browse, select the main class (WordCount) and click Finish. Note − Click OK, in case you get any warning. Run the below command. It will further run the Flink application you just created. ./bin/flink run /home/ubuntu/wordcount.jar --input README.txt --output /home/ubuntu/output In this chapter, we will learn how to run a Flink program. Let us run the Flink wordcount example on a Flink cluster. Go to Flink's home directory and run the below command in the terminal. bin/flink run examples/batch/WordCount.jar -input README.txt -output /home/ubuntu/flink-1.7.1/output.txt Go to Flink dashboard, you will be able to see a completed job with its details. If you click on Completed Jobs, you will get detailed overview of the jobs. To check the output of wordcount program, run the below command in the terminal. cat output.txt In this chapter, we will learn about the different libraries of Apache Flink. FlinkCEP is an API in Apache Flink, which analyses event patterns on continuous streaming data. These events are near real time, which have high throughput and low latency. This API is used mostly on Sensor data, which come in real-time and are very complex to process. CEP analyses the pattern of the input stream and gives the result very soon. It has the ability to provide real-time notifications and alerts in case the event pattern is complex. FlinkCEP can connect to different kind of input sources and analyse patterns in them. This how a sample architecture with CEP looks like − Sensor data will be coming in from different sources, Kafka will act as a distributed messaging framework, which will distribute the streams to Apache Flink, and FlinkCEP will analyse the complex event patterns. You can write programs in Apache Flink for complex event processing using Pattern API. It allows you to decide the event patterns to detect from the continuous stream data. Below are some of the most commonly used CEP patterns − It is used to define the starting state. The following program shows how it is defined in a Flink program − Pattern<Event, ?> next = start.next("next"); It is used to define a filter condition in the current state. patternState.where(new FilterFunction <Event>() { @Override public boolean filter(Event value) throws Exception { } }); It is used to append a new pattern state and the matching event needed to pass the previous pattern. Pattern<Event, ?> next = start.next("next"); It is used to append a new pattern state but here other events can occur b/w two matching events. Pattern<Event, ?> followedBy = start.followedBy("next"); Apache Flink's Graph API is Gelly. Gelly is used to perform graph analysis on Flink applications using a set of methods and utilities. You can analyse huge graphs using Apache Flink API in a distributed fashion with Gelly. There are other graph libraries also like Apache Giraph for the same purpose, but since Gelly is used on top of Apache Flink, it uses single API. This is very helpful from development and operation point of view. Let us run an example using Apache Flink API − Gelly. Firstly, you need to copy 2 Gelly jar files from opt directory of Apache Flink to its lib directory. Then run flink-gelly-examples jar. cp opt/flink-gelly* lib/ ./bin/flink run examples/gelly/flink-gelly-examples_*.jar Let us now run the PageRank example. PageRank computes a per-vertex score, which is the sum of PageRank scores transmitted over in-edges. Each vertex's score is divided evenly among out-edges. High-scoring vertices are linked to by other high-scoring vertices. The result contains the vertex ID and the PageRank score. usage: flink run examples/flink-gelly-examples_<version>.jar --algorithm PageRank [algorithm options] --input <input> [input options] --output <output> [output options] ./bin/flink run examples/gelly/flink-gelly-examples_*.jar --algorithm PageRank --input CycleGraph --vertex_count 2 --output Print Apache Flink's Machine Learning library is called FlinkML. Since usage of machine learning has been increasing exponentially over the last 5 years, Flink community decided to add this machine learning APO also in its ecosystem. The list of contributors and algorithms are increasing in FlinkML. This API is not a part of binary distribution yet. Here is an example of linear regression using FlinkML − // LabeledVector is a feature vector with a label (class or real value) val trainingData: DataSet[LabeledVector] = ... val testingData: DataSet[Vector] = ... // Alternatively, a Splitter is used to break up a DataSet into training and testing data. val dataSet: DataSet[LabeledVector] = ... val trainTestData: DataSet[TrainTestDataSet] = Splitter.trainTestSplit(dataSet) val trainingData: DataSet[LabeledVector] = trainTestData.training val testingData: DataSet[Vector] = trainTestData.testing.map(lv => lv.vector) val mlr = MultipleLinearRegression() .setStepsize(1.0) .setIterations(100) .setConvergenceThreshold(0.001) mlr.fit(trainingData) // The fitted model can now be used to make predictions val predictions: DataSet[LabeledVector] = mlr.predict(testingData) Inside flink-1.7.1/examples/batch/ path, you will find KMeans.jar file. Let us run this sample FlinkML example. This example program is run using the default point and the centroid data set. ./bin/flink run examples/batch/KMeans.jar --output Print In this chapter, we will understand a few test cases in Apache Flink. Bouygues Telecom is one of the largest telecom organization in France. It has 11+ million mobile subscribers and 2.5+ million fixed customers. Bouygues heard about Apache Flink for the first time in a Hadoop Group Meeting held at Paris. Since then they have been using Flink for multiple use-cases. They have been processing billions of messages in a day in real-time through Apache Flink. This is what Bouygues has to say about Apache Flink: "We ended up with Flink because the system supports true streaming - both at the API and at the runtime level, giving us the programmability and low latency that we were looking for. In addition, we were able to get our system up and running with Flink in a fraction of the time compared to other solutions, which resulted in more available developer resources for expanding the business logic in the system." At Bouygues, customer experience is the highest priority. They analyse data in real-time so that they can give below insights to their engineers − Real-Time Customer Experience over their network Real-Time Customer Experience over their network What is happening globally on the network What is happening globally on the network Network evaluations and operations Network evaluations and operations They created a system called LUX (Logged User Experience) which processed massive log data from network equipment with internal data reference to give quality of experience indicators which will log their customer experience and build an alarming functionality to detect any failure in consumption of data within 60 seconds. To achieve this, they needed a framework which can take massive data in real-time, is easy to set up and provides rich set of APIs for processing the streamed data. Apache Flink was a perfect fit for Bouygues Telecom. Alibaba is the largest ecommerce retail company in the world with 394 billion $ revenue in 2015. Alibaba search is the entry point to all the customers, which shows all the search and recommends accordingly. Alibaba uses Apache Flink in its search engine to show results in real-time with highest accuracy and relevancy for each user. Alibaba was looking for a framework, which was − Very Agile in maintaining one codebase for their entire search infrastructure process. Very Agile in maintaining one codebase for their entire search infrastructure process. Provides low latency for the availability changes in the products on the website. Provides low latency for the availability changes in the products on the website. Consistent and cost effective. Consistent and cost effective. Apache Flink qualified for all the above requirements. They need a framework, which has a single processing engine and can process both batch and stream data with same engine and that is what Apache Flink does. They also use Blink, a forked version for Flink to meet some unique requirements for their search. They are also using Apache Flink's Table API with few improvements for their search. This is what Alibaba had to say about apache Flink: "Looking back, it was no doubt a huge year for Blink and Flink at Alibaba. No one thought that we would make this much progress in a year, and we are very grateful to all the people who helped us in the community. Flink is proven to work at the very large scale. We are more committed than ever to continue our work with the community to move Flink forward!" Here is a comprehensive table, which shows the comparison between three most popular big data frameworks: Apache Flink, Apache Spark and Apache Hadoop. Year of Origin Place of Origin Data Processing Engine Processing Speed Programming Languages Programming Model Data Transfer Memory Management Latency Throughput Optimization API Streaming Support SQL Support Graph Support Machine Learning Support The comparison table that we saw in the previous chapter concludes the pointers pretty much. Apache Flink is the most suited framework for real-time processing and use cases. Its single engine system is unique which can process both batch and streaming data with different APIs like Dataset and DataStream. It does not mean Hadoop and Spark are out of the game, the selection of the most suited big data framework always depends and vary from use case to use case. There can be several use cases where a combination of Hadoop and Flink or Spark and Flink might be suited. Nevertheless, Flink is the best framework for real time processing currently. The growth of Apache Flink has been amazing and the number of contributors to its community is growing day by day. Happy Flinking! 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": 2614, "s": 2069, "text": "The advancement of data in the last 10 years has been enormous; this gave rise to a term 'Big Data'. There is no fixed size of data, which you can call as big data; any data that your traditional system (RDBMS) is not able to handle is Big Data. This Big Data can be in structured, semi-structured or un-structured format. Initially, there were three dimensions to data − Volume, Velocity, Variety. The dimensions have now gone beyond just the three Vs. We have now added other Vs − Veracity, Validity, Vulnerability, Value, Variability, etc." }, { "code": null, "e": 2953, "s": 2614, "text": "Big Data led to the emergence of multiple tools and frameworks that help in the storage and processing of data. There are a few popular big data frameworks such as Hadoop, Spark, Hive, Pig, Storm and Zookeeper. It also gave opportunity to create Next Gen products in multiple domains like Healthcare, Finance, Retail, E-Commerce and more." }, { "code": null, "e": 3073, "s": 2953, "text": "Whether it is an MNC or a start-up, everyone is leveraging Big Data to store and process it and take smarter decisions." }, { "code": null, "e": 3131, "s": 3073, "text": "In terms of Big Data, there are two types of processing −" }, { "code": null, "e": 3149, "s": 3131, "text": "Batch Processing " }, { "code": null, "e": 3170, "s": 3149, "text": "Real-time Processing" }, { "code": null, "e": 3404, "s": 3170, "text": "Processing based on the data collected over time is called Batch Processing. For example, a bank manager wants to process past one-month data (collected over time) to know the number of cheques that got cancelled in the past 1 month." }, { "code": null, "e": 3609, "s": 3404, "text": "Processing based on immediate data for instant result is called Real-time Processing. For example, a bank manager getting a fraud alert immediately after a fraud transaction (instant result) has occurred." }, { "code": null, "e": 3699, "s": 3609, "text": "The table given below lists down the differences between Batch and Real-Time Processing −" }, { "code": null, "e": 3712, "s": 3699, "text": "Static Files" }, { "code": null, "e": 3726, "s": 3712, "text": "Event Streams" }, { "code": null, "e": 3776, "s": 3726, "text": "Processed Periodically in minute, \nhour, day etc." }, { "code": null, "e": 3798, "s": 3776, "text": "Processed immediately" }, { "code": null, "e": 3810, "s": 3798, "text": "nanoseconds" }, { "code": null, "e": 3836, "s": 3810, "text": "Past data on disk storage" }, { "code": null, "e": 3854, "s": 3836, "text": "In Memory Storage" }, { "code": null, "e": 3880, "s": 3854, "text": "Example − Bill Generation" }, { "code": null, "e": 3912, "s": 3880, "text": "Example − ATM Transaction Alert" }, { "code": null, "e": 4179, "s": 3912, "text": "These days, real-time processing is being used a lot in every organization. Use cases like fraud detection, real-time alerts in healthcare and network attack alert require real-time processing of instant data; a delay of even few milliseconds can have a huge impact." }, { "code": null, "e": 4334, "s": 4179, "text": "An ideal tool for such real time use cases would be the one, which can input data as stream and not batch. Apache Flink is that real-time processing tool." }, { "code": null, "e": 4619, "s": 4334, "text": "Apache Flink is a real-time processing framework which can process streaming data. It is an open source stream processing framework for high-performance, scalable, and accurate real-time applications. It has true streaming model and does not take input data as batch or micro-batches." }, { "code": null, "e": 4807, "s": 4619, "text": "Apache Flink was founded by Data Artisans company and is now developed under Apache License by Apache Flink Community. This community has over 479 contributors and 15500 + commits so far." }, { "code": null, "e": 4886, "s": 4807, "text": "The diagram given below shows the different layers of Apache Flink Ecosystem −" }, { "code": null, "e": 4987, "s": 4886, "text": "Apache Flink has multiple options from where it can Read/Write data. Below is a basic storage list −" }, { "code": null, "e": 5025, "s": 4987, "text": "HDFS (Hadoop Distributed File System)" }, { "code": null, "e": 5043, "s": 5025, "text": "Local File System" }, { "code": null, "e": 5046, "s": 5043, "text": "S3" }, { "code": null, "e": 5081, "s": 5046, "text": "RDBMS (MySQL, Oracle, MS SQL etc.)" }, { "code": null, "e": 5089, "s": 5081, "text": "MongoDB" }, { "code": null, "e": 5095, "s": 5089, "text": "HBase" }, { "code": null, "e": 5108, "s": 5095, "text": "Apache Kafka" }, { "code": null, "e": 5121, "s": 5108, "text": "Apache Flume" }, { "code": null, "e": 5234, "s": 5121, "text": "You can deploy Apache Fink in local mode, cluster mode or on cloud. Cluster mode can be standalone, YARN, MESOS." }, { "code": null, "e": 5281, "s": 5234, "text": "On cloud, Flink can be deployed on AWS or GCP." }, { "code": null, "e": 5426, "s": 5281, "text": "This is the runtime layer, which provides distributed processing, fault tolerance, reliability, native iterative processing capability and more." }, { "code": null, "e": 5776, "s": 5426, "text": "This is the top layer and most important layer of Apache Flink. It has Dataset API, which takes care of batch processing, and Datastream API, which takes care of stream processing. There are other libraries like Flink ML (for machine learning), Gelly (for graph processing ), Tables for SQL. This layer provides diverse capabilities to Apache Flink." }, { "code": null, "e": 6026, "s": 5776, "text": "Apache Flink works on Kappa architecture. Kappa architecture has a single processor - stream, which treats all input as stream and the streaming engine processes the data in real-time. Batch data in kappa architecture is a special case of streaming." }, { "code": null, "e": 6085, "s": 6026, "text": "The following diagram shows the Apache Flink Architecture." }, { "code": null, "e": 6206, "s": 6085, "text": "The key idea in Kappa architecture is to handle both batch and real-time data through a single stream processing engine." }, { "code": null, "e": 6661, "s": 6206, "text": "Most big data framework works on Lambda architecture, which has separate processors for batch and streaming data. In Lambda architecture, you have separate codebases for batch and stream views. For querying and getting the result, the codebases need to be merged. Not maintaining separate codebases/views and merging them is a pain, but Kappa architecture solves this issue as it has only one view − real-time, hence merging of codebase is not required." }, { "code": null, "e": 6840, "s": 6661, "text": "That does not mean Kappa architecture replaces Lambda architecture, it completely depends on the use-case and the application that decides which architecture would be preferable." }, { "code": null, "e": 6909, "s": 6840, "text": "The following diagram shows Apache Flink job execution architecture." }, { "code": null, "e": 6968, "s": 6909, "text": "It is a piece of code, which you run on the Flink Cluster." }, { "code": null, "e": 7115, "s": 6968, "text": "It is responsible for taking code (program) and constructing job dataflow graph, then passing it to JobManager. It also retrieves the Job results." }, { "code": null, "e": 7310, "s": 7115, "text": "After receiving the Job Dataflow Graph from Client, it is responsible for creating the execution graph. It assigns the job to TaskManagers in the cluster and supervises the execution of the job." }, { "code": null, "e": 7545, "s": 7310, "text": "It is responsible for executing all the tasks that have been assigned by JobManager. All the TaskManagers run the tasks in their separate slots in specified parallelism. It is responsible to send the status of the tasks to JobManager." }, { "code": null, "e": 7591, "s": 7545, "text": "The features of Apache Flink are as follows −" }, { "code": null, "e": 7667, "s": 7591, "text": "It has a streaming processor, which can run both batch and stream programs." }, { "code": null, "e": 7743, "s": 7667, "text": "It has a streaming processor, which can run both batch and stream programs." }, { "code": null, "e": 7788, "s": 7743, "text": "It can process data at lightning fast speed." }, { "code": null, "e": 7833, "s": 7788, "text": "It can process data at lightning fast speed." }, { "code": null, "e": 7875, "s": 7833, "text": "APIs available in Java, Scala and Python." }, { "code": null, "e": 7917, "s": 7875, "text": "APIs available in Java, Scala and Python." }, { "code": null, "e": 8005, "s": 7917, "text": "Provides APIs for all the common operations, which is very easy for programmers to use." }, { "code": null, "e": 8093, "s": 8005, "text": "Provides APIs for all the common operations, which is very easy for programmers to use." }, { "code": null, "e": 8158, "s": 8093, "text": "Processes data in low latency (nanoseconds) and high throughput." }, { "code": null, "e": 8223, "s": 8158, "text": "Processes data in low latency (nanoseconds) and high throughput." }, { "code": null, "e": 8319, "s": 8223, "text": "Its fault tolerant. If a node, application or a hardware fails, it does not affect the cluster." }, { "code": null, "e": 8415, "s": 8319, "text": "Its fault tolerant. If a node, application or a hardware fails, it does not affect the cluster." }, { "code": null, "e": 8520, "s": 8415, "text": "Can easily integrate with Apache Hadoop, Apache MapReduce, Apache Spark, HBase and other big data tools." }, { "code": null, "e": 8625, "s": 8520, "text": "Can easily integrate with Apache Hadoop, Apache MapReduce, Apache Spark, HBase and other big data tools." }, { "code": null, "e": 8688, "s": 8625, "text": "In-memory management can be customized for better computation." }, { "code": null, "e": 8751, "s": 8688, "text": "In-memory management can be customized for better computation." }, { "code": null, "e": 8824, "s": 8751, "text": "It is highly scalable and can scale upto thousands of node in a cluster." }, { "code": null, "e": 8897, "s": 8824, "text": "It is highly scalable and can scale upto thousands of node in a cluster." }, { "code": null, "e": 8941, "s": 8897, "text": "Windowing is very flexible in Apache Flink." }, { "code": null, "e": 8985, "s": 8941, "text": "Windowing is very flexible in Apache Flink." }, { "code": null, "e": 9066, "s": 8985, "text": "Provides Graph Processing, Machine Learning, Complex Event Processing libraries." }, { "code": null, "e": 9147, "s": 9066, "text": "Provides Graph Processing, Machine Learning, Complex Event Processing libraries." }, { "code": null, "e": 9228, "s": 9147, "text": "The following are the system requirements to download and work on Apache Flink −" }, { "code": null, "e": 9249, "s": 9228, "text": "Microsoft Windows 10" }, { "code": null, "e": 9266, "s": 9249, "text": "Ubuntu 16.04 LTS" }, { "code": null, "e": 9296, "s": 9266, "text": "Apple macOS 10.13/High Sierra" }, { "code": null, "e": 9336, "s": 9296, "text": "Memory - Minimum 4 GB, Recommended 8 GB" }, { "code": null, "e": 9358, "s": 9336, "text": "Storage Space - 30 GB" }, { "code": null, "e": 9430, "s": 9358, "text": "Note − Java 8 must be available with environment variables already set." }, { "code": null, "e": 9554, "s": 9430, "text": "Before the start with the setup/ installation of Apache Flink, let us check whether we have Java 8 installed in our system." }, { "code": null, "e": 9603, "s": 9554, "text": "We will now proceed by downloading Apache Flink." }, { "code": null, "e": 9696, "s": 9603, "text": "wget http://mirrors.estointernet.in/apache/flink/flink-1.7.1/flink-1.7.1-bin-scala_2.11.tgz\n" }, { "code": null, "e": 9726, "s": 9696, "text": "Now, uncompress the tar file." }, { "code": null, "e": 9767, "s": 9726, "text": "tar -xzf flink-1.7.1-bin-scala_2.11.tgz\n" }, { "code": null, "e": 9797, "s": 9767, "text": "Go to Flink's home directory." }, { "code": null, "e": 9814, "s": 9797, "text": "cd flink-1.7.1/\n" }, { "code": null, "e": 9839, "s": 9814, "text": "Start the Flink Cluster." }, { "code": null, "e": 9863, "s": 9839, "text": "./bin/start-cluster.sh\n" }, { "code": null, "e": 9951, "s": 9863, "text": "Open the Mozilla browser and go to the below URL, it will open the Flink Web Dashboard." }, { "code": null, "e": 9973, "s": 9951, "text": "http://localhost:8081" }, { "code": null, "e": 10042, "s": 9973, "text": "This is how the User Interface of Apache Flink Dashboard looks like." }, { "code": null, "e": 10083, "s": 10042, "text": "Now the Flink cluster is up and running." }, { "code": null, "e": 10427, "s": 10083, "text": "Flink has a rich set of APIs using which developers can perform transformations on both batch and real-time data. A variety of transformations includes mapping, filtering, sorting, joining, grouping and aggregating. These transformations by Apache Flink are performed on distributed data. Let us discuss the different APIs Apache Flink offers." }, { "code": null, "e": 10690, "s": 10427, "text": "Dataset API in Apache Flink is used to perform batch operations on the data over a period. This API can be used in Java, Scala and Python. It can apply different kinds of transformations on the datasets like filtering, mapping, aggregating, joining and grouping." }, { "code": null, "e": 10958, "s": 10690, "text": "Datasets are created from sources like local files or by reading a file from a particular sourse and the result data can be written on different sinks like distributed files or command line terminal. This API is supported by both Java and Scala programming languages." }, { "code": null, "e": 11003, "s": 10958, "text": "Here is a Wordcount program of Dataset API −" }, { "code": null, "e": 11772, "s": 11003, "text": "public class WordCountProg {\n public static void main(String[] args) throws Exception {\n final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();\n\n DataSet<String> text = env.fromElements(\n \"Hello\",\n \"My Dataset API Flink Program\");\n\n DataSet<Tuple2<String, Integer>> wordCounts = text\n .flatMap(new LineSplitter())\n .groupBy(0)\n .sum(1);\n\n wordCounts.print();\n }\n\n public static class LineSplitter implements FlatMapFunction<String, Tuple2<String, Integer>> {\n @Override\n public void flatMap(String line, Collector<Tuple2<String, Integer>> out) {\n for (String word : line.split(\" \")) {\n out.collect(new Tuple2<String, Integer>(word, 1));\n }\n }\n }\n}" }, { "code": null, "e": 12163, "s": 11772, "text": "This API is used for handling data in continuous stream. You can perform various operations like filtering, mapping, windowing, aggregating on the stream data. There are various sources on this data stream like message queues, files, socket streams and the result data can be written on different sinks like command line terminal. Both Java and Scala programming languages support this API." }, { "code": null, "e": 12314, "s": 12163, "text": "Here is a streaming Wordcount program of DataStream API, where you have continuous stream of word counts and the data is grouped in the second window." }, { "code": null, "e": 13481, "s": 12314, "text": "import org.apache.flink.api.common.functions.FlatMapFunction;\nimport org.apache.flink.api.java.tuple.Tuple2;\nimport org.apache.flink.streaming.api.datastream.DataStream;\nimport org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;\nimport org.apache.flink.streaming.api.windowing.time.Time;\nimport org.apache.flink.util.Collector;\npublic class WindowWordCountProg {\n public static void main(String[] args) throws Exception {\n StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();\n DataStream<Tuple2<String, Integer>> dataStream = env\n .socketTextStream(\"localhost\", 9999)\n .flatMap(new Splitter())\n .keyBy(0)\n .timeWindow(Time.seconds(5))\n .sum(1);\n dataStream.print();\n env.execute(\"Streaming WordCount Example\");\n }\n public static class Splitter implements FlatMapFunction<String, Tuple2<String, Integer>> {\n @Override\n public void flatMap(String sentence, Collector<Tuple2<String, Integer>> out) throws Exception {\n for (String word: sentence.split(\" \")) {\n out.collect(new Tuple2<String, Integer>(word, 1));\n }\n }\n }\n}" }, { "code": null, "e": 13936, "s": 13481, "text": "Table API is a relational API with SQL like expression language. This API can do both batch and stream processing. It can be embedded with Java and Scala Dataset and Datastream APIs. You can create tables from existing Datasets and Datastreams or from external data sources. Through this relational API, you can perform operations like join, aggregate, select and filter. Whether the input is batch or stream, the semantics of the query remains the same." }, { "code": null, "e": 13973, "s": 13936, "text": "Here is a sample Table API program −" }, { "code": null, "e": 14772, "s": 13973, "text": "// for batch programs use ExecutionEnvironment instead of StreamExecutionEnvironment\nval env = StreamExecutionEnvironment.getExecutionEnvironment\n\n// create a TableEnvironment\nval tableEnv = TableEnvironment.getTableEnvironment(env)\n\n// register a Table\ntableEnv.registerTable(\"table1\", ...) // or\ntableEnv.registerTableSource(\"table2\", ...) // or\ntableEnv.registerExternalCatalog(\"extCat\", ...)\n\n// register an output Table\ntableEnv.registerTableSink(\"outputTable\", ...);\n// create a Table from a Table API query\nval tapiResult = tableEnv.scan(\"table1\").select(...)\n// Create a Table from a SQL query\nval sqlResult = tableEnv.sqlQuery(\"SELECT ... FROM table2 ...\")\n\n// emit a Table API result Table to a TableSink, same for SQL result\ntapiResult.insertInto(\"outputTable\")\n\n// execute\nenv.execute()" }, { "code": null, "e": 14838, "s": 14772, "text": "In this chapter, we will learn how to create a Flink application." }, { "code": null, "e": 14902, "s": 14838, "text": "Open Eclipse IDE, click on New Project and Select Java Project." }, { "code": null, "e": 14941, "s": 14902, "text": "Give Project Name and click on Finish." }, { "code": null, "e": 15000, "s": 14941, "text": "Now, click on Finish as shown in the following screenshot." }, { "code": null, "e": 15048, "s": 15000, "text": "Now, right-click on src and go to New >> Class." }, { "code": null, "e": 15087, "s": 15048, "text": "Give a class name and click on Finish." }, { "code": null, "e": 15132, "s": 15087, "text": "Copy and paste the below code in the Editor." }, { "code": null, "e": 17343, "s": 15132, "text": "import org.apache.flink.api.common.functions.FlatMapFunction;\nimport org.apache.flink.api.java.DataSet;\nimport org.apache.flink.api.java.ExecutionEnvironment;\nimport org.apache.flink.api.java.tuple.Tuple2;\nimport org.apache.flink.api.java.utils.ParameterTool;\nimport org.apache.flink.util.Collector;\npublic class WordCount {\n\n // *************************************************************************\n // PROGRAM\n // *************************************************************************\n public static void main(String[] args) throws Exception {\n final ParameterTool params = ParameterTool.fromArgs(args);\n // set up the execution environment\n final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();\n // make parameters available in the web interface\n env.getConfig().setGlobalJobParameters(params);\n // get input data\n DataSet<String> text = env.readTextFile(params.get(\"input\"));\n DataSet<Tuple2<String, Integer>> counts =\n // split up the lines in pairs (2-tuples) containing: (word,1)\n text.flatMap(new Tokenizer())\n // group by the tuple field \"0\" and sum up tuple field \"1\"\n .groupBy(0)\n .sum(1);\n // emit result\n if (params.has(\"output\")) {\n counts.writeAsCsv(params.get(\"output\"), \"\\n\", \" \");\n // execute program\n env.execute(\"WordCount Example\");\n } else {\n System.out.println(\"Printing result to stdout. Use --output to specify output path.\");\n counts.print();\n }\n }\n \n // *************************************************************************\n // USER FUNCTIONS\n // *************************************************************************\n public static final class Tokenizer implements FlatMapFunction<String, Tuple2<String, Integer>> {\n public void flatMap(String value, Collector<Tuple2<String, Integer>> out) {\n // normalize and split the line\n String[] tokens = value.toLowerCase().split(\"\\\\W+\");\n // emit the pairs\n for (String token : tokens) {\n if (token.length() > 0) {\n out.collect(new Tuple2<>(token, 1));\n }\n }\n }\n }\n}" }, { "code": null, "e": 17441, "s": 17343, "text": "You will get many errors in the editor, because Flink libraries need to be added to this project." }, { "code": null, "e": 17507, "s": 17441, "text": "Right-click on the project >> Build Path >> Configure Build Path." }, { "code": null, "e": 17564, "s": 17507, "text": "Select the Libraries tab and click on Add External JARs." }, { "code": null, "e": 17637, "s": 17564, "text": "Go to Flink's lib directory, select all the 4 libraries and click on OK." }, { "code": null, "e": 17711, "s": 17637, "text": "Go to the Order and Export tab, select all the libraries and click on OK." }, { "code": null, "e": 17759, "s": 17711, "text": "You will see that the errors are no more there." }, { "code": null, "e": 17844, "s": 17759, "text": "Now, let us export this application. Right-click on the project and click on Export." }, { "code": null, "e": 17875, "s": 17844, "text": "Select JAR file and click Next" }, { "code": null, "e": 17917, "s": 17875, "text": "Give a destination path and click on Next" }, { "code": null, "e": 17932, "s": 17917, "text": "Click on Next>" }, { "code": null, "e": 18001, "s": 17932, "text": "Click on Browse, select the main class (WordCount) and click Finish." }, { "code": null, "e": 18047, "s": 18001, "text": "Note − Click OK, in case you get any warning." }, { "code": null, "e": 18130, "s": 18047, "text": "Run the below command. It will further run the Flink application you just created." }, { "code": null, "e": 18222, "s": 18130, "text": "./bin/flink run /home/ubuntu/wordcount.jar --input README.txt --output /home/ubuntu/output\n" }, { "code": null, "e": 18281, "s": 18222, "text": "In this chapter, we will learn how to run a Flink program." }, { "code": null, "e": 18340, "s": 18281, "text": "Let us run the Flink wordcount example on a Flink cluster." }, { "code": null, "e": 18412, "s": 18340, "text": "Go to Flink's home directory and run the below command in the terminal." }, { "code": null, "e": 18518, "s": 18412, "text": "bin/flink run examples/batch/WordCount.jar -input README.txt -output /home/ubuntu/flink-1.7.1/output.txt\n" }, { "code": null, "e": 18599, "s": 18518, "text": "Go to Flink dashboard, you will be able to see a completed job with its details." }, { "code": null, "e": 18675, "s": 18599, "text": "If you click on Completed Jobs, you will get detailed overview of the jobs." }, { "code": null, "e": 18756, "s": 18675, "text": "To check the output of wordcount program, run the below command in the terminal." }, { "code": null, "e": 18772, "s": 18756, "text": "cat output.txt\n" }, { "code": null, "e": 18850, "s": 18772, "text": "In this chapter, we will learn about the different libraries of Apache Flink." }, { "code": null, "e": 19120, "s": 18850, "text": "FlinkCEP is an API in Apache Flink, which analyses event patterns on continuous streaming data. These events are near real time, which have high throughput and low latency. This API is used mostly on Sensor data, which come in real-time and are very complex to process." }, { "code": null, "e": 19386, "s": 19120, "text": "CEP analyses the pattern of the input stream and gives the result very soon. It has the ability to provide real-time notifications and alerts in case the event pattern is complex. FlinkCEP can connect to different kind of input sources and analyse patterns in them." }, { "code": null, "e": 19439, "s": 19386, "text": "This how a sample architecture with CEP looks like −" }, { "code": null, "e": 19651, "s": 19439, "text": "Sensor data will be coming in from different sources, Kafka will act as a distributed messaging framework, which will distribute the streams to Apache Flink, and FlinkCEP will analyse the complex event patterns." }, { "code": null, "e": 19880, "s": 19651, "text": "You can write programs in Apache Flink for complex event processing using Pattern API. It allows you to decide the event patterns to detect from the continuous stream data. Below are some of the most commonly used CEP patterns −" }, { "code": null, "e": 19988, "s": 19880, "text": "It is used to define the starting state. The following program shows how it is defined in a Flink program −" }, { "code": null, "e": 20034, "s": 19988, "text": "Pattern<Event, ?> next = start.next(\"next\");\n" }, { "code": null, "e": 20096, "s": 20034, "text": "It is used to define a filter condition in the current state." }, { "code": null, "e": 20234, "s": 20096, "text": "patternState.where(new FilterFunction <Event>() { \n @Override \n public boolean filter(Event value) throws Exception { \n } \n});\n" }, { "code": null, "e": 20335, "s": 20234, "text": "It is used to append a new pattern state and the matching event needed to pass the previous pattern." }, { "code": null, "e": 20381, "s": 20335, "text": "Pattern<Event, ?> next = start.next(\"next\");\n" }, { "code": null, "e": 20479, "s": 20381, "text": "It is used to append a new pattern state but here other events can occur b/w two matching events." }, { "code": null, "e": 20537, "s": 20479, "text": "Pattern<Event, ?> followedBy = start.followedBy(\"next\");\n" }, { "code": null, "e": 20973, "s": 20537, "text": "Apache Flink's Graph API is Gelly. Gelly is used to perform graph analysis on Flink applications using a set of methods and utilities. You can analyse huge graphs using Apache Flink API in a distributed fashion with Gelly. There are other graph libraries also like Apache Giraph for the same purpose, but since Gelly is used on top of Apache Flink, it uses single API. This is very helpful from development and operation point of view." }, { "code": null, "e": 21028, "s": 20973, "text": "Let us run an example using Apache Flink API − Gelly." }, { "code": null, "e": 21164, "s": 21028, "text": "Firstly, you need to copy 2 Gelly jar files from opt directory of Apache Flink to its lib directory. Then run flink-gelly-examples jar." }, { "code": null, "e": 21250, "s": 21164, "text": "cp opt/flink-gelly* lib/ \n./bin/flink run examples/gelly/flink-gelly-examples_*.jar \n" }, { "code": null, "e": 21287, "s": 21250, "text": "Let us now run the PageRank example." }, { "code": null, "e": 21511, "s": 21287, "text": "PageRank computes a per-vertex score, which is the sum of PageRank scores transmitted over in-edges. Each vertex's score is divided evenly among out-edges. High-scoring vertices are linked to by other high-scoring vertices." }, { "code": null, "e": 21569, "s": 21511, "text": "The result contains the vertex ID and the PageRank score." }, { "code": null, "e": 21872, "s": 21569, "text": "usage: flink run examples/flink-gelly-examples_<version>.jar --algorithm PageRank [algorithm options] --input <input> [input options] --output <output> [output options] \n\n./bin/flink run examples/gelly/flink-gelly-examples_*.jar --algorithm PageRank --input CycleGraph --vertex_count 2 --output Print \n" }, { "code": null, "e": 22218, "s": 21872, "text": "Apache Flink's Machine Learning library is called FlinkML. Since usage of machine learning has been increasing exponentially over the last 5 years, Flink community decided to add this machine learning APO also in its ecosystem. The list of contributors and algorithms are increasing in FlinkML. This API is not a part of binary distribution yet." }, { "code": null, "e": 22274, "s": 22218, "text": "Here is an example of linear regression using FlinkML −" }, { "code": null, "e": 23044, "s": 22274, "text": "// LabeledVector is a feature vector with a label (class or real value)\nval trainingData: DataSet[LabeledVector] = ...\nval testingData: DataSet[Vector] = ...\n\n// Alternatively, a Splitter is used to break up a DataSet into training and testing data.\nval dataSet: DataSet[LabeledVector] = ...\nval trainTestData: DataSet[TrainTestDataSet] = Splitter.trainTestSplit(dataSet)\nval trainingData: DataSet[LabeledVector] = trainTestData.training\nval testingData: DataSet[Vector] = trainTestData.testing.map(lv => lv.vector)\nval mlr = MultipleLinearRegression()\n\n.setStepsize(1.0)\n.setIterations(100)\n.setConvergenceThreshold(0.001)\nmlr.fit(trainingData)\n\n// The fitted model can now be used to make predictions\nval predictions: DataSet[LabeledVector] = mlr.predict(testingData)" }, { "code": null, "e": 23156, "s": 23044, "text": "Inside flink-1.7.1/examples/batch/ path, you will find KMeans.jar file. Let us run this sample FlinkML example." }, { "code": null, "e": 23235, "s": 23156, "text": "This example program is run using the default point and the centroid data set." }, { "code": null, "e": 23293, "s": 23235, "text": "./bin/flink run examples/batch/KMeans.jar --output Print\n" }, { "code": null, "e": 23363, "s": 23293, "text": "In this chapter, we will understand a few test cases in Apache Flink." }, { "code": null, "e": 23753, "s": 23363, "text": "Bouygues Telecom is one of the largest telecom organization in France. It has 11+ million mobile subscribers and 2.5+ million fixed customers. Bouygues heard about Apache Flink for the first time in a Hadoop Group Meeting held at Paris. Since then they have been using Flink for multiple use-cases. They have been processing billions of messages in a day in real-time through Apache Flink." }, { "code": null, "e": 24216, "s": 23753, "text": "This is what Bouygues has to say about Apache Flink: \"We ended up with Flink because the system supports true streaming - both at the API and at the runtime level, giving us the programmability and low latency that we were looking for. In addition, we were able to get our system up and running with Flink in a fraction of the time compared to other solutions, which resulted in more available developer resources for expanding the business logic in the system.\"" }, { "code": null, "e": 24363, "s": 24216, "text": "At Bouygues, customer experience is the highest priority. They analyse data in real-time so that they can give below insights to their engineers −" }, { "code": null, "e": 24412, "s": 24363, "text": "Real-Time Customer Experience over their network" }, { "code": null, "e": 24461, "s": 24412, "text": "Real-Time Customer Experience over their network" }, { "code": null, "e": 24503, "s": 24461, "text": "What is happening globally on the network" }, { "code": null, "e": 24545, "s": 24503, "text": "What is happening globally on the network" }, { "code": null, "e": 24580, "s": 24545, "text": "Network evaluations and operations" }, { "code": null, "e": 24615, "s": 24580, "text": "Network evaluations and operations" }, { "code": null, "e": 24940, "s": 24615, "text": "They created a system called LUX (Logged User Experience) which processed massive log data from network equipment with internal data reference to give quality of experience indicators which will log their customer experience and build an alarming functionality to detect any failure in consumption of data within 60 seconds." }, { "code": null, "e": 25158, "s": 24940, "text": "To achieve this, they needed a framework which can take massive data in real-time, is easy to set up and provides rich set of APIs for processing the streamed data. Apache Flink was a perfect fit for Bouygues Telecom." }, { "code": null, "e": 25366, "s": 25158, "text": "Alibaba is the largest ecommerce retail company in the world with 394 billion $ revenue in 2015. Alibaba search is the entry point to all the customers, which shows all the search and recommends accordingly." }, { "code": null, "e": 25493, "s": 25366, "text": "Alibaba uses Apache Flink in its search engine to show results in real-time with highest accuracy and relevancy for each user." }, { "code": null, "e": 25542, "s": 25493, "text": "Alibaba was looking for a framework, which was −" }, { "code": null, "e": 25629, "s": 25542, "text": "Very Agile in maintaining one codebase for their entire search infrastructure process." }, { "code": null, "e": 25716, "s": 25629, "text": "Very Agile in maintaining one codebase for their entire search infrastructure process." }, { "code": null, "e": 25798, "s": 25716, "text": "Provides low latency for the availability changes in the products on the website." }, { "code": null, "e": 25880, "s": 25798, "text": "Provides low latency for the availability changes in the products on the website." }, { "code": null, "e": 25911, "s": 25880, "text": "Consistent and cost effective." }, { "code": null, "e": 25942, "s": 25911, "text": "Consistent and cost effective." }, { "code": null, "e": 26153, "s": 25942, "text": "Apache Flink qualified for all the above requirements. They need a framework, which has a single processing engine and can process both batch and stream data with same engine and that is what Apache Flink does." }, { "code": null, "e": 26337, "s": 26153, "text": "They also use Blink, a forked version for Flink to meet some unique requirements for their search. They are also using Apache Flink's Table API with few improvements for their search." }, { "code": null, "e": 26748, "s": 26337, "text": "This is what Alibaba had to say about apache Flink: \"Looking back, it was no doubt a huge year for Blink and Flink at Alibaba. No one thought that we would make this much progress in a year, and we are very grateful to all the people who helped us in the community. Flink is proven to work at the very large scale. We are more committed than ever to continue our work with the community to move Flink forward!\"" }, { "code": null, "e": 26900, "s": 26748, "text": "Here is a comprehensive table, which shows the comparison between three most popular big data frameworks: Apache Flink, Apache Spark and Apache Hadoop." }, { "code": null, "e": 26915, "s": 26900, "text": "Year of Origin" }, { "code": null, "e": 26931, "s": 26915, "text": "Place of Origin" }, { "code": null, "e": 26954, "s": 26931, "text": "Data Processing Engine" }, { "code": null, "e": 26971, "s": 26954, "text": "Processing Speed" }, { "code": null, "e": 26993, "s": 26971, "text": "Programming Languages" }, { "code": null, "e": 27011, "s": 26993, "text": "Programming Model" }, { "code": null, "e": 27025, "s": 27011, "text": "Data Transfer" }, { "code": null, "e": 27043, "s": 27025, "text": "Memory Management" }, { "code": null, "e": 27051, "s": 27043, "text": "Latency" }, { "code": null, "e": 27062, "s": 27051, "text": "Throughput" }, { "code": null, "e": 27075, "s": 27062, "text": "Optimization" }, { "code": null, "e": 27079, "s": 27075, "text": "API" }, { "code": null, "e": 27097, "s": 27079, "text": "Streaming Support" }, { "code": null, "e": 27109, "s": 27097, "text": "SQL Support" }, { "code": null, "e": 27123, "s": 27109, "text": "Graph Support" }, { "code": null, "e": 27148, "s": 27123, "text": "Machine Learning Support" }, { "code": null, "e": 27455, "s": 27148, "text": "The comparison table that we saw in the previous chapter concludes the pointers pretty much. Apache Flink is the most suited framework for real-time processing and use cases. Its single engine system is unique which can process both batch and streaming data with different APIs like Dataset and DataStream." }, { "code": null, "e": 27720, "s": 27455, "text": "It does not mean Hadoop and Spark are out of the game, the selection of the most suited big data framework always depends and vary from use case to use case. There can be several use cases where a combination of Hadoop and Flink or Spark and Flink might be suited." }, { "code": null, "e": 27913, "s": 27720, "text": "Nevertheless, Flink is the best framework for real time processing currently. The growth of Apache Flink has been amazing and the number of contributors to its community is growing day by day." }, { "code": null, "e": 27929, "s": 27913, "text": "Happy Flinking!" }, { "code": null, "e": 27964, "s": 27929, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 27983, "s": 27964, "text": " Arnab Chakraborty" }, { "code": null, "e": 28018, "s": 27983, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 28039, "s": 28018, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 28072, "s": 28039, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 28085, "s": 28072, "text": " Nilay Mehta" }, { "code": null, "e": 28120, "s": 28085, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 28138, "s": 28120, "text": " Bigdata Engineer" }, { "code": null, "e": 28171, "s": 28138, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 28189, "s": 28171, "text": " Bigdata Engineer" }, { "code": null, "e": 28222, "s": 28189, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 28240, "s": 28222, "text": " Bigdata Engineer" }, { "code": null, "e": 28247, "s": 28240, "text": " Print" }, { "code": null, "e": 28258, "s": 28247, "text": " Add Notes" } ]
java.util.zip.Inflater.read() Method Example
The java.util.zip.InflaterInputStream.read() method reads a byte of uncompressed data. This method will block until enough input is available for decompression. Following is the declaration for java.util.zip.InflaterInputStream.read() method. public int read() throws IOException the byte read, or -1 if end of compressed input is reached. IOException − if an I/O error occurs. IOException − if an I/O error occurs. The following example shows the usage of java.util.zip.InflaterInputStream.read() method. package com.tutorialspoint; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.zip.DataFormatException; import java.util.zip.Deflater; import java.util.zip.InflaterInputStream; public class InflaterInputStreamDemo { public static void main(String[] args) throws DataFormatException, IOException { String message = "Welcome to TutorialsPoint.com;" +"Welcome to TutorialsPoint.com;" +"Welcome to TutorialsPoint.com;" +"Welcome to TutorialsPoint.com;" +"Welcome to TutorialsPoint.com;" +"Welcome to TutorialsPoint.com;" +"Welcome to TutorialsPoint.com;" +"Welcome to TutorialsPoint.com;" +"Welcome to TutorialsPoint.com;" +"Welcome to TutorialsPoint.com;"; System.out.println("Original Message length : " + message.length()); byte[] input = message.getBytes("UTF-8"); int length = message.length(); // Compress the bytes byte[] output = new byte[1024]; Deflater deflater = new Deflater(); deflater.setInput(input); deflater.finish(); int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH); System.out.println("Total uncompressed bytes input :" + deflater.getTotalIn()); System.out.println("Compressed Message Checksum :" + deflater.getAdler()); deflater.finished(); System.out.println("Compressed Message length : " + compressedDataLength); ByteArrayInputStream bin = new ByteArrayInputStream(output); InflaterInputStream inflaterInputStream = new InflaterInputStream(bin); byte[] result = new byte[1024]; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); if(inflaterInputStream.markSupported()){ inflaterInputStream.mark(0); } if(inflaterInputStream.markSupported()){ inflaterInputStream.reset(); } while(inflaterInputStream.available() != 0){ buffer.write(inflaterInputStream.read()); } inflaterInputStream.close(); // Decode the bytes into a String String message1 = new String(buffer.toByteArray(),0, length,"UTF-8"); System.out.println(message.equals(message1)); } } Let us compile and run the above program, this will produce the following result − Original Message length : 300 Total uncompressed bytes input :300 Compressed Message Checksum :368538129 Compressed Message length : 42 true Print Add Notes Bookmark this page
[ { "code": null, "e": 2353, "s": 2192, "text": "The java.util.zip.InflaterInputStream.read() method reads a byte of uncompressed data. This method will block until enough input is available for decompression." }, { "code": null, "e": 2435, "s": 2353, "text": "Following is the declaration for java.util.zip.InflaterInputStream.read() method." }, { "code": null, "e": 2473, "s": 2435, "text": "public int read() throws IOException\n" }, { "code": null, "e": 2533, "s": 2473, "text": "the byte read, or -1 if end of compressed input is reached." }, { "code": null, "e": 2572, "s": 2533, "text": "IOException − if an I/O error occurs." }, { "code": null, "e": 2611, "s": 2572, "text": "IOException − if an I/O error occurs." }, { "code": null, "e": 2701, "s": 2611, "text": "The following example shows the usage of java.util.zip.InflaterInputStream.read() method." }, { "code": null, "e": 4987, "s": 2701, "text": "package com.tutorialspoint;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.util.zip.DataFormatException;\nimport java.util.zip.Deflater;\nimport java.util.zip.InflaterInputStream;\n\npublic class InflaterInputStreamDemo {\n public static void main(String[] args) throws DataFormatException, IOException {\n String message = \"Welcome to TutorialsPoint.com;\"\n +\"Welcome to TutorialsPoint.com;\"\n +\"Welcome to TutorialsPoint.com;\"\n +\"Welcome to TutorialsPoint.com;\"\n +\"Welcome to TutorialsPoint.com;\"\n +\"Welcome to TutorialsPoint.com;\"\n +\"Welcome to TutorialsPoint.com;\"\n +\"Welcome to TutorialsPoint.com;\"\n +\"Welcome to TutorialsPoint.com;\"\n +\"Welcome to TutorialsPoint.com;\";\n System.out.println(\"Original Message length : \" + message.length());\n byte[] input = message.getBytes(\"UTF-8\");\n int length = message.length();\n // Compress the bytes\n byte[] output = new byte[1024];\n Deflater deflater = new Deflater();\n deflater.setInput(input);\n \n deflater.finish();\n int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);\n System.out.println(\"Total uncompressed bytes input :\" + deflater.getTotalIn());\n System.out.println(\"Compressed Message Checksum :\" + deflater.getAdler()); \n deflater.finished();\n\n System.out.println(\"Compressed Message length : \" + compressedDataLength);\n \n ByteArrayInputStream bin = new ByteArrayInputStream(output);\n InflaterInputStream inflaterInputStream = new InflaterInputStream(bin);\n byte[] result = new byte[1024];\n\n ByteArrayOutputStream buffer = new ByteArrayOutputStream();\n if(inflaterInputStream.markSupported()){\n inflaterInputStream.mark(0); \n }\n if(inflaterInputStream.markSupported()){\n inflaterInputStream.reset(); \n }\n while(inflaterInputStream.available() != 0){\n buffer.write(inflaterInputStream.read());\n }\n\n inflaterInputStream.close();\n // Decode the bytes into a String\n String message1 = new String(buffer.toByteArray(),0, length,\"UTF-8\");\n System.out.println(message.equals(message1));\n }\n}" }, { "code": null, "e": 5070, "s": 4987, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 5212, "s": 5070, "text": "Original Message length : 300\nTotal uncompressed bytes input :300\nCompressed Message Checksum :368538129\nCompressed Message length : 42\ntrue\n" }, { "code": null, "e": 5219, "s": 5212, "text": " Print" }, { "code": null, "e": 5230, "s": 5219, "text": " Add Notes" } ]
Add Text Inside the Plot in Matplotlib - GeeksforGeeks
03 Jan, 2021 In this article, We are going to see how to add text inside the plot in Matplotlib. The matplotlib.pyplot.text() function is used to add text inside the plot. The syntax adds text at an arbitrary location of the axes. It also supports mathematical expressions. Syntax: matplotlib.pyplot.text(x, y, s, fontdict=None, **kwargs) Parameters: where x, y – coordinates s – text to be added inside the plot(string) fontdict – optional parameter. It overrides the default text properties **kwargs – text properties Example 1: Adding mathematical equations inside the plot. Python3 import matplotlib.pyplot as pltimport numpy as np x = np.arange(-10, 10, 0.01)y = x**2 #adding text inside the plotplt.text(-5, 60, 'Parabola $Y = x^2$', fontsize = 22) plt.plot(x, y, c='g') plt.xlabel("X-axis", fontsize = 15)plt.ylabel("Y-axis",fontsize = 15) plt.show() Output: Example 2: Adding rectangular box around the text by using the keyword ‘bbox’. bbox is a dictionary of Rectangle properties. Python3 import matplotlib.pyplot as pltimport numpy as np x = np.arange(-10, 10, 0.01)y = x**2 plt.xlabel("X-axis", fontsize = 15)plt.ylabel("Y-axis",fontsize = 15) #Adding text inside a rectangular box by using the keyword 'bbox'plt.text(-5, 60, 'Parabola $Y = x^2$', fontsize = 22, bbox = dict(facecolor = 'red', alpha = 0.5)) plt.plot(x, y, c = 'g') plt.show() Output: Example 3: Adding the text “Sine wave” inside the plot. Python3 import matplotlib.pyplot as pltimport numpy as np x = np.arange(0, 10, 0.1)y = np.sin(x) plt.plot(x,y) plt.text(3.5, 0.9, 'Sine wave', fontsize = 23) plt.xlabel('X-axis', fontsize = 15)plt.ylabel('Y-axis', fontsize = 15) #plt.grid(True, which='both')plt.show() Output: Example 4: Using annotation along with text inside plot Python3 import matplotlib.pyplot as pltimport numpy as np x = ['Rani', 'Meena', 'Raju', 'Jhansi', 'Ram']y = [5, 7, 9, 2, 6] plt.bar(x,y) plt.text(3, 7, 'Student Marks', fontsize = 18, color = 'g') plt.xlabel('Students', fontsize = 15)plt.ylabel('Marks', fontsize = 15) plt.annotate('Highest scored', xy = (2.4, 8), fontsize = 16, xytext = (3, 9), arrowprops = dict(facecolor = 'red'), color = 'g') plt.show() Output: Picked Python-matplotlib Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Python OOPs Concepts Python | Get unique values from a list Check if element exists in list in Python Python Classes and Objects Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Pandas dataframe.groupby() Create a directory in Python
[ { "code": null, "e": 24238, "s": 24210, "text": "\n03 Jan, 2021" }, { "code": null, "e": 24499, "s": 24238, "text": "In this article, We are going to see how to add text inside the plot in Matplotlib. The matplotlib.pyplot.text() function is used to add text inside the plot. The syntax adds text at an arbitrary location of the axes. It also supports mathematical expressions." }, { "code": null, "e": 24564, "s": 24499, "text": "Syntax: matplotlib.pyplot.text(x, y, s, fontdict=None, **kwargs)" }, { "code": null, "e": 24576, "s": 24564, "text": "Parameters:" }, { "code": null, "e": 24601, "s": 24576, "text": "where x, y – coordinates" }, { "code": null, "e": 24646, "s": 24601, "text": "s – text to be added inside the plot(string)" }, { "code": null, "e": 24718, "s": 24646, "text": "fontdict – optional parameter. It overrides the default text properties" }, { "code": null, "e": 24745, "s": 24718, "text": "**kwargs – text properties" }, { "code": null, "e": 24803, "s": 24745, "text": "Example 1: Adding mathematical equations inside the plot." }, { "code": null, "e": 24811, "s": 24803, "text": "Python3" }, { "code": "import matplotlib.pyplot as pltimport numpy as np x = np.arange(-10, 10, 0.01)y = x**2 #adding text inside the plotplt.text(-5, 60, 'Parabola $Y = x^2$', fontsize = 22) plt.plot(x, y, c='g') plt.xlabel(\"X-axis\", fontsize = 15)plt.ylabel(\"Y-axis\",fontsize = 15) plt.show()", "e": 25088, "s": 24811, "text": null }, { "code": null, "e": 25096, "s": 25088, "text": "Output:" }, { "code": null, "e": 25221, "s": 25096, "text": "Example 2: Adding rectangular box around the text by using the keyword ‘bbox’. bbox is a dictionary of Rectangle properties." }, { "code": null, "e": 25229, "s": 25221, "text": "Python3" }, { "code": "import matplotlib.pyplot as pltimport numpy as np x = np.arange(-10, 10, 0.01)y = x**2 plt.xlabel(\"X-axis\", fontsize = 15)plt.ylabel(\"Y-axis\",fontsize = 15) #Adding text inside a rectangular box by using the keyword 'bbox'plt.text(-5, 60, 'Parabola $Y = x^2$', fontsize = 22, bbox = dict(facecolor = 'red', alpha = 0.5)) plt.plot(x, y, c = 'g') plt.show()", "e": 25599, "s": 25229, "text": null }, { "code": null, "e": 25607, "s": 25599, "text": "Output:" }, { "code": null, "e": 25663, "s": 25607, "text": "Example 3: Adding the text “Sine wave” inside the plot." }, { "code": null, "e": 25671, "s": 25663, "text": "Python3" }, { "code": "import matplotlib.pyplot as pltimport numpy as np x = np.arange(0, 10, 0.1)y = np.sin(x) plt.plot(x,y) plt.text(3.5, 0.9, 'Sine wave', fontsize = 23) plt.xlabel('X-axis', fontsize = 15)plt.ylabel('Y-axis', fontsize = 15) #plt.grid(True, which='both')plt.show()", "e": 25937, "s": 25671, "text": null }, { "code": null, "e": 25946, "s": 25937, "text": "Output: " }, { "code": null, "e": 26002, "s": 25946, "text": "Example 4: Using annotation along with text inside plot" }, { "code": null, "e": 26010, "s": 26002, "text": "Python3" }, { "code": "import matplotlib.pyplot as pltimport numpy as np x = ['Rani', 'Meena', 'Raju', 'Jhansi', 'Ram']y = [5, 7, 9, 2, 6] plt.bar(x,y) plt.text(3, 7, 'Student Marks', fontsize = 18, color = 'g') plt.xlabel('Students', fontsize = 15)plt.ylabel('Marks', fontsize = 15) plt.annotate('Highest scored', xy = (2.4, 8), fontsize = 16, xytext = (3, 9), arrowprops = dict(facecolor = 'red'), color = 'g') plt.show()", "e": 26464, "s": 26010, "text": null }, { "code": null, "e": 26472, "s": 26464, "text": "Output:" }, { "code": null, "e": 26479, "s": 26472, "text": "Picked" }, { "code": null, "e": 26497, "s": 26479, "text": "Python-matplotlib" }, { "code": null, "e": 26521, "s": 26497, "text": "Technical Scripter 2020" }, { "code": null, "e": 26528, "s": 26521, "text": "Python" }, { "code": null, "e": 26547, "s": 26528, "text": "Technical Scripter" }, { "code": null, "e": 26645, "s": 26547, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26654, "s": 26645, "text": "Comments" }, { "code": null, "e": 26667, "s": 26654, "text": "Old Comments" }, { "code": null, "e": 26699, "s": 26667, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26755, "s": 26699, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26776, "s": 26755, "text": "Python OOPs Concepts" }, { "code": null, "e": 26815, "s": 26776, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26857, "s": 26815, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26884, "s": 26857, "text": "Python Classes and Objects" }, { "code": null, "e": 26915, "s": 26884, "text": "Python | os.path.join() method" }, { "code": null, "e": 26957, "s": 26915, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26993, "s": 26957, "text": "Python | Pandas dataframe.groupby()" } ]
Types of Ensemble methods in Machine learning | by Anju Rajbangshi | Towards Data Science
In my previous article, we discussed about the different types of regression in machine learning. So, today I am going to focus on the various ensemble methods in data science. One thing I have experienced in the course of my career is that while learning any skill , things become easier when we try to relate concepts to events we face in our everyday lives. It’s effortless remembering things when we have a real life analogy. Hence, keeping that in mind, we will look at the various ensemble techniques by comparing it to everyday scenarios. 1. Introduction 2. Types of ensemble methods 3. Similarities between bagging and boosting methods 4. Differences between both the methods 5. Types of voting 6. Detailed understanding of the concepts Bagging Boosting 7. Conclusion What is an ensemble? In simple English, ensemble refers to a group of items. For e.g: a group of ministers, a group of dancers etc. What is ensemble method in machine learning? An ensemble method is a technique which uses multiple independent similar or different models/weak learners to derive an output or make some predictions. For e.g. A random forest is an ensemble of multiple decision trees. An ensemble can also be built with a combination of different models like random forest, SVM, Logistic regression etc. So now, let’s compare it with a real life example. Suppose a bill is passed in the parliament and a meeting is held for the same with a group of ministers. Instead of the President or the prime minister taking the decision alone by themselves might not be a very good idea as this accounts for dictatorship and the results might not be so much in favor of the public. So, this analogy can be referred to a single model like Decision Tree, Logistic Regression etc in machine learning and they will always slightly perform less better than the ensemble methods. However, if a meeting is held between different ministers , let’s say four of them, each of them will provide an opinion with pros and cons. And finally, the best opinion will be picked based on majority voting. This is exactly what ensemble method is. Minister 1: based on his pros and cons, says the bill should be passed. Minister 2: based on his pros and cons, says the bill is not useful and might trigger a lot of challenges. Hence should not be passed. Minister 3: Says bill can be passed. Minister 4: Also says bill can be passed. Similarly, we can see below that different models are used and based on the output of each, the final decision will be made on the majority voting. Why do we need ensemble techniques? As we all know, the errors and predictions in any machine learning models are adversely influenced by bias, variance and noise. In order to combat these disadvantages, ensemble methods are used. There are many ensemble techniques available but we will discuss about the below two most widely used methods: 1. Bagging 2. Boosting Let us first understand the similarities and differences between both of the terminologies. · Both the methods can be used for classification (discrete output) and regression (continuous output) problems. · ­Both methods are better in performance compared to single models as they aggregate the output of all the weak learners via voting thereby leading to more accuracy in the predictions. There are two types of voting used to aggregate the output of all the weak learners. Hard voting — If we receive the output of each weak learner in classes (for e.g: 0/1), and finally we select the output class which was returned in majority, then this method is called hard voting. For instance: In our example of the group of ministers, since 3 ministers were in favor of the bill, the final decision was made to pass the bill. This is hard voting. Majority wins. Soft voting — There are many algorithms which also provide us with prediction probabilities and if we receive the output in probabilities, we take the average of the probabilities of each of the classes and whichever class is having the highest average will be the final prediction. This way of prediction is called Soft voting and is better than hard voting as we receive more information in terms of probability. Another important thing to remember is, this method of voting is used as a default technique for ensembles like random forest. Let’s understand these two concepts using below diagrams where 1 is class 1 and 0 is class 0. Also known as Bootstrap aggregating because the training set is divided into multiple sub samples and fed to each weak learner(for e.g.: each decision tree). And each sub sample contains a few set of features along with a few observations selected randomly. Since the main idea of this article is to understand the concepts in Layman terms, let us take an easy example to comprehend bagging. We all attend interviews right and the interview process is the most simple scenario I could come across which is analogous to Bagging. Suppose you went to attend an interview and as soon as you enter the room, you see five stern looking people sitting there to lash out all their questions at you . What do you do? Feel nervous and storm out of the room !! No right? You went there because you need the job and you know you are bold enough , intelligent enough to face whatever comes your way and you greet them anyway and sit down in front of them. So, let’s face this. Now consider each of the five interviewers are going to interview the candidate on five different aspects say aptitude , technical -basic ,technical- advanced, communication and management skills . Also, the company might already have prepared a set of questions based on the different aspects to test the candidate’s skills. And let’s name this as ‘question set’. So, the interview starts now. And our target variable here would be if the candidate gets selected or not. Interviewer 1 — The interviewer 1 starts testing your aptitude skills taking a sample of aptitude based questions from the ‘question set’ and sets some probabilities whether you should be selected or not. Interviewer 2 — The interviewer 2 also starts testing your basic technical skills, again taking a sample of preliminary technical questions from the’ question set’ and sets some probabilities whether you should be selected or not. Interviewer 3 — Similarly, the interviewer 3 starts testing your advanced technical skills taking another sample of slightly difficult technical questions from the’ question set’ and again sets some probabilities whether you should be selected or not. Now, It can also be possible that he asks you some questions picked randomly from the ‘question set’ but is similar and was already asked in basic technical test or any of the previous tests . Such a scenario is called bootstrap in bagging method as the same sample may be picked up again due to the use of random sampling with replacement. Interviewer 4 & Interviewer 5: Interviewer 4 and interviewer 5 repeats the same process as above, testing the candidate’s communication and management skills taking a sample of related questions from the ‘question set’ and accordingly sets some probabilities whether to select or not. Result: Finally the candidate is done with the interview and he comes out of the room leaving the interviewers to analyse their respective scores about his skills based on the sub samples of questions from the ‘question set’ that he was scored upon . Ultimately they aggregate all of their individual opinions and come out with the final decision whether to select the candidate or not. This is exactly similar to ensemble methods. Let’s try out a few ensemble methods using python and compare their accuracy corresponding to a few single models. Note: The jupyter notebook with complete code is available in github. I am using Advertisement Success dataset from Kaggle for this purpose and want to predict the success of an Ad. a. Decision tree # Decision tree classifier with grid seacrh CV and model evaluation using accuracy score, precision score and AUC/ROC curve.from sklearn.tree import DecisionTreeClassifierfrom sklearn.model_selection import GridSearchCVparameters = {'max_features': [0.5,0.6,0.7,0.8,0.9,1.0], 'max_depth': [2,3,4,5,6,7],'min_samples_leaf':[1,10,100],'random_state':[14]} clf = GridSearchCV(DecisionTreeClassifier(), parameters, cv=5, scoring='roc_auc')clf.fit(X_train, y_train) Evaluation metrics of Decision Tree applied on example data : AUC score is 85.84%. Decision trees are always prone to overfitting if we don’t choose the right parameters like minimum sample of leaf, minimum sample of nodes, maximum depth of the tree as higher the depth , more minutely will the model capture the data points of the training set leading to excellent predictions in the training dataset itself but will fail on new data. Hence, ensemble methods are one of the techniques which helps to reduce the variance thereby solving overfitting encountered by a single decision tree. b. Single Logistic Regression classifier #Single Logistic Regressionfrom sklearn.linear_model import LogisticRegressionlog = LogisticRegression(random_state=0, solver='lbfgs') log.fit(X_train, y_train)y_pred = log.predict(X_test) Evaluation Metric of Single Logistic regression classifier applied on example data: AUC score is 83.84 %. Few examples are Random Forest , Extra tree classifiers/regressors, ensemble of linear regressors, ensemble of logistic regression classifiers, ensemble of SVMs etc. a. Random forest — an ensemble of multiple decision trees from sklearn.ensemble import RandomForestClassifierparameters = {'n_estimators':[700],'n_jobs':[-1], 'max_features': [0.5,0.7,0.9], 'max_depth': [3,5,7],'min_samples_leaf':[1,10],'random_state':[14]} clf1 = GridSearchCV(RandomForestClassifier(), parameters, cv=5, scoring='roc_auc')clf1.fit(X_train, y_train) Evaluation metrics of random forest applied on example data: AUC score is 86.53 %. b. Ensemble of logistic regression classifiers. When we use an ensemble of same classifiers, Sklearn’s BaggingClassifier is used to get the OOB (Out of bag) score which is a very important score in bagging to examine the performance of the classifiers as it gives us an idea of the accuracy to be achieved on the test set. As we all know, during training, sub samples are fed to each independent classifier but in bagging technique, it can also happen that the same sample is passed two to three times to any of the other individual classifiers. So , in that scenario the samples which are new to a particular classifier i.e. the samples which are not already seen are called out of bag samples. It serves the same purpose of a test set as OOB instances are something not seen earlier. We can get the OOB score using ‘classifier.oob_score_’ function after building the ensemble using Bagging Classifier. # Multiple logistic regression classifiers using bagging Classifier.# Number of logistic regression classifiers we are using here are 400.logbagClf = BaggingClassifier(LogisticRegression(random_state=0, solver='lbfgs'), n_estimators = 400, oob_score = True, random_state = 90)logbagClf.fit(X_train, y_train) Evaluation metric of the bagging classifier(multiple Logistic Regression Classifiers): AUC score is 84.44 %. For this technique, we can use Sklearn’s VotingClassifier. For my testing purpose, I am using an ensemble of RandomForestClassifier, Support vector machine and Logistic regression. from sklearn.ensemble import RandomForestClassifier, VotingClassifierfrom sklearn.svm import SVCfrom sklearn.linear_model import LogisticRegressionfrom sklearn.naive_bayes import GaussianNBrfClf = RandomForestClassifier(n_estimators=500, random_state=0) # 500 trees. svmClf = SVC(probability=True, random_state=0) # probability calculationlogClf = LogisticRegression(random_state=0)#nbclf = GaussianNB(random_state=0)# constructing the ensemble classifier by mentioning the individual classifiers.clf2 = VotingClassifier(estimators = [('rf',rfClf), ('svm',svmClf), ('log', logClf)], voting='soft') # train the ensemble classifierclf2.fit(X_train, y_train) Evaluation metrics of the Voting Classifier(Ensemble of multiple models): AUC score is 84.92 % The main idea behind boosting is to convert weak learners to strong learners in sequential iterations. Let us again take the example of interviews to understand the concept boosting. Suppose a candidate has attended five interviews in five different companies. And based on his performance in these five interviews, he wants to rate himself on the skill. Interview 1 — company 1 — He could answer only a few of the questions but he got an idea of the type of questions he could be asked again. He comes back home and studies. His learning rate increased. Interview 2 — company 2 — Here, he did better than the first company as he learns all the concepts he missed on the first interview but still not selected. He comes back home and studies more thereby correcting all the mistakes he made in the previous two interviews. Interview 3 and interview 4 also, he faced the same issue and by the time, he attends the 5th interview, he became an expert and was almost able to answer all the questions. Ultimately all we see here is the candidate being exposed to different sample of questions and him learning and improving himself gradually till he becomes an expert. The outcome is he could rate himself the best after learning from his mistakes and correcting himself. There is a learning rate involved in each step. Same is the concept of boosting. I will implement boosting algorithm XGBoost on my dataset. import xgboost as xgbxgb_clf = xgb.XGBClassifier(max_depth=3,n_estimators=300,learning_rate=0.05) xgb_clf.fit(X_train,y_train) Evaluation metrics of XGBoost applied on example data: AUC score is 86.46 %. Let’s compare the accuracies , precision and AUC score of the single and the ensemble models. Accuracy Score: Boosting algorithm ‘XGBoost’ is leading on the accuracy score. Accuracy Score: Boosting algorithm ‘XGBoost’ is leading on the accuracy score. We can also notice that ensemble classifiers ‘random forest’ and ‘multiple logistic regression classifiers’ have better accuracies compared to single classifiers ‘Decision Tree’ and ‘Logistic Regression’ respectively. 2. Precision Score: Boosting algorithm ‘XGboost’ is leading on the precision score. We can notice that ensemble classifiers ‘random forest’ and ‘multiple logistic regression classifiers’ have better precision compared to single classifiers ‘Decision Tree’ and ‘Logistic Regression’ respectively. 3. AUC Score: Bagging algorithm ‘Random forest’ is leading on the AUC score even though there is very minute difference with the Auc score of XGboost. We can notice that ensemble classifiers ‘random forest’ and ‘multiple logistic regression classifiers’ have better AUC scores compared to single classifiers ‘Decision Tree’ and ‘Logistic Regression’ respectively. Hence, we can conclude that boosting method performed best on our dataset and we can finally deploy XGBoost model as it will predict most precisely the success of an ad campaign which is the main agenda of our problem statement. However, It depends on the type of data we are dealing with. Also, we can infer that bagging and boosting methods always perform better with great accuracies as compared to the single models. Kindly add any additional thoughts, comments as it will help me understand things better. Thanks for reading !!
[ { "code": null, "e": 348, "s": 171, "text": "In my previous article, we discussed about the different types of regression in machine learning. So, today I am going to focus on the various ensemble methods in data science." }, { "code": null, "e": 717, "s": 348, "text": "One thing I have experienced in the course of my career is that while learning any skill , things become easier when we try to relate concepts to events we face in our everyday lives. It’s effortless remembering things when we have a real life analogy. Hence, keeping that in mind, we will look at the various ensemble techniques by comparing it to everyday scenarios." }, { "code": null, "e": 733, "s": 717, "text": "1. Introduction" }, { "code": null, "e": 762, "s": 733, "text": "2. Types of ensemble methods" }, { "code": null, "e": 815, "s": 762, "text": "3. Similarities between bagging and boosting methods" }, { "code": null, "e": 855, "s": 815, "text": "4. Differences between both the methods" }, { "code": null, "e": 874, "s": 855, "text": "5. Types of voting" }, { "code": null, "e": 916, "s": 874, "text": "6. Detailed understanding of the concepts" }, { "code": null, "e": 924, "s": 916, "text": "Bagging" }, { "code": null, "e": 933, "s": 924, "text": "Boosting" }, { "code": null, "e": 947, "s": 933, "text": "7. Conclusion" }, { "code": null, "e": 968, "s": 947, "text": "What is an ensemble?" }, { "code": null, "e": 1079, "s": 968, "text": "In simple English, ensemble refers to a group of items. For e.g: a group of ministers, a group of dancers etc." }, { "code": null, "e": 1124, "s": 1079, "text": "What is ensemble method in machine learning?" }, { "code": null, "e": 1278, "s": 1124, "text": "An ensemble method is a technique which uses multiple independent similar or different models/weak learners to derive an output or make some predictions." }, { "code": null, "e": 1287, "s": 1278, "text": "For e.g." }, { "code": null, "e": 1346, "s": 1287, "text": "A random forest is an ensemble of multiple decision trees." }, { "code": null, "e": 1465, "s": 1346, "text": "An ensemble can also be built with a combination of different models like random forest, SVM, Logistic regression etc." }, { "code": null, "e": 1516, "s": 1465, "text": "So now, let’s compare it with a real life example." }, { "code": null, "e": 1621, "s": 1516, "text": "Suppose a bill is passed in the parliament and a meeting is held for the same with a group of ministers." }, { "code": null, "e": 2025, "s": 1621, "text": "Instead of the President or the prime minister taking the decision alone by themselves might not be a very good idea as this accounts for dictatorship and the results might not be so much in favor of the public. So, this analogy can be referred to a single model like Decision Tree, Logistic Regression etc in machine learning and they will always slightly perform less better than the ensemble methods." }, { "code": null, "e": 2278, "s": 2025, "text": "However, if a meeting is held between different ministers , let’s say four of them, each of them will provide an opinion with pros and cons. And finally, the best opinion will be picked based on majority voting. This is exactly what ensemble method is." }, { "code": null, "e": 2350, "s": 2278, "text": "Minister 1: based on his pros and cons, says the bill should be passed." }, { "code": null, "e": 2485, "s": 2350, "text": "Minister 2: based on his pros and cons, says the bill is not useful and might trigger a lot of challenges. Hence should not be passed." }, { "code": null, "e": 2522, "s": 2485, "text": "Minister 3: Says bill can be passed." }, { "code": null, "e": 2564, "s": 2522, "text": "Minister 4: Also says bill can be passed." }, { "code": null, "e": 2712, "s": 2564, "text": "Similarly, we can see below that different models are used and based on the output of each, the final decision will be made on the majority voting." }, { "code": null, "e": 2748, "s": 2712, "text": "Why do we need ensemble techniques?" }, { "code": null, "e": 2943, "s": 2748, "text": "As we all know, the errors and predictions in any machine learning models are adversely influenced by bias, variance and noise. In order to combat these disadvantages, ensemble methods are used." }, { "code": null, "e": 3054, "s": 2943, "text": "There are many ensemble techniques available but we will discuss about the below two most widely used methods:" }, { "code": null, "e": 3065, "s": 3054, "text": "1. Bagging" }, { "code": null, "e": 3077, "s": 3065, "text": "2. Boosting" }, { "code": null, "e": 3169, "s": 3077, "text": "Let us first understand the similarities and differences between both of the terminologies." }, { "code": null, "e": 3282, "s": 3169, "text": "· Both the methods can be used for classification (discrete output) and regression (continuous output) problems." }, { "code": null, "e": 3468, "s": 3282, "text": "· ­Both methods are better in performance compared to single models as they aggregate the output of all the weak learners via voting thereby leading to more accuracy in the predictions." }, { "code": null, "e": 3553, "s": 3468, "text": "There are two types of voting used to aggregate the output of all the weak learners." }, { "code": null, "e": 3751, "s": 3553, "text": "Hard voting — If we receive the output of each weak learner in classes (for e.g: 0/1), and finally we select the output class which was returned in majority, then this method is called hard voting." }, { "code": null, "e": 3934, "s": 3751, "text": "For instance: In our example of the group of ministers, since 3 ministers were in favor of the bill, the final decision was made to pass the bill. This is hard voting. Majority wins." }, { "code": null, "e": 4349, "s": 3934, "text": "Soft voting — There are many algorithms which also provide us with prediction probabilities and if we receive the output in probabilities, we take the average of the probabilities of each of the classes and whichever class is having the highest average will be the final prediction. This way of prediction is called Soft voting and is better than hard voting as we receive more information in terms of probability." }, { "code": null, "e": 4476, "s": 4349, "text": "Another important thing to remember is, this method of voting is used as a default technique for ensembles like random forest." }, { "code": null, "e": 4570, "s": 4476, "text": "Let’s understand these two concepts using below diagrams where 1 is class 1 and 0 is class 0." }, { "code": null, "e": 4828, "s": 4570, "text": "Also known as Bootstrap aggregating because the training set is divided into multiple sub samples and fed to each weak learner(for e.g.: each decision tree). And each sub sample contains a few set of features along with a few observations selected randomly." }, { "code": null, "e": 4962, "s": 4828, "text": "Since the main idea of this article is to understand the concepts in Layman terms, let us take an easy example to comprehend bagging." }, { "code": null, "e": 5098, "s": 4962, "text": "We all attend interviews right and the interview process is the most simple scenario I could come across which is analogous to Bagging." }, { "code": null, "e": 5534, "s": 5098, "text": "Suppose you went to attend an interview and as soon as you enter the room, you see five stern looking people sitting there to lash out all their questions at you . What do you do? Feel nervous and storm out of the room !! No right? You went there because you need the job and you know you are bold enough , intelligent enough to face whatever comes your way and you greet them anyway and sit down in front of them. So, let’s face this." }, { "code": null, "e": 5732, "s": 5534, "text": "Now consider each of the five interviewers are going to interview the candidate on five different aspects say aptitude , technical -basic ,technical- advanced, communication and management skills ." }, { "code": null, "e": 5899, "s": 5732, "text": "Also, the company might already have prepared a set of questions based on the different aspects to test the candidate’s skills. And let’s name this as ‘question set’." }, { "code": null, "e": 6006, "s": 5899, "text": "So, the interview starts now. And our target variable here would be if the candidate gets selected or not." }, { "code": null, "e": 6211, "s": 6006, "text": "Interviewer 1 — The interviewer 1 starts testing your aptitude skills taking a sample of aptitude based questions from the ‘question set’ and sets some probabilities whether you should be selected or not." }, { "code": null, "e": 6442, "s": 6211, "text": "Interviewer 2 — The interviewer 2 also starts testing your basic technical skills, again taking a sample of preliminary technical questions from the’ question set’ and sets some probabilities whether you should be selected or not." }, { "code": null, "e": 6694, "s": 6442, "text": "Interviewer 3 — Similarly, the interviewer 3 starts testing your advanced technical skills taking another sample of slightly difficult technical questions from the’ question set’ and again sets some probabilities whether you should be selected or not." }, { "code": null, "e": 7035, "s": 6694, "text": "Now, It can also be possible that he asks you some questions picked randomly from the ‘question set’ but is similar and was already asked in basic technical test or any of the previous tests . Such a scenario is called bootstrap in bagging method as the same sample may be picked up again due to the use of random sampling with replacement." }, { "code": null, "e": 7320, "s": 7035, "text": "Interviewer 4 & Interviewer 5: Interviewer 4 and interviewer 5 repeats the same process as above, testing the candidate’s communication and management skills taking a sample of related questions from the ‘question set’ and accordingly sets some probabilities whether to select or not." }, { "code": null, "e": 7707, "s": 7320, "text": "Result: Finally the candidate is done with the interview and he comes out of the room leaving the interviewers to analyse their respective scores about his skills based on the sub samples of questions from the ‘question set’ that he was scored upon . Ultimately they aggregate all of their individual opinions and come out with the final decision whether to select the candidate or not." }, { "code": null, "e": 7752, "s": 7707, "text": "This is exactly similar to ensemble methods." }, { "code": null, "e": 7867, "s": 7752, "text": "Let’s try out a few ensemble methods using python and compare their accuracy corresponding to a few single models." }, { "code": null, "e": 7937, "s": 7867, "text": "Note: The jupyter notebook with complete code is available in github." }, { "code": null, "e": 8049, "s": 7937, "text": "I am using Advertisement Success dataset from Kaggle for this purpose and want to predict the success of an Ad." }, { "code": null, "e": 8066, "s": 8049, "text": "a. Decision tree" }, { "code": null, "e": 8527, "s": 8066, "text": "# Decision tree classifier with grid seacrh CV and model evaluation using accuracy score, precision score and AUC/ROC curve.from sklearn.tree import DecisionTreeClassifierfrom sklearn.model_selection import GridSearchCVparameters = {'max_features': [0.5,0.6,0.7,0.8,0.9,1.0], 'max_depth': [2,3,4,5,6,7],'min_samples_leaf':[1,10,100],'random_state':[14]} clf = GridSearchCV(DecisionTreeClassifier(), parameters, cv=5, scoring='roc_auc')clf.fit(X_train, y_train)" }, { "code": null, "e": 8589, "s": 8527, "text": "Evaluation metrics of Decision Tree applied on example data :" }, { "code": null, "e": 8610, "s": 8589, "text": "AUC score is 85.84%." }, { "code": null, "e": 9115, "s": 8610, "text": "Decision trees are always prone to overfitting if we don’t choose the right parameters like minimum sample of leaf, minimum sample of nodes, maximum depth of the tree as higher the depth , more minutely will the model capture the data points of the training set leading to excellent predictions in the training dataset itself but will fail on new data. Hence, ensemble methods are one of the techniques which helps to reduce the variance thereby solving overfitting encountered by a single decision tree." }, { "code": null, "e": 9156, "s": 9115, "text": "b. Single Logistic Regression classifier" }, { "code": null, "e": 9345, "s": 9156, "text": "#Single Logistic Regressionfrom sklearn.linear_model import LogisticRegressionlog = LogisticRegression(random_state=0, solver='lbfgs') log.fit(X_train, y_train)y_pred = log.predict(X_test)" }, { "code": null, "e": 9429, "s": 9345, "text": "Evaluation Metric of Single Logistic regression classifier applied on example data:" }, { "code": null, "e": 9451, "s": 9429, "text": "AUC score is 83.84 %." }, { "code": null, "e": 9617, "s": 9451, "text": "Few examples are Random Forest , Extra tree classifiers/regressors, ensemble of linear regressors, ensemble of logistic regression classifiers, ensemble of SVMs etc." }, { "code": null, "e": 9675, "s": 9617, "text": "a. Random forest — an ensemble of multiple decision trees" }, { "code": null, "e": 9984, "s": 9675, "text": "from sklearn.ensemble import RandomForestClassifierparameters = {'n_estimators':[700],'n_jobs':[-1], 'max_features': [0.5,0.7,0.9], 'max_depth': [3,5,7],'min_samples_leaf':[1,10],'random_state':[14]} clf1 = GridSearchCV(RandomForestClassifier(), parameters, cv=5, scoring='roc_auc')clf1.fit(X_train, y_train)" }, { "code": null, "e": 10045, "s": 9984, "text": "Evaluation metrics of random forest applied on example data:" }, { "code": null, "e": 10067, "s": 10045, "text": "AUC score is 86.53 %." }, { "code": null, "e": 10115, "s": 10067, "text": "b. Ensemble of logistic regression classifiers." }, { "code": null, "e": 10971, "s": 10115, "text": "When we use an ensemble of same classifiers, Sklearn’s BaggingClassifier is used to get the OOB (Out of bag) score which is a very important score in bagging to examine the performance of the classifiers as it gives us an idea of the accuracy to be achieved on the test set. As we all know, during training, sub samples are fed to each independent classifier but in bagging technique, it can also happen that the same sample is passed two to three times to any of the other individual classifiers. So , in that scenario the samples which are new to a particular classifier i.e. the samples which are not already seen are called out of bag samples. It serves the same purpose of a test set as OOB instances are something not seen earlier. We can get the OOB score using ‘classifier.oob_score_’ function after building the ensemble using Bagging Classifier." }, { "code": null, "e": 11279, "s": 10971, "text": "# Multiple logistic regression classifiers using bagging Classifier.# Number of logistic regression classifiers we are using here are 400.logbagClf = BaggingClassifier(LogisticRegression(random_state=0, solver='lbfgs'), n_estimators = 400, oob_score = True, random_state = 90)logbagClf.fit(X_train, y_train)" }, { "code": null, "e": 11366, "s": 11279, "text": "Evaluation metric of the bagging classifier(multiple Logistic Regression Classifiers):" }, { "code": null, "e": 11388, "s": 11366, "text": "AUC score is 84.44 %." }, { "code": null, "e": 11447, "s": 11388, "text": "For this technique, we can use Sklearn’s VotingClassifier." }, { "code": null, "e": 11569, "s": 11447, "text": "For my testing purpose, I am using an ensemble of RandomForestClassifier, Support vector machine and Logistic regression." }, { "code": null, "e": 12225, "s": 11569, "text": "from sklearn.ensemble import RandomForestClassifier, VotingClassifierfrom sklearn.svm import SVCfrom sklearn.linear_model import LogisticRegressionfrom sklearn.naive_bayes import GaussianNBrfClf = RandomForestClassifier(n_estimators=500, random_state=0) # 500 trees. svmClf = SVC(probability=True, random_state=0) # probability calculationlogClf = LogisticRegression(random_state=0)#nbclf = GaussianNB(random_state=0)# constructing the ensemble classifier by mentioning the individual classifiers.clf2 = VotingClassifier(estimators = [('rf',rfClf), ('svm',svmClf), ('log', logClf)], voting='soft') # train the ensemble classifierclf2.fit(X_train, y_train)" }, { "code": null, "e": 12299, "s": 12225, "text": "Evaluation metrics of the Voting Classifier(Ensemble of multiple models):" }, { "code": null, "e": 12320, "s": 12299, "text": "AUC score is 84.92 %" }, { "code": null, "e": 12423, "s": 12320, "text": "The main idea behind boosting is to convert weak learners to strong learners in sequential iterations." }, { "code": null, "e": 12503, "s": 12423, "text": "Let us again take the example of interviews to understand the concept boosting." }, { "code": null, "e": 12675, "s": 12503, "text": "Suppose a candidate has attended five interviews in five different companies. And based on his performance in these five interviews, he wants to rate himself on the skill." }, { "code": null, "e": 12875, "s": 12675, "text": "Interview 1 — company 1 — He could answer only a few of the questions but he got an idea of the type of questions he could be asked again. He comes back home and studies. His learning rate increased." }, { "code": null, "e": 13143, "s": 12875, "text": "Interview 2 — company 2 — Here, he did better than the first company as he learns all the concepts he missed on the first interview but still not selected. He comes back home and studies more thereby correcting all the mistakes he made in the previous two interviews." }, { "code": null, "e": 13317, "s": 13143, "text": "Interview 3 and interview 4 also, he faced the same issue and by the time, he attends the 5th interview, he became an expert and was almost able to answer all the questions." }, { "code": null, "e": 13668, "s": 13317, "text": "Ultimately all we see here is the candidate being exposed to different sample of questions and him learning and improving himself gradually till he becomes an expert. The outcome is he could rate himself the best after learning from his mistakes and correcting himself. There is a learning rate involved in each step. Same is the concept of boosting." }, { "code": null, "e": 13727, "s": 13668, "text": "I will implement boosting algorithm XGBoost on my dataset." }, { "code": null, "e": 13857, "s": 13727, "text": "import xgboost as xgbxgb_clf = xgb.XGBClassifier(max_depth=3,n_estimators=300,learning_rate=0.05) xgb_clf.fit(X_train,y_train)" }, { "code": null, "e": 13912, "s": 13857, "text": "Evaluation metrics of XGBoost applied on example data:" }, { "code": null, "e": 13934, "s": 13912, "text": "AUC score is 86.46 %." }, { "code": null, "e": 14028, "s": 13934, "text": "Let’s compare the accuracies , precision and AUC score of the single and the ensemble models." }, { "code": null, "e": 14107, "s": 14028, "text": "Accuracy Score: Boosting algorithm ‘XGBoost’ is leading on the accuracy score." }, { "code": null, "e": 14186, "s": 14107, "text": "Accuracy Score: Boosting algorithm ‘XGBoost’ is leading on the accuracy score." }, { "code": null, "e": 14404, "s": 14186, "text": "We can also notice that ensemble classifiers ‘random forest’ and ‘multiple logistic regression classifiers’ have better accuracies compared to single classifiers ‘Decision Tree’ and ‘Logistic Regression’ respectively." }, { "code": null, "e": 14488, "s": 14404, "text": "2. Precision Score: Boosting algorithm ‘XGboost’ is leading on the precision score." }, { "code": null, "e": 14700, "s": 14488, "text": "We can notice that ensemble classifiers ‘random forest’ and ‘multiple logistic regression classifiers’ have better precision compared to single classifiers ‘Decision Tree’ and ‘Logistic Regression’ respectively." }, { "code": null, "e": 14851, "s": 14700, "text": "3. AUC Score: Bagging algorithm ‘Random forest’ is leading on the AUC score even though there is very minute difference with the Auc score of XGboost." }, { "code": null, "e": 15064, "s": 14851, "text": "We can notice that ensemble classifiers ‘random forest’ and ‘multiple logistic regression classifiers’ have better AUC scores compared to single classifiers ‘Decision Tree’ and ‘Logistic Regression’ respectively." }, { "code": null, "e": 15293, "s": 15064, "text": "Hence, we can conclude that boosting method performed best on our dataset and we can finally deploy XGBoost model as it will predict most precisely the success of an ad campaign which is the main agenda of our problem statement." }, { "code": null, "e": 15354, "s": 15293, "text": "However, It depends on the type of data we are dealing with." }, { "code": null, "e": 15485, "s": 15354, "text": "Also, we can infer that bagging and boosting methods always perform better with great accuracies as compared to the single models." }, { "code": null, "e": 15575, "s": 15485, "text": "Kindly add any additional thoughts, comments as it will help me understand things better." } ]
Python | Find Mean of a List of Numpy Array - GeeksforGeeks
14 Mar, 2019 Given a list of Numpy array, the task is to find mean of every numpy array. Let’s see a few methods we can do the task. Method #1: Using np.mean() # Python code to find mean of every numpy array in list # Importing moduleimport numpy as np # List InitializationInput = [np.array([1, 2, 3]), np.array([4, 5, 6]), np.array([7, 8, 9])] # Output list initializationOutput = [] # using np.mean()for i in range(len(Input)): Output.append(np.mean(Input[i])) # Printing outputprint(Output) [2.0, 5.0, 8.0] Method #2: Using np.average() # Python code to find mean of # every numpy array in list # Importing moduleimport numpy as np # List InitializationInput = [np.array([11, 12, 13]), np.array([14, 15, 16]), np.array([17, 18, 19])] # Output list initializationOutput = [] # using np.mean()for i in range(len(Input)): Output.append(np.average(Input[i])) # Printing outputprint(Output) [12.0, 15.0, 18.0] Python numpy-program Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Read a file line by line in Python Enumerate() in Python Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Create a Pandas DataFrame from Lists Python String | replace() Reading and Writing to text files in Python
[ { "code": null, "e": 24126, "s": 24098, "text": "\n14 Mar, 2019" }, { "code": null, "e": 24246, "s": 24126, "text": "Given a list of Numpy array, the task is to find mean of every numpy array. Let’s see a few methods we can do the task." }, { "code": null, "e": 24273, "s": 24246, "text": "Method #1: Using np.mean()" }, { "code": "# Python code to find mean of every numpy array in list # Importing moduleimport numpy as np # List InitializationInput = [np.array([1, 2, 3]), np.array([4, 5, 6]), np.array([7, 8, 9])] # Output list initializationOutput = [] # using np.mean()for i in range(len(Input)): Output.append(np.mean(Input[i])) # Printing outputprint(Output)", "e": 24631, "s": 24273, "text": null }, { "code": null, "e": 24648, "s": 24631, "text": "[2.0, 5.0, 8.0]\n" }, { "code": null, "e": 24679, "s": 24648, "text": " Method #2: Using np.average()" }, { "code": "# Python code to find mean of # every numpy array in list # Importing moduleimport numpy as np # List InitializationInput = [np.array([11, 12, 13]), np.array([14, 15, 16]), np.array([17, 18, 19])] # Output list initializationOutput = [] # using np.mean()for i in range(len(Input)): Output.append(np.average(Input[i])) # Printing outputprint(Output)", "e": 25051, "s": 24679, "text": null }, { "code": null, "e": 25071, "s": 25051, "text": "[12.0, 15.0, 18.0]\n" }, { "code": null, "e": 25092, "s": 25071, "text": "Python numpy-program" }, { "code": null, "e": 25105, "s": 25092, "text": "Python-numpy" }, { "code": null, "e": 25112, "s": 25105, "text": "Python" }, { "code": null, "e": 25210, "s": 25112, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25219, "s": 25210, "text": "Comments" }, { "code": null, "e": 25232, "s": 25219, "text": "Old Comments" }, { "code": null, "e": 25250, "s": 25232, "text": "Python Dictionary" }, { "code": null, "e": 25282, "s": 25250, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25317, "s": 25282, "text": "Read a file line by line in Python" }, { "code": null, "e": 25339, "s": 25317, "text": "Enumerate() in Python" }, { "code": null, "e": 25369, "s": 25339, "text": "Iterate over a list in Python" }, { "code": null, "e": 25411, "s": 25369, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 25454, "s": 25411, "text": "Python program to convert a list to string" }, { "code": null, "e": 25491, "s": 25454, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 25517, "s": 25491, "text": "Python String | replace()" } ]
Modelling tabular data with Google’s TabNet | by Mikael Huss | Towards Data Science
Can a neural network beat classical methods? Released in 2019, Google Research’s TabNet is claimed in a preprint manuscript to outperform existing methods on tabular data. How does it work and how can one try it? Tabular data probably make up the majority of business data today. Think of things like retail transactions, click stream data, temperature and pressure sensors in factories, KYC (Know Your Customer) information used by banks, or gene expression data for model organisms used by pharmaceutical companies. The variety is simply endless. In another post, I introduced CatBoost, one of my favorite methods for building prediction models on tabular data, and its neural network counterpart, NODE. But around the same time as the NODE manuscript came out, Google Research released a manuscript taking a totally different approach to tabular data modelling with neural networks. Whereas NODE mimics decision tree ensembles, Google’s proposed TabNet tries to build a new kind of architecture suitable for tabular data. The paper describing the method is called TabNet: Attentive Interpretable Tabular Learning, which nicely summarizes what the authors are trying to do. The “Net” part tells us that it is a type of neural network, the “Attentive” part implies it is using an attention mechanism, it aims to be interpretable, and it is used for machine learning on tabular data. TabNet uses a kind of soft feature selection to focus on just the features that are important for the example at hand. This is accomplished through a sequential multi-step decision mechanism. That is, the input information is processed top-down in several steps. As the manuscript puts it, “The idea of top-down attention in sequential form is inspired from its applications in processing visual and language data such as for visual question answering (Hudson & Manning, 2018) or in reinforcement learning (Mott et al., 2019) while searching for a small subset of relevant information in high dimensional input.” The building blocks for performing this sequential attention are called transformer blocks even though they are a bit different from the transformers used in popular NLP models such as BERT. Those transformers use self-attention and seek to model the dependencies between the different words in a sentence. The type of transformer used here is trying to eliminate, step by step, those features that are not relevant for the example at hand using a “soft” feature selection, which is accomplished by using the sparsemax function. The first figure from the paper, reproduced below, sketches how information is aggregated to form a prediction. One nice property of TabNet is that it does not require feature preprocessing (in contrast to e.g. NODE). Another one is that it has interpretability built in “for free” in that the most relevant features are selected for each example. This means that you don’t have to apply an external explanation module such as shap or LIME. It is not so easy to wrap one’s head around what is happening inside this architecture when reading the paper, but luckily there is published code which clarifies things a bit and shows that it is not as complicated as you might think. Addition on 2020–03–09: There are now better interfaces to TabNet that the one described below: one for PyTorch which has a scikit-learn-like interface and one for FastAI. As already mentioned, the code is available, and the authors show how to use it together with the forest covertype dataset. To facilitate this, they have provided three dataset-specific files: one file that downloads and prepares the data (download_prepare_covertype.py), another one that defines the appropriate Tensorflow Feature Columns and a CSV reader input function (data_helper_covertype.py), and the file that contains the training loop (experiment_covertype.py). The repo README states: To modify the experiment to other tabular datasets: - Substitute the train.csv, val.csv, and test.csv files under “data/” directory, - Modify the data_helper function with the numerical and categorical features of the new dataset, - Reoptimize the TabNet hyperparameters for the new dataset. After having gone through this process a couple of times with other datasets, I decided to write my own wrapper code to streamline the process. This code, which I must stress is a totally unofficial fork, is on GitHub. In terms of the README points above: Rather than making new train.csv, val.csv and test.csv files for each dataset, I preferred to read the entire dataset and do the splitting in-memory (as long as it is feasible, of course), so I wrote a new input function for Pandas in my code.It can take a bit of work to modify the data_helper.py file, at least initially when you aren’t quite sure what it does and how the feature columns should be defined (this was certainly the case with me). There are also many parameters which need to be changed but which are in the main training loop file rather than the data helper file. In view of this, I also tried to generalize and streamline this process in my code.I added some quick-and-dirty code for doing hyperparameter optimization, but so far only for classification.It is also worth mentioning that the example code from the authors only shows how to do classification, not regression, so that extra code also has to be written by the user. I have added regression functionality with a simple mean squared error loss. Rather than making new train.csv, val.csv and test.csv files for each dataset, I preferred to read the entire dataset and do the splitting in-memory (as long as it is feasible, of course), so I wrote a new input function for Pandas in my code. It can take a bit of work to modify the data_helper.py file, at least initially when you aren’t quite sure what it does and how the feature columns should be defined (this was certainly the case with me). There are also many parameters which need to be changed but which are in the main training loop file rather than the data helper file. In view of this, I also tried to generalize and streamline this process in my code. I added some quick-and-dirty code for doing hyperparameter optimization, but so far only for classification. It is also worth mentioning that the example code from the authors only shows how to do classification, not regression, so that extra code also has to be written by the user. I have added regression functionality with a simple mean squared error loss. Execute a command like: python train_tabnet.py \ --csv-path data/adult.csv \ --target-name "<=50K" \ --categorical-features workclass,education,marital.status,\occupation,relationship,race,sex,native.country\ --feature_dim 16 \ --output_dim 16 \ --batch-size 4096 \ --virtual-batch-size 128 \ --batch-momentum 0.98 \ --gamma 1.5 \ --n_steps 5 \ --decay-every 2500 \ --lambda-sparsity 0.0001 \ --max-steps 7700 The mandatory parameters are — -csv-path(pointing to the location of the CSV file),--target-name(the name of the column with the prediction target) and--categorical-featues (a comma-separated list of the features that should be treated as categorical). The rest of the input parameters are hyperparameters that need to be optimized for each specific problem. The values shown above, though, are taken directly from the TabNet manuscript, so they have already been optimized for the Adult Census dataset by the authors. By default, the training process will write information to the tflog subfolder of the location where you execute the script. You can point tensorboard at this folder to look at training and validation stats: tensorboard --logdir tflog and point your web browser to localhost:6006. ... you could try this Colaboratory notebook. Note that if you want to look at the Tensorboard logs, your best bet is probably to create a Google Storage bucket and have the script write the logs there. This is accomplished by using the tb-log-locationparameter. E.g. if your bucket’s name were camembert-skyscrape, you could add--tb-log-location gs://camembert-skyscraperto the invocation of the script. (Note, though, that you have to set the permissions for the storage bucket correctly. This can be a bit of a hassle.) Then you can point tensorboard, from your own local computer, to that bucket: tensorboard --logdir gs://camembert-skyscraper There is also a quick-and-dirty script for doing hyperparameter optimization in the repo (opt_tabnet.py). Again, an example is shown in the Colaboratory notebook. The script only works for classification so far, and it is worth noting that some training parameters are still hard-coded although they shouldn’t really be (for example, the patience parameter for early stopping [how many steps do you continue while the best validation accuracy does not improve].) The parameters that are varied in the optimization script are N_steps, feature_dim, batch-momentum, gamma, lambda-sparsity. (output_dim is set to be equal to feature_dim, as suggested in the optimization tips just below.) The paper has the following tips on hyperparameter optimization: Most datasets yield the best results for N_steps ∈ [3, 10]. Typically, larger datasets and more complex tasks require a larger N_steps. A very high value of N_steps may suffer from overfitting and yield poor generalization. Adjustment of the values of Nd [feature_dim] and Na [output_dim] is the most efficient way of obtaining a trade-off between performance and complexity. Nd = Na is a reasonable choice for most datasets. A very high value of Nd and Na may suffer from overfitting and yield poor generalization. An optimal choice of γ can have a major role on the overall performance. Typically a larger N_steps value favors for a larger γ. A large batch size is beneficial for performance — if the memory constraints permit, as large as 1–10 % of the total training dataset size is suggested. The virtual batch size is typically much smaller than the batch size. Initially large learning rate is important, which should be gradually decayed until convergence. I’ve tried TabNet via this command line interface for several datasets, including the Adult Census dataset that I used in the post about NODE and CatBoost for reasons that can be found in that post. Conveniently, this dataset had also been used in the TabNet manuscript, and the authors present the best parameter settings they found there. With repeated runs using those setting, I noticed that the best validation error (and test error) tends to be at around 86%, similar to CatBoost without hyperparameter tuning. The authors report a test set performance of 85.7% in the manuscript. When I did hyperparameter optimization with hyperopt, I unsurprisingly reached a similar performance around 86%, albeit with a different parameter setting. For other datasets such as the Poker Hand dataset, TabNet is claimed to beat other methods by a considerable margin. I have not yet devoted much time to that, but everyone is of course invited to try TabNet with hyperparameter optimization on various datasets for themselves! TabNet is an interesting architecture that seems promising for tabular data analysis. It operates directly on raw data and uses a sequential attention mechanism to perform explicit feature selection for each example. This property also gives it a sort of built-in interpretability. I have tried to make TabNet slightly easier to work with by writing some wrapper code around it. The next step is to compare it to other methods across a wide range of datasets. Please try it on your own datasets and/or send pull requests and help me improve the interface if you are interested!
[ { "code": null, "e": 217, "s": 172, "text": "Can a neural network beat classical methods?" }, { "code": null, "e": 385, "s": 217, "text": "Released in 2019, Google Research’s TabNet is claimed in a preprint manuscript to outperform existing methods on tabular data. How does it work and how can one try it?" }, { "code": null, "e": 721, "s": 385, "text": "Tabular data probably make up the majority of business data today. Think of things like retail transactions, click stream data, temperature and pressure sensors in factories, KYC (Know Your Customer) information used by banks, or gene expression data for model organisms used by pharmaceutical companies. The variety is simply endless." }, { "code": null, "e": 1197, "s": 721, "text": "In another post, I introduced CatBoost, one of my favorite methods for building prediction models on tabular data, and its neural network counterpart, NODE. But around the same time as the NODE manuscript came out, Google Research released a manuscript taking a totally different approach to tabular data modelling with neural networks. Whereas NODE mimics decision tree ensembles, Google’s proposed TabNet tries to build a new kind of architecture suitable for tabular data." }, { "code": null, "e": 1556, "s": 1197, "text": "The paper describing the method is called TabNet: Attentive Interpretable Tabular Learning, which nicely summarizes what the authors are trying to do. The “Net” part tells us that it is a type of neural network, the “Attentive” part implies it is using an attention mechanism, it aims to be interpretable, and it is used for machine learning on tabular data." }, { "code": null, "e": 2169, "s": 1556, "text": "TabNet uses a kind of soft feature selection to focus on just the features that are important for the example at hand. This is accomplished through a sequential multi-step decision mechanism. That is, the input information is processed top-down in several steps. As the manuscript puts it, “The idea of top-down attention in sequential form is inspired from its applications in processing visual and language data such as for visual question answering (Hudson & Manning, 2018) or in reinforcement learning (Mott et al., 2019) while searching for a small subset of relevant information in high dimensional input.”" }, { "code": null, "e": 2698, "s": 2169, "text": "The building blocks for performing this sequential attention are called transformer blocks even though they are a bit different from the transformers used in popular NLP models such as BERT. Those transformers use self-attention and seek to model the dependencies between the different words in a sentence. The type of transformer used here is trying to eliminate, step by step, those features that are not relevant for the example at hand using a “soft” feature selection, which is accomplished by using the sparsemax function." }, { "code": null, "e": 2810, "s": 2698, "text": "The first figure from the paper, reproduced below, sketches how information is aggregated to form a prediction." }, { "code": null, "e": 3139, "s": 2810, "text": "One nice property of TabNet is that it does not require feature preprocessing (in contrast to e.g. NODE). Another one is that it has interpretability built in “for free” in that the most relevant features are selected for each example. This means that you don’t have to apply an external explanation module such as shap or LIME." }, { "code": null, "e": 3375, "s": 3139, "text": "It is not so easy to wrap one’s head around what is happening inside this architecture when reading the paper, but luckily there is published code which clarifies things a bit and shows that it is not as complicated as you might think." }, { "code": null, "e": 3399, "s": 3375, "text": "Addition on 2020–03–09:" }, { "code": null, "e": 3547, "s": 3399, "text": "There are now better interfaces to TabNet that the one described below: one for PyTorch which has a scikit-learn-like interface and one for FastAI." }, { "code": null, "e": 4019, "s": 3547, "text": "As already mentioned, the code is available, and the authors show how to use it together with the forest covertype dataset. To facilitate this, they have provided three dataset-specific files: one file that downloads and prepares the data (download_prepare_covertype.py), another one that defines the appropriate Tensorflow Feature Columns and a CSV reader input function (data_helper_covertype.py), and the file that contains the training loop (experiment_covertype.py)." }, { "code": null, "e": 4043, "s": 4019, "text": "The repo README states:" }, { "code": null, "e": 4095, "s": 4043, "text": "To modify the experiment to other tabular datasets:" }, { "code": null, "e": 4176, "s": 4095, "text": "- Substitute the train.csv, val.csv, and test.csv files under “data/” directory," }, { "code": null, "e": 4274, "s": 4176, "text": "- Modify the data_helper function with the numerical and categorical features of the new dataset," }, { "code": null, "e": 4335, "s": 4274, "text": "- Reoptimize the TabNet hyperparameters for the new dataset." }, { "code": null, "e": 4554, "s": 4335, "text": "After having gone through this process a couple of times with other datasets, I decided to write my own wrapper code to streamline the process. This code, which I must stress is a totally unofficial fork, is on GitHub." }, { "code": null, "e": 4591, "s": 4554, "text": "In terms of the README points above:" }, { "code": null, "e": 5617, "s": 4591, "text": "Rather than making new train.csv, val.csv and test.csv files for each dataset, I preferred to read the entire dataset and do the splitting in-memory (as long as it is feasible, of course), so I wrote a new input function for Pandas in my code.It can take a bit of work to modify the data_helper.py file, at least initially when you aren’t quite sure what it does and how the feature columns should be defined (this was certainly the case with me). There are also many parameters which need to be changed but which are in the main training loop file rather than the data helper file. In view of this, I also tried to generalize and streamline this process in my code.I added some quick-and-dirty code for doing hyperparameter optimization, but so far only for classification.It is also worth mentioning that the example code from the authors only shows how to do classification, not regression, so that extra code also has to be written by the user. I have added regression functionality with a simple mean squared error loss." }, { "code": null, "e": 5861, "s": 5617, "text": "Rather than making new train.csv, val.csv and test.csv files for each dataset, I preferred to read the entire dataset and do the splitting in-memory (as long as it is feasible, of course), so I wrote a new input function for Pandas in my code." }, { "code": null, "e": 6285, "s": 5861, "text": "It can take a bit of work to modify the data_helper.py file, at least initially when you aren’t quite sure what it does and how the feature columns should be defined (this was certainly the case with me). There are also many parameters which need to be changed but which are in the main training loop file rather than the data helper file. In view of this, I also tried to generalize and streamline this process in my code." }, { "code": null, "e": 6394, "s": 6285, "text": "I added some quick-and-dirty code for doing hyperparameter optimization, but so far only for classification." }, { "code": null, "e": 6646, "s": 6394, "text": "It is also worth mentioning that the example code from the authors only shows how to do classification, not regression, so that extra code also has to be written by the user. I have added regression functionality with a simple mean squared error loss." }, { "code": null, "e": 6670, "s": 6646, "text": "Execute a command like:" }, { "code": null, "e": 7069, "s": 6670, "text": "python train_tabnet.py \\ --csv-path data/adult.csv \\ --target-name \"<=50K\" \\ --categorical-features workclass,education,marital.status,\\occupation,relationship,race,sex,native.country\\ --feature_dim 16 \\ --output_dim 16 \\ --batch-size 4096 \\ --virtual-batch-size 128 \\ --batch-momentum 0.98 \\ --gamma 1.5 \\ --n_steps 5 \\ --decay-every 2500 \\ --lambda-sparsity 0.0001 \\ --max-steps 7700" }, { "code": null, "e": 7588, "s": 7069, "text": "The mandatory parameters are — -csv-path(pointing to the location of the CSV file),--target-name(the name of the column with the prediction target) and--categorical-featues (a comma-separated list of the features that should be treated as categorical). The rest of the input parameters are hyperparameters that need to be optimized for each specific problem. The values shown above, though, are taken directly from the TabNet manuscript, so they have already been optimized for the Adult Census dataset by the authors." }, { "code": null, "e": 7796, "s": 7588, "text": "By default, the training process will write information to the tflog subfolder of the location where you execute the script. You can point tensorboard at this folder to look at training and validation stats:" }, { "code": null, "e": 7823, "s": 7796, "text": "tensorboard --logdir tflog" }, { "code": null, "e": 7869, "s": 7823, "text": "and point your web browser to localhost:6006." }, { "code": null, "e": 8392, "s": 7869, "text": "... you could try this Colaboratory notebook. Note that if you want to look at the Tensorboard logs, your best bet is probably to create a Google Storage bucket and have the script write the logs there. This is accomplished by using the tb-log-locationparameter. E.g. if your bucket’s name were camembert-skyscrape, you could add--tb-log-location gs://camembert-skyscraperto the invocation of the script. (Note, though, that you have to set the permissions for the storage bucket correctly. This can be a bit of a hassle.)" }, { "code": null, "e": 8470, "s": 8392, "text": "Then you can point tensorboard, from your own local computer, to that bucket:" }, { "code": null, "e": 8517, "s": 8470, "text": "tensorboard --logdir gs://camembert-skyscraper" }, { "code": null, "e": 8980, "s": 8517, "text": "There is also a quick-and-dirty script for doing hyperparameter optimization in the repo (opt_tabnet.py). Again, an example is shown in the Colaboratory notebook. The script only works for classification so far, and it is worth noting that some training parameters are still hard-coded although they shouldn’t really be (for example, the patience parameter for early stopping [how many steps do you continue while the best validation accuracy does not improve].)" }, { "code": null, "e": 9202, "s": 8980, "text": "The parameters that are varied in the optimization script are N_steps, feature_dim, batch-momentum, gamma, lambda-sparsity. (output_dim is set to be equal to feature_dim, as suggested in the optimization tips just below.)" }, { "code": null, "e": 9267, "s": 9202, "text": "The paper has the following tips on hyperparameter optimization:" }, { "code": null, "e": 9491, "s": 9267, "text": "Most datasets yield the best results for N_steps ∈ [3, 10]. Typically, larger datasets and more complex tasks require a larger N_steps. A very high value of N_steps may suffer from overfitting and yield poor generalization." }, { "code": null, "e": 9783, "s": 9491, "text": "Adjustment of the values of Nd [feature_dim] and Na [output_dim] is the most efficient way of obtaining a trade-off between performance and complexity. Nd = Na is a reasonable choice for most datasets. A very high value of Nd and Na may suffer from overfitting and yield poor generalization." }, { "code": null, "e": 9912, "s": 9783, "text": "An optimal choice of γ can have a major role on the overall performance. Typically a larger N_steps value favors for a larger γ." }, { "code": null, "e": 10135, "s": 9912, "text": "A large batch size is beneficial for performance — if the memory constraints permit, as large as 1–10 % of the total training dataset size is suggested. The virtual batch size is typically much smaller than the batch size." }, { "code": null, "e": 10232, "s": 10135, "text": "Initially large learning rate is important, which should be gradually decayed until convergence." }, { "code": null, "e": 10975, "s": 10232, "text": "I’ve tried TabNet via this command line interface for several datasets, including the Adult Census dataset that I used in the post about NODE and CatBoost for reasons that can be found in that post. Conveniently, this dataset had also been used in the TabNet manuscript, and the authors present the best parameter settings they found there. With repeated runs using those setting, I noticed that the best validation error (and test error) tends to be at around 86%, similar to CatBoost without hyperparameter tuning. The authors report a test set performance of 85.7% in the manuscript. When I did hyperparameter optimization with hyperopt, I unsurprisingly reached a similar performance around 86%, albeit with a different parameter setting." }, { "code": null, "e": 11251, "s": 10975, "text": "For other datasets such as the Poker Hand dataset, TabNet is claimed to beat other methods by a considerable margin. I have not yet devoted much time to that, but everyone is of course invited to try TabNet with hyperparameter optimization on various datasets for themselves!" }, { "code": null, "e": 11533, "s": 11251, "text": "TabNet is an interesting architecture that seems promising for tabular data analysis. It operates directly on raw data and uses a sequential attention mechanism to perform explicit feature selection for each example. This property also gives it a sort of built-in interpretability." }, { "code": null, "e": 11711, "s": 11533, "text": "I have tried to make TabNet slightly easier to work with by writing some wrapper code around it. The next step is to compare it to other methods across a wide range of datasets." } ]
Maximum length subarray with LCM equal to product - GeeksforGeeks
03 Jun, 2021 Given an arr[], the task is to find the maximum length of the sub-array such that the LCM of the sub-array is equal to the product of numbers in the sub-array. If no valid sub-array exists, then print -1. Note: The length of the sub-array must be ≥ 2. Examples: Input: arr[] = { 6, 10, 21} Output: 2 The sub-array { 10, 21 } satisfies the condition. Input: arr[] = { 2, 2, 4} Output: -1 No sub-array satisfies the condition. Hence, the output is -1. Naive Approach: Run nested loops to check the condition for every possible sub-array of length ≥ 2. If the sub-array satisfies the condition, then update ans = max(ans, length(sub-array)). Print the ans in the end. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; #define ll long long // Function to calculate gcd(a, b)int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // Function to return max length of subarray// that satisfies the conditionint maxLengthSubArray(const int* arr, int n){ int maxLen = -1; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { ll lcm = 1LL * arr[i]; ll product = 1LL * arr[i]; // Update LCM and product of the // sub-array for (int k = i + 1; k <= j; k++) { lcm = (((arr[k] * lcm)) / (gcd(arr[k], lcm))); product = product * arr[k]; } // If the current sub-array satisfies // the condition if (lcm == product) { // Choose the maximum maxLen = max(maxLen, j - i + 1); } } } return maxLen;} // Driver codeint main(){ int arr[] = { 6, 10, 21 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxLengthSubArray(arr, n); return 0;} // Java implementation of the above approachimport java.util.*; class GFG{ // Function to calculate gcd(a, b)static int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // Function to return max length of subarray// that satisfies the conditionstatic int maxLengthSubArray(int arr[], int n){ int maxLen = -1; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { int lcm = 1 * arr[i]; int product = 1 * arr[i]; // Update LCM and product of the // sub-array for (int k = i + 1; k <= j; k++) { lcm = (((arr[k] * lcm)) / (gcd(arr[k], lcm))); product = product * arr[k]; } // If the current sub-array satisfies // the condition if (lcm == product) { // Choose the maximum maxLen = Math.max(maxLen, j - i + 1); } } } return maxLen;} // Driver codepublic static void main(String args[]){ int arr[] = { 6, 10, 21 }; int n = arr.length; System.out.println(maxLengthSubArray(arr, n));}} // This code is contributed by// Shashank_Sharma # Python3 implementation of the# above approach # Function to calculate gcd(a, b)def gcd(a, b): if (b == 0): return a return gcd(b, a % b) # Function to return max length of# subarray that satisfies the conditiondef maxLengthSubArray(arr, n): maxLen = -1 for i in range(n - 1): for j in range(n): lcm = arr[i] product = arr[i] # Update LCM and product of the # sub-array for k in range(i + 1, j + 1): lcm = (((arr[k] * lcm)) // (gcd(arr[k], lcm))) product = product * arr[k] # If the current sub-array satisfies # the condition if (lcm == product): # Choose the maximum maxLen = max(maxLen, j - i + 1) return maxLen # Driver codearr = [6, 10, 21 ]n = len(arr)print(maxLengthSubArray(arr, n)) # This code is contributed by# mohit kumar 29 // C# implementation of the above approachusing System; class GFG{ // Function to calculate gcd(a, b)static int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // Function to return max length of subarray// that satisfies the conditionstatic int maxLengthSubArray(int[] arr, int n){ int maxLen = -1; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { int lcm = 1 * arr[i]; int product = 1 * arr[i]; // Update LCM and product of the // sub-array for (int k = i + 1; k <= j; k++) { lcm = (((arr[k] * lcm)) / (gcd(arr[k], lcm))); product = product * arr[k]; } // If the current sub-array satisfies // the condition if (lcm == product) { // Choose the maximum maxLen = Math.Max(maxLen, j - i + 1); } } } return maxLen;} // Driver codepublic static void Main(){ int[] arr = { 6, 10, 21 }; int n = arr.Length; Console.Write(maxLengthSubArray(arr, n));}} // This code is contributed by ita_c <?php// PHP implementation of the above approach // Function to calculate gcd(a, b)function gcd($a, $b){ if ($b == 0) return $a; return gcd($b, $a % $b);} // Function to return max length of subarray// that satisfies the conditionfunction maxLengthSubArray(&$arr, $n){ $maxLen = -1; for ($i = 0; $i < $n - 1; $i++) { for ($j = $i + 1; $j < $n; $j++) { $lcm = $arr[$i]; $product = $arr[$i]; // Update LCM and product of the // sub-array for ($k = $i + 1; $k <= $j; $k++) { $lcm = ((($arr[$k] * $lcm)) / (gcd($arr[$k], $lcm))); $product = $product * $arr[$k]; } // If the current sub-array satisfies // the condition if ($lcm == $product) { // Choose the maximum $maxLen = max($maxLen, $j - $i + 1); } } } return $maxLen;} // Driver code$arr = array(6, 10, 21 );$n = sizeof($arr);echo(maxLengthSubArray($arr, $n)); // This code is contributed by Shivi_Aggarwal?> <script>// Javascript implementation of the above approach // Function to calculate gcd(a, b)function gcd(a,b){ if (b == 0) return a; return gcd(b, a % b);} // Function to return max length of subarray// that satisfies the conditionfunction maxLengthSubArray(arr,n){ let maxLen = -1; for (let i = 0; i < n - 1; i++) { for (let j = i + 1; j < n; j++) { let lcm = 1 * arr[i]; let product = 1 * arr[i]; // Update LCM and product of the // sub-array for (let k = i + 1; k <= j; k++) { lcm = (((arr[k] * lcm)) / (gcd(arr[k], lcm))); product = product * arr[k]; } // If the current sub-array satisfies // the condition if (lcm == product) { // Choose the maximum maxLen = Math.max(maxLen, j - i + 1); } } } return maxLen;} // Driver codelet arr=[6, 10, 21 ];let n = arr.length;document.write(maxLengthSubArray(arr, n)); // This code is contributed by unknown2108</script> 2 Efficient Approach: A sub-array will have its LCM equal to its product when no two elements in the sub-array have any common factor. For example: arr[] = { 6, 10, 21 }Prime factorization yields: arr[] = { 2 * 3, 2 * 5, 3 * 7 }[6, 10] has 2 as a common factor. [6, 10, 21] has 2 as a common factor between 6 and 10. Sub-array [10, 21] has no common factor between any 2 elements. Therefore, answer = 2. Firstly, prime factorization of numbers is done to deal with factors. To calculate the sub-array in which no 2 elements have a common factor, we use the two-pointer technique. Two pointers run, both from the right and they represent the current sub-array. We add elements in the sub-array from the right. Now there are two scenarios: An element is added in the current sub-array if it has no factor in common with the current elements in the sub-array. If a common factor is found, then starting from the left, elements are subsequently eliminated until no common factor is found with the newly added element.If there are no common factors between the newly added element and existing elements, then update ans = max(ans, length of sub-array) An element is added in the current sub-array if it has no factor in common with the current elements in the sub-array. If a common factor is found, then starting from the left, elements are subsequently eliminated until no common factor is found with the newly added element. If there are no common factors between the newly added element and existing elements, then update ans = max(ans, length of sub-array) Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the above approach#include <bits/stdc++.h> #define pb push_back#define N 100005#define MAX 1000002#define mem(a, b) memset(a, b, sizeof(a)) using namespace std; int prime[MAX]; // Stores array of primes for every elementvector<int> v[N]; // Stores the position of a prime in the subarray// in two pointer techniqueint f[MAX]; // Function to store smallest prime factor of numbersvoid sieve(){ prime[0] = prime[1] = 1; for (int i = 2; i < MAX; i++) { if (!prime[i]) { for (int j = i * 2; j < MAX; j += i) { if (!prime[j]) prime[j] = i; } } } for (int i = 2; i < MAX; i++) { // If number is prime, // then smallest prime factor is the // number itself if (!prime[i]) prime[i] = i; }} // Function to return maximum length of subarray// with LCM = productint maxLengthSubArray(int* arr, int n){ // Initialize f with -1 mem(f, -1); for (int i = 0; i < n; ++i) { // Prime factorization of numbers // Store primes in a vector for every element while (arr[i] > 1) { int p = prime[arr[i]]; arr[i] /= p; v[i].pb(p); } } // Two pointers l and r // denoting left and right of subarray int l = 0, r = 1, ans = -1; // f is a mapping. // prime -> index in the current subarray // With the help of f, // we can detect whether a prime has // already occurred in the subarray for (int i : v[0]) { f[i] = 0; } while (l <= r && r < n) { int flag = 0; for (int i = 0; i < v[r].size(); i++) { // Map the prime to the index if (f[v[r][i]] == -1 || f[v[r][i]] == r) { f[v[r][i]] = r; } // If already occurred then, // start removing elements from the left else { flag = 1; break; } } // Remove elements if flag = 1 if (flag) { // Nullify entries of element at index 'l' for (int i : v[l]) { f[i] = -1; } // Increment 'l' l++; } else { // Maximize the answer when // no common factor is found ans = max(ans, r - l + 1); r++; } } // One length subarray is discarded if (ans == 1) ans = -1; return ans;} // Driver codeint main(){ sieve(); int arr[] = { 6, 10, 21 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxLengthSubArray(arr, n); return 0;} // Java implementation of the above approachimport java.io.*;import java.util.*; class GFG{ static int N = 100005;static int MAX = 1000002;static int[] prime = new int[MAX]; // Stores array of primes for every elementstatic ArrayList< ArrayList<Integer>> v = new ArrayList< ArrayList<Integer>>(); // Stores the position of a prime in the// subarray in two pointer techniquestatic int[] f = new int[MAX]; // Function to store smallest prime// factor of numbersstatic void sieve(){ for(int i = 0; i < N; i++) { v.add(new ArrayList<Integer>()); } prime[0] = prime[1] = 1; for(int i = 2; i < MAX; i++) { if (prime[i] == 0) { for(int j = i * 2; j < MAX; j += i) { if (prime[j] == 0) { prime[j] = i; } } } } for(int i = 2; i < MAX; i++) { // If number is prime, then // smallest prime factor is // the number itself if (prime[i] == 0) { prime[i] = i; } }} // Function to return maximum length of// subarray with LCM = productstatic int maxLengthSubArray(int[] arr, int n){ // Initialize f with -1 Arrays.fill(f, -1); for(int i = 0; i < n; ++i) { // Prime factorization of numbers // Store primes in a vector for // every element while (arr[i] > 1) { int p = prime[arr[i]]; arr[i] /= p; v.get(i).add(p); } } // Two pointers l and r denoting // left and right of subarray int l = 0, r = 1, ans = -1; // f is a mapping. // prime -> index in the current subarray // With the help of f, // we can detect whether a prime has // already occurred in the subarray for(int i : v.get(0)) { f[i] = 0; } while (l <= r && r < n) { int flag = 0; for(int i = 0; i < v.get(r).size(); i++) { // Map the prime to the index if (f[v.get(r).get(i)] == -1 || f[v.get(r).get(i)] == r) { f[v.get(r).get(i)] = r; } // If already occurred then, // start removing elements // from the left else { flag = 1; break; } } // Remove elements if flag = 1 if (flag != 0) { // Nullify entries of element // at index 'l' for(int i : v.get(l)) { f[i] = -1; } // Increment 'l' l++; } else { // Maximize the answer when // no common factor is found ans = Math.max(ans, r - l + 1); r++; } } // One length subarray is discarded if (ans == 1) { ans = -1; } return ans;} // Driver codepublic static void main(String[] args){ sieve(); int arr[] = { 6, 10, 21 }; int n = arr.length; System.out.println(maxLengthSubArray(arr, n));}} // This code is contributed by avanitrachhadiya2155 # Python3 implementation of the above approach N = 100005MAX = 1000002 prime = [0 for i in range(MAX + 1)] # Stores array of primes for every elementv = [[] for i in range(N)] # Stores the position of a prime in the subarray# in two pointer techniquef = [-1 for i in range(MAX)] # Function to store smallest prime factor of numbersdef sieve(): prime[0], prime[1] = 1, 1 for i in range(2, MAX + 1): if (prime[i] == 0): for j in range(i * 2, MAX, i): if (prime[j] == 0): prime[j] = i for i in range(2, MAX): # If number is prime, # then smallest prime factor is the # number itself if (prime[i] == 0): prime[i] = i # Function to return maximum length of subarray# with LCM = productdef maxLengthSubArray(arr, n): # Initialize f with -1 for i in range(n): f[i] = -1 for i in range(n): # Prime factorization of numbers # Store primes in a vector for every element while (arr[i] > 1): p = prime[arr[i]] arr[i] //= p v[i].append(p) # Two pointers l and r # denoting left and right of subarray l, r, ans = 0, 1, -1 # f is a mapping. # prime -> index in the current subarray # With the help of f, # we can detect whether a prime has # already occurred in the subarray for i in v[0]: f[i] = 0 while (l <= r and r < n): flag = 0 for i in range(len(v[r])): # Map the prime to the index if (f[v[r][i]] == -1 or f[v[r][i]] == r): f[v[r][i]] = r # If already occurred then, # start removing elements from the left else: flag = 1 break # Remove elements if flag = 1 if (flag): # Nullify entries of element at index 'l' for i in v[l]: f[i] = -1 # Increment 'l' l += 1 else : # Maximize the answer when # no common factor is found ans = max(ans, r - l + 1) r += 1 # One length subarray is discarded if (ans == 1): ans = -1 return ans # Driver codesieve()arr = [6, 10, 21]n = len(arr)print(maxLengthSubArray(arr, n)) # This code is contributed by mohit kumar // C# implementation of the above approachusing System;using System.Collections.Generic;class GFG{ static int N = 100005; static int MAX = 1000002; static int[] prime = new int[MAX]; // Stores array of primes for every element static List<List<int>> v = new List<List<int>>(); // Stores the position of a prime in the // subarray in two pointer technique static int[] f = new int[MAX]; // Function to store smallest prime // factor of numbers static void sieve() { for(int i = 0; i < N; i++) { v.Add(new List<int>()); } prime[0] = prime[1] = 1; for(int i = 2; i < MAX; i++) { if (prime[i] == 0) { for(int j = i * 2; j < MAX; j += i) { if (prime[j] == 0) { prime[j] = i; } } } } for(int i = 2; i < MAX; i++) { // If number is prime, then // smallest prime factor is // the number itself if (prime[i] == 0) { prime[i] = i; } } } // Function to return maximum length of // subarray with LCM = product static int maxLengthSubArray(int[] arr, int n) { // Initialize f with -1 Array.Fill(f, -1); for(int i = 0; i < n; ++i) { // Prime factorization of numbers // Store primes in a vector for // every element while (arr[i] > 1) { int p = prime[arr[i]]; arr[i] /= p; v[i].Add(p); } } // Two pointers l and r denoting // left and right of subarray int l = 0, r = 1, ans = -1; // f is a mapping. // prime -> index in the current subarray // With the help of f, // we can detect whether a prime has // already occurred in the subarray foreach(int i in v[0]) { f[i] = 0; } while (l <= r && r < n) { int flag = 0; for(int i = 0; i < v[r].Count; i++) { // Map the prime to the index if (f[v[r][i]] == -1 || f[v[r][i]] == r) { f[v[r][i]] = r; } // If already occurred then, // start removing elements // from the left else { flag = 1; break; } } // Remove elements if flag = 1 if (flag != 0) { // Nullify entries of element // at index 'l' foreach(int i in v[l]) { f[i] = -1; } // Increment 'l' l++; } else { // Maximize the answer when // no common factor is found ans = Math.Max(ans, r - l + 1); r++; } } // One length subarray is discarded if (ans == 1) { ans = -1; } return ans; } // Driver code static public void Main () { sieve(); int[] arr = { 6, 10, 21 }; int n = arr.Length; Console.WriteLine(maxLengthSubArray(arr, n)); }}// This code is contributed by rag2127 <script>// Javascript implementation of the above approach let N = 100005;let MAX = 1000002;let prime = new Array(MAX);for(let i=0;i<prime.length;i++){ prime[i]=0;}// Stores array of primes for every elementlet v = []; // Stores the position of a prime in the// subarray in two pointer techniquelet f = new Array(MAX); // Function to store smallest prime// factor of numbersfunction sieve(){ for(let i = 0; i < N; i++) { v.push([]); } prime[0] = prime[1] = 1; for(let i = 2; i < MAX; i++) { if (prime[i] == 0) { for(let j = i * 2; j < MAX; j += i) { if (prime[j] == 0) { prime[j] = i; } } } } for(let i = 2; i < MAX; i++) { // If number is prime, then // smallest prime factor is // the number itself if (prime[i] == 0) { prime[i] = i; } }} // Function to return maximum length of// subarray with LCM = productfunction maxLengthSubArray(arr,n){ // Initialize f with -1 for(let i=0;i<f.length;i++) { f[i]=-1; } for(let i = 0; i < n; ++i) { // Prime factorization of numbers // Store primes in a vector for // every element while (arr[i] > 1) { let p = prime[arr[i]]; arr[i] /= p; v[i].push(p); } } // Two pointers l and r denoting // left and right of subarray let l = 0, r = 1, ans = -1; // f is a mapping. // prime -> index in the current subarray // With the help of f, // we can detect whether a prime has // already occurred in the subarray for(let i=0;i< v[0].length;i++) { f[v[0][i]] = 0; } while (l <= r && r < n) { let flag = 0; for(let i = 0; i < v[r].length; i++) { // Map the prime to the index if (f[v[r][i]] == -1 || f[v[r][i]] == r) { f[v[r][i]] = r; } // If already occurred then, // start removing elements // from the left else { flag = 1; break; } } // Remove elements if flag = 1 if (flag != 0) { // Nullify entries of element // at index 'l' for(let i=0;i<v[l].length;i++) { f[v[l][i]] = -1; } // Increment 'l' l++; } else { // Maximize the answer when // no common factor is found ans = Math.max(ans, r - l + 1); r++; } } // One length subarray is discarded if (ans == 1) { ans = -1; } return ans;} // Driver code sieve();let arr=[ 6, 10, 21];let n = arr.length;document.write(maxLengthSubArray(arr, n)); // This code is contributed by patel2127</script> 2 mohit kumar 29 Shivi_Aggarwal Shashank_Sharma ukasp avanitrachhadiya2155 rag2127 unknown2108 patel2127 GCD-LCM Technical Scripter 2018 Algorithms Technical Scripter Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments DSA Sheet by Love Babbar Quadratic Probing in Hashing Difference between Informed and Uninformed Search in AI K means Clustering - Introduction SCAN (Elevator) Disk Scheduling Algorithms What are Hash Functions and How to choose a good Hash Function? Travelling Salesman Problem implementation using BackTracking Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Program for SSTF disk scheduling algorithm
[ { "code": null, "e": 24612, "s": 24584, "text": "\n03 Jun, 2021" }, { "code": null, "e": 24818, "s": 24612, "text": "Given an arr[], the task is to find the maximum length of the sub-array such that the LCM of the sub-array is equal to the product of numbers in the sub-array. If no valid sub-array exists, then print -1. " }, { "code": null, "e": 24865, "s": 24818, "text": "Note: The length of the sub-array must be ≥ 2." }, { "code": null, "e": 24877, "s": 24865, "text": "Examples: " }, { "code": null, "e": 24965, "s": 24877, "text": "Input: arr[] = { 6, 10, 21} Output: 2 The sub-array { 10, 21 } satisfies the condition." }, { "code": null, "e": 25066, "s": 24965, "text": "Input: arr[] = { 2, 2, 4} Output: -1 No sub-array satisfies the condition. Hence, the output is -1. " }, { "code": null, "e": 25281, "s": 25066, "text": "Naive Approach: Run nested loops to check the condition for every possible sub-array of length ≥ 2. If the sub-array satisfies the condition, then update ans = max(ans, length(sub-array)). Print the ans in the end." }, { "code": null, "e": 25334, "s": 25281, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25338, "s": 25334, "text": "C++" }, { "code": null, "e": 25343, "s": 25338, "text": "Java" }, { "code": null, "e": 25351, "s": 25343, "text": "Python3" }, { "code": null, "e": 25354, "s": 25351, "text": "C#" }, { "code": null, "e": 25358, "s": 25354, "text": "PHP" }, { "code": null, "e": 25369, "s": 25358, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; #define ll long long // Function to calculate gcd(a, b)int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // Function to return max length of subarray// that satisfies the conditionint maxLengthSubArray(const int* arr, int n){ int maxLen = -1; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { ll lcm = 1LL * arr[i]; ll product = 1LL * arr[i]; // Update LCM and product of the // sub-array for (int k = i + 1; k <= j; k++) { lcm = (((arr[k] * lcm)) / (gcd(arr[k], lcm))); product = product * arr[k]; } // If the current sub-array satisfies // the condition if (lcm == product) { // Choose the maximum maxLen = max(maxLen, j - i + 1); } } } return maxLen;} // Driver codeint main(){ int arr[] = { 6, 10, 21 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxLengthSubArray(arr, n); return 0;}", "e": 26535, "s": 25369, "text": null }, { "code": "// Java implementation of the above approachimport java.util.*; class GFG{ // Function to calculate gcd(a, b)static int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // Function to return max length of subarray// that satisfies the conditionstatic int maxLengthSubArray(int arr[], int n){ int maxLen = -1; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { int lcm = 1 * arr[i]; int product = 1 * arr[i]; // Update LCM and product of the // sub-array for (int k = i + 1; k <= j; k++) { lcm = (((arr[k] * lcm)) / (gcd(arr[k], lcm))); product = product * arr[k]; } // If the current sub-array satisfies // the condition if (lcm == product) { // Choose the maximum maxLen = Math.max(maxLen, j - i + 1); } } } return maxLen;} // Driver codepublic static void main(String args[]){ int arr[] = { 6, 10, 21 }; int n = arr.length; System.out.println(maxLengthSubArray(arr, n));}} // This code is contributed by// Shashank_Sharma", "e": 27780, "s": 26535, "text": null }, { "code": "# Python3 implementation of the# above approach # Function to calculate gcd(a, b)def gcd(a, b): if (b == 0): return a return gcd(b, a % b) # Function to return max length of# subarray that satisfies the conditiondef maxLengthSubArray(arr, n): maxLen = -1 for i in range(n - 1): for j in range(n): lcm = arr[i] product = arr[i] # Update LCM and product of the # sub-array for k in range(i + 1, j + 1): lcm = (((arr[k] * lcm)) // (gcd(arr[k], lcm))) product = product * arr[k] # If the current sub-array satisfies # the condition if (lcm == product): # Choose the maximum maxLen = max(maxLen, j - i + 1) return maxLen # Driver codearr = [6, 10, 21 ]n = len(arr)print(maxLengthSubArray(arr, n)) # This code is contributed by# mohit kumar 29", "e": 28730, "s": 27780, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{ // Function to calculate gcd(a, b)static int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // Function to return max length of subarray// that satisfies the conditionstatic int maxLengthSubArray(int[] arr, int n){ int maxLen = -1; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { int lcm = 1 * arr[i]; int product = 1 * arr[i]; // Update LCM and product of the // sub-array for (int k = i + 1; k <= j; k++) { lcm = (((arr[k] * lcm)) / (gcd(arr[k], lcm))); product = product * arr[k]; } // If the current sub-array satisfies // the condition if (lcm == product) { // Choose the maximum maxLen = Math.Max(maxLen, j - i + 1); } } } return maxLen;} // Driver codepublic static void Main(){ int[] arr = { 6, 10, 21 }; int n = arr.Length; Console.Write(maxLengthSubArray(arr, n));}} // This code is contributed by ita_c", "e": 29937, "s": 28730, "text": null }, { "code": "<?php// PHP implementation of the above approach // Function to calculate gcd(a, b)function gcd($a, $b){ if ($b == 0) return $a; return gcd($b, $a % $b);} // Function to return max length of subarray// that satisfies the conditionfunction maxLengthSubArray(&$arr, $n){ $maxLen = -1; for ($i = 0; $i < $n - 1; $i++) { for ($j = $i + 1; $j < $n; $j++) { $lcm = $arr[$i]; $product = $arr[$i]; // Update LCM and product of the // sub-array for ($k = $i + 1; $k <= $j; $k++) { $lcm = ((($arr[$k] * $lcm)) / (gcd($arr[$k], $lcm))); $product = $product * $arr[$k]; } // If the current sub-array satisfies // the condition if ($lcm == $product) { // Choose the maximum $maxLen = max($maxLen, $j - $i + 1); } } } return $maxLen;} // Driver code$arr = array(6, 10, 21 );$n = sizeof($arr);echo(maxLengthSubArray($arr, $n)); // This code is contributed by Shivi_Aggarwal?>", "e": 31066, "s": 29937, "text": null }, { "code": "<script>// Javascript implementation of the above approach // Function to calculate gcd(a, b)function gcd(a,b){ if (b == 0) return a; return gcd(b, a % b);} // Function to return max length of subarray// that satisfies the conditionfunction maxLengthSubArray(arr,n){ let maxLen = -1; for (let i = 0; i < n - 1; i++) { for (let j = i + 1; j < n; j++) { let lcm = 1 * arr[i]; let product = 1 * arr[i]; // Update LCM and product of the // sub-array for (let k = i + 1; k <= j; k++) { lcm = (((arr[k] * lcm)) / (gcd(arr[k], lcm))); product = product * arr[k]; } // If the current sub-array satisfies // the condition if (lcm == product) { // Choose the maximum maxLen = Math.max(maxLen, j - i + 1); } } } return maxLen;} // Driver codelet arr=[6, 10, 21 ];let n = arr.length;document.write(maxLengthSubArray(arr, n)); // This code is contributed by unknown2108</script>", "e": 32222, "s": 31066, "text": null }, { "code": null, "e": 32224, "s": 32222, "text": "2" }, { "code": null, "e": 32360, "s": 32226, "text": "Efficient Approach: A sub-array will have its LCM equal to its product when no two elements in the sub-array have any common factor. " }, { "code": null, "e": 32375, "s": 32360, "text": "For example: " }, { "code": null, "e": 32633, "s": 32375, "text": "arr[] = { 6, 10, 21 }Prime factorization yields: arr[] = { 2 * 3, 2 * 5, 3 * 7 }[6, 10] has 2 as a common factor. [6, 10, 21] has 2 as a common factor between 6 and 10. Sub-array [10, 21] has no common factor between any 2 elements. Therefore, answer = 2. " }, { "code": null, "e": 32810, "s": 32633, "text": "Firstly, prime factorization of numbers is done to deal with factors. To calculate the sub-array in which no 2 elements have a common factor, we use the two-pointer technique. " }, { "code": null, "e": 32970, "s": 32810, "text": "Two pointers run, both from the right and they represent the current sub-array. We add elements in the sub-array from the right. Now there are two scenarios: " }, { "code": null, "e": 33379, "s": 32970, "text": "An element is added in the current sub-array if it has no factor in common with the current elements in the sub-array. If a common factor is found, then starting from the left, elements are subsequently eliminated until no common factor is found with the newly added element.If there are no common factors between the newly added element and existing elements, then update ans = max(ans, length of sub-array)" }, { "code": null, "e": 33655, "s": 33379, "text": "An element is added in the current sub-array if it has no factor in common with the current elements in the sub-array. If a common factor is found, then starting from the left, elements are subsequently eliminated until no common factor is found with the newly added element." }, { "code": null, "e": 33789, "s": 33655, "text": "If there are no common factors between the newly added element and existing elements, then update ans = max(ans, length of sub-array)" }, { "code": null, "e": 33842, "s": 33789, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 33846, "s": 33842, "text": "C++" }, { "code": null, "e": 33851, "s": 33846, "text": "Java" }, { "code": null, "e": 33859, "s": 33851, "text": "Python3" }, { "code": null, "e": 33862, "s": 33859, "text": "C#" }, { "code": null, "e": 33873, "s": 33862, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h> #define pb push_back#define N 100005#define MAX 1000002#define mem(a, b) memset(a, b, sizeof(a)) using namespace std; int prime[MAX]; // Stores array of primes for every elementvector<int> v[N]; // Stores the position of a prime in the subarray// in two pointer techniqueint f[MAX]; // Function to store smallest prime factor of numbersvoid sieve(){ prime[0] = prime[1] = 1; for (int i = 2; i < MAX; i++) { if (!prime[i]) { for (int j = i * 2; j < MAX; j += i) { if (!prime[j]) prime[j] = i; } } } for (int i = 2; i < MAX; i++) { // If number is prime, // then smallest prime factor is the // number itself if (!prime[i]) prime[i] = i; }} // Function to return maximum length of subarray// with LCM = productint maxLengthSubArray(int* arr, int n){ // Initialize f with -1 mem(f, -1); for (int i = 0; i < n; ++i) { // Prime factorization of numbers // Store primes in a vector for every element while (arr[i] > 1) { int p = prime[arr[i]]; arr[i] /= p; v[i].pb(p); } } // Two pointers l and r // denoting left and right of subarray int l = 0, r = 1, ans = -1; // f is a mapping. // prime -> index in the current subarray // With the help of f, // we can detect whether a prime has // already occurred in the subarray for (int i : v[0]) { f[i] = 0; } while (l <= r && r < n) { int flag = 0; for (int i = 0; i < v[r].size(); i++) { // Map the prime to the index if (f[v[r][i]] == -1 || f[v[r][i]] == r) { f[v[r][i]] = r; } // If already occurred then, // start removing elements from the left else { flag = 1; break; } } // Remove elements if flag = 1 if (flag) { // Nullify entries of element at index 'l' for (int i : v[l]) { f[i] = -1; } // Increment 'l' l++; } else { // Maximize the answer when // no common factor is found ans = max(ans, r - l + 1); r++; } } // One length subarray is discarded if (ans == 1) ans = -1; return ans;} // Driver codeint main(){ sieve(); int arr[] = { 6, 10, 21 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxLengthSubArray(arr, n); return 0;}", "e": 36500, "s": 33873, "text": null }, { "code": "// Java implementation of the above approachimport java.io.*;import java.util.*; class GFG{ static int N = 100005;static int MAX = 1000002;static int[] prime = new int[MAX]; // Stores array of primes for every elementstatic ArrayList< ArrayList<Integer>> v = new ArrayList< ArrayList<Integer>>(); // Stores the position of a prime in the// subarray in two pointer techniquestatic int[] f = new int[MAX]; // Function to store smallest prime// factor of numbersstatic void sieve(){ for(int i = 0; i < N; i++) { v.add(new ArrayList<Integer>()); } prime[0] = prime[1] = 1; for(int i = 2; i < MAX; i++) { if (prime[i] == 0) { for(int j = i * 2; j < MAX; j += i) { if (prime[j] == 0) { prime[j] = i; } } } } for(int i = 2; i < MAX; i++) { // If number is prime, then // smallest prime factor is // the number itself if (prime[i] == 0) { prime[i] = i; } }} // Function to return maximum length of// subarray with LCM = productstatic int maxLengthSubArray(int[] arr, int n){ // Initialize f with -1 Arrays.fill(f, -1); for(int i = 0; i < n; ++i) { // Prime factorization of numbers // Store primes in a vector for // every element while (arr[i] > 1) { int p = prime[arr[i]]; arr[i] /= p; v.get(i).add(p); } } // Two pointers l and r denoting // left and right of subarray int l = 0, r = 1, ans = -1; // f is a mapping. // prime -> index in the current subarray // With the help of f, // we can detect whether a prime has // already occurred in the subarray for(int i : v.get(0)) { f[i] = 0; } while (l <= r && r < n) { int flag = 0; for(int i = 0; i < v.get(r).size(); i++) { // Map the prime to the index if (f[v.get(r).get(i)] == -1 || f[v.get(r).get(i)] == r) { f[v.get(r).get(i)] = r; } // If already occurred then, // start removing elements // from the left else { flag = 1; break; } } // Remove elements if flag = 1 if (flag != 0) { // Nullify entries of element // at index 'l' for(int i : v.get(l)) { f[i] = -1; } // Increment 'l' l++; } else { // Maximize the answer when // no common factor is found ans = Math.max(ans, r - l + 1); r++; } } // One length subarray is discarded if (ans == 1) { ans = -1; } return ans;} // Driver codepublic static void main(String[] args){ sieve(); int arr[] = { 6, 10, 21 }; int n = arr.length; System.out.println(maxLengthSubArray(arr, n));}} // This code is contributed by avanitrachhadiya2155", "e": 39801, "s": 36500, "text": null }, { "code": "# Python3 implementation of the above approach N = 100005MAX = 1000002 prime = [0 for i in range(MAX + 1)] # Stores array of primes for every elementv = [[] for i in range(N)] # Stores the position of a prime in the subarray# in two pointer techniquef = [-1 for i in range(MAX)] # Function to store smallest prime factor of numbersdef sieve(): prime[0], prime[1] = 1, 1 for i in range(2, MAX + 1): if (prime[i] == 0): for j in range(i * 2, MAX, i): if (prime[j] == 0): prime[j] = i for i in range(2, MAX): # If number is prime, # then smallest prime factor is the # number itself if (prime[i] == 0): prime[i] = i # Function to return maximum length of subarray# with LCM = productdef maxLengthSubArray(arr, n): # Initialize f with -1 for i in range(n): f[i] = -1 for i in range(n): # Prime factorization of numbers # Store primes in a vector for every element while (arr[i] > 1): p = prime[arr[i]] arr[i] //= p v[i].append(p) # Two pointers l and r # denoting left and right of subarray l, r, ans = 0, 1, -1 # f is a mapping. # prime -> index in the current subarray # With the help of f, # we can detect whether a prime has # already occurred in the subarray for i in v[0]: f[i] = 0 while (l <= r and r < n): flag = 0 for i in range(len(v[r])): # Map the prime to the index if (f[v[r][i]] == -1 or f[v[r][i]] == r): f[v[r][i]] = r # If already occurred then, # start removing elements from the left else: flag = 1 break # Remove elements if flag = 1 if (flag): # Nullify entries of element at index 'l' for i in v[l]: f[i] = -1 # Increment 'l' l += 1 else : # Maximize the answer when # no common factor is found ans = max(ans, r - l + 1) r += 1 # One length subarray is discarded if (ans == 1): ans = -1 return ans # Driver codesieve()arr = [6, 10, 21]n = len(arr)print(maxLengthSubArray(arr, n)) # This code is contributed by mohit kumar", "e": 42130, "s": 39801, "text": null }, { "code": "// C# implementation of the above approachusing System;using System.Collections.Generic;class GFG{ static int N = 100005; static int MAX = 1000002; static int[] prime = new int[MAX]; // Stores array of primes for every element static List<List<int>> v = new List<List<int>>(); // Stores the position of a prime in the // subarray in two pointer technique static int[] f = new int[MAX]; // Function to store smallest prime // factor of numbers static void sieve() { for(int i = 0; i < N; i++) { v.Add(new List<int>()); } prime[0] = prime[1] = 1; for(int i = 2; i < MAX; i++) { if (prime[i] == 0) { for(int j = i * 2; j < MAX; j += i) { if (prime[j] == 0) { prime[j] = i; } } } } for(int i = 2; i < MAX; i++) { // If number is prime, then // smallest prime factor is // the number itself if (prime[i] == 0) { prime[i] = i; } } } // Function to return maximum length of // subarray with LCM = product static int maxLengthSubArray(int[] arr, int n) { // Initialize f with -1 Array.Fill(f, -1); for(int i = 0; i < n; ++i) { // Prime factorization of numbers // Store primes in a vector for // every element while (arr[i] > 1) { int p = prime[arr[i]]; arr[i] /= p; v[i].Add(p); } } // Two pointers l and r denoting // left and right of subarray int l = 0, r = 1, ans = -1; // f is a mapping. // prime -> index in the current subarray // With the help of f, // we can detect whether a prime has // already occurred in the subarray foreach(int i in v[0]) { f[i] = 0; } while (l <= r && r < n) { int flag = 0; for(int i = 0; i < v[r].Count; i++) { // Map the prime to the index if (f[v[r][i]] == -1 || f[v[r][i]] == r) { f[v[r][i]] = r; } // If already occurred then, // start removing elements // from the left else { flag = 1; break; } } // Remove elements if flag = 1 if (flag != 0) { // Nullify entries of element // at index 'l' foreach(int i in v[l]) { f[i] = -1; } // Increment 'l' l++; } else { // Maximize the answer when // no common factor is found ans = Math.Max(ans, r - l + 1); r++; } } // One length subarray is discarded if (ans == 1) { ans = -1; } return ans; } // Driver code static public void Main () { sieve(); int[] arr = { 6, 10, 21 }; int n = arr.Length; Console.WriteLine(maxLengthSubArray(arr, n)); }}// This code is contributed by rag2127", "e": 44984, "s": 42130, "text": null }, { "code": "<script>// Javascript implementation of the above approach let N = 100005;let MAX = 1000002;let prime = new Array(MAX);for(let i=0;i<prime.length;i++){ prime[i]=0;}// Stores array of primes for every elementlet v = []; // Stores the position of a prime in the// subarray in two pointer techniquelet f = new Array(MAX); // Function to store smallest prime// factor of numbersfunction sieve(){ for(let i = 0; i < N; i++) { v.push([]); } prime[0] = prime[1] = 1; for(let i = 2; i < MAX; i++) { if (prime[i] == 0) { for(let j = i * 2; j < MAX; j += i) { if (prime[j] == 0) { prime[j] = i; } } } } for(let i = 2; i < MAX; i++) { // If number is prime, then // smallest prime factor is // the number itself if (prime[i] == 0) { prime[i] = i; } }} // Function to return maximum length of// subarray with LCM = productfunction maxLengthSubArray(arr,n){ // Initialize f with -1 for(let i=0;i<f.length;i++) { f[i]=-1; } for(let i = 0; i < n; ++i) { // Prime factorization of numbers // Store primes in a vector for // every element while (arr[i] > 1) { let p = prime[arr[i]]; arr[i] /= p; v[i].push(p); } } // Two pointers l and r denoting // left and right of subarray let l = 0, r = 1, ans = -1; // f is a mapping. // prime -> index in the current subarray // With the help of f, // we can detect whether a prime has // already occurred in the subarray for(let i=0;i< v[0].length;i++) { f[v[0][i]] = 0; } while (l <= r && r < n) { let flag = 0; for(let i = 0; i < v[r].length; i++) { // Map the prime to the index if (f[v[r][i]] == -1 || f[v[r][i]] == r) { f[v[r][i]] = r; } // If already occurred then, // start removing elements // from the left else { flag = 1; break; } } // Remove elements if flag = 1 if (flag != 0) { // Nullify entries of element // at index 'l' for(let i=0;i<v[l].length;i++) { f[v[l][i]] = -1; } // Increment 'l' l++; } else { // Maximize the answer when // no common factor is found ans = Math.max(ans, r - l + 1); r++; } } // One length subarray is discarded if (ans == 1) { ans = -1; } return ans;} // Driver code sieve();let arr=[ 6, 10, 21];let n = arr.length;document.write(maxLengthSubArray(arr, n)); // This code is contributed by patel2127</script>", "e": 48100, "s": 44984, "text": null }, { "code": null, "e": 48102, "s": 48100, "text": "2" }, { "code": null, "e": 48119, "s": 48104, "text": "mohit kumar 29" }, { "code": null, "e": 48134, "s": 48119, "text": "Shivi_Aggarwal" }, { "code": null, "e": 48150, "s": 48134, "text": "Shashank_Sharma" }, { "code": null, "e": 48156, "s": 48150, "text": "ukasp" }, { "code": null, "e": 48177, "s": 48156, "text": "avanitrachhadiya2155" }, { "code": null, "e": 48185, "s": 48177, "text": "rag2127" }, { "code": null, "e": 48197, "s": 48185, "text": "unknown2108" }, { "code": null, "e": 48207, "s": 48197, "text": "patel2127" }, { "code": null, "e": 48215, "s": 48207, "text": "GCD-LCM" }, { "code": null, "e": 48239, "s": 48215, "text": "Technical Scripter 2018" }, { "code": null, "e": 48250, "s": 48239, "text": "Algorithms" }, { "code": null, "e": 48269, "s": 48250, "text": "Technical Scripter" }, { "code": null, "e": 48280, "s": 48269, "text": "Algorithms" }, { "code": null, "e": 48378, "s": 48280, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 48387, "s": 48378, "text": "Comments" }, { "code": null, "e": 48400, "s": 48387, "text": "Old Comments" }, { "code": null, "e": 48425, "s": 48400, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 48454, "s": 48425, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 48510, "s": 48454, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 48544, "s": 48510, "text": "K means Clustering - Introduction" }, { "code": null, "e": 48587, "s": 48544, "text": "SCAN (Elevator) Disk Scheduling Algorithms" }, { "code": null, "e": 48651, "s": 48587, "text": "What are Hash Functions and How to choose a good Hash Function?" }, { "code": null, "e": 48713, "s": 48651, "text": "Travelling Salesman Problem implementation using BackTracking" }, { "code": null, "e": 48780, "s": 48713, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" } ]
Count the characters in each word in a given sentence | Practice | GeeksforGeeks
Given a string containing multiple words, count the characters in each word and display them. Example 1: Input: S = "the quick brown fox" Output: 3 5 5 3 Explanation: "the" has 3 characters "quick" has 5 characters "brown" has 5 characters "fox" has 3 characters ​Example 2: Input: S = "geeks for geeks" Output: 5 3 5 Explanation: "geeks" has 5 characters "for" has 3 characters "geeks" has 5 characters Your Task: You don't need to read input or print anything. Your task is to complete the function countChars() which takes the string S as inputs are returns an array containing the number of characters in each word of the string in the order as they appear in the input string S. Expected Time Complexity: O(|S|). Expected Auxiliary Space: O(|S|) (for output). Constraints: 1 <= |S| <= 105 0 codewithshoaib191 month ago int c = 0; ArrayList<Integer> list = new ArrayList<>(); for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == ' ') { list.add(c); c = 0; } else { c++; } } list.add(c); return list; 0 codewithshoaib191 month ago String strArr[] = s.split(" "); ArrayList<Integer> list = new ArrayList<>(); for (int i = 0; i < strArr.length; i++) { list.add(strArr[i].length()); } return list; 0 selfless3 months ago ArrayList<Integer> countChars (String s) { // code here ArrayList<Integer> ans = new ArrayList<>(); String a[]=s.split(" "); int count=0; for(int i=0;i<a.length;i++){ String S=a[i]; ans.add(S.length()); } return ans; } +1 badgujarsachin836 months ago vector<int> countChars (string s) { // code here int c=0; vector<int> v; for(int i=0;i<s.size();i++){ if(s[i]==' '){ v.push_back(c); c=0; }else{ c++; } } v.push_back(c); return v; } -1 ybrijesh7 months ago vector<int> v; int count=0; for(int i=0;i<s.length();i++) { if(s[i]==' ') { count=0; } else { count++; } v.push_back(count); } vector<int> v1; for(int i=0;i<v.size();i++) { if(v[i]==0) { v1.push_back(v[i-1]); } } v1.push_back(v[v.size()-1]); return v1; 0 Ashwani2 years ago Ashwani PYTHONfor t in range(int(input())): s=list(input().split()) for i in s: print(len(i),end=" ") print() 0 Manjot Kaur2 years ago Manjot Kaur https://practice.geeksforge....Correct AnswerExecution Time:0.24 0 Riya kashyap2 years ago Riya kashyap solution in javaimport java.util.*;import java.lang.*;import java.io.*;class GFG {public static void main (String[] args) { //code Scanner sc = new Scanner(System.in); int t = sc.nextInt(); sc.nextLine(); while(t--!=0) { String aa = sc.nextLine(); int count = 0; char y[] = aa.toCharArray(); for(int i=0;i<aa.length();i++) {="" if(y[i]="">='a' && y[i]<='z') count++; if(y[i]==' ') { System.out.print(count+" "); count=0; } } System.out.print(count); System.out.println(); } }} 0 Chandan Kumar2 years ago Chandan Kumar Solution:for _ in range(int(input())): s=input().split() for x in s: print(len(x),end=" ") print() 0 Naresh_Vishram3 years ago Naresh_Vishram for java userTake input with the help of BufferedReader 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": 320, "s": 226, "text": "Given a string containing multiple words, count the characters in each word and display them." }, { "code": null, "e": 331, "s": 320, "text": "Example 1:" }, { "code": null, "e": 490, "s": 331, "text": "Input:\nS = \"the quick brown fox\"\nOutput: 3 5 5 3\nExplanation: \"the\" has 3 characters\n\"quick\" has 5 characters\n\"brown\" has 5 characters\n\"fox\" has 3 characters\n" }, { "code": null, "e": 505, "s": 490, "text": "​Example 2:" }, { "code": null, "e": 636, "s": 505, "text": "Input: \nS = \"geeks for geeks\"\nOutput: 5 3 5\nExplanation: \"geeks\" has 5 characters\n\"for\" has 3 characters\n\"geeks\" has 5 characters\n" }, { "code": null, "e": 917, "s": 636, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function countChars() which takes the string S as inputs are returns an array containing the number of characters in each word of the string in the order as they appear in the input string S." }, { "code": null, "e": 999, "s": 917, "text": "\nExpected Time Complexity: O(|S|).\nExpected Auxiliary Space: O(|S|) (for output)." }, { "code": null, "e": 1029, "s": 999, "text": "\nConstraints:\n1 <= |S| <= 105" }, { "code": null, "e": 1033, "s": 1031, "text": "0" }, { "code": null, "e": 1061, "s": 1033, "text": "codewithshoaib191 month ago" }, { "code": null, "e": 1073, "s": 1061, "text": " int c = 0;" }, { "code": null, "e": 1126, "s": 1073, "text": " ArrayList<Integer> list = new ArrayList<>();" }, { "code": null, "e": 1175, "s": 1126, "text": " for (int i = 0; i < str.length(); i++) {" }, { "code": null, "e": 1215, "s": 1175, "text": " if (str.charAt(i) == ' ') {" }, { "code": null, "e": 1244, "s": 1215, "text": " list.add(c);" }, { "code": null, "e": 1267, "s": 1244, "text": " c = 0;" }, { "code": null, "e": 1288, "s": 1267, "text": " } else {" }, { "code": null, "e": 1309, "s": 1288, "text": " c++;" }, { "code": null, "e": 1323, "s": 1309, "text": " }" }, { "code": null, "e": 1333, "s": 1323, "text": " }" }, { "code": null, "e": 1354, "s": 1333, "text": " list.add(c);" }, { "code": null, "e": 1375, "s": 1354, "text": " return list;" }, { "code": null, "e": 1377, "s": 1375, "text": "0" }, { "code": null, "e": 1405, "s": 1377, "text": "codewithshoaib191 month ago" }, { "code": null, "e": 1604, "s": 1405, "text": " String strArr[] = s.split(\" \"); ArrayList<Integer> list = new ArrayList<>(); for (int i = 0; i < strArr.length; i++) { list.add(strArr[i].length()); } return list;" }, { "code": null, "e": 1606, "s": 1604, "text": "0" }, { "code": null, "e": 1627, "s": 1606, "text": "selfless3 months ago" }, { "code": null, "e": 1957, "s": 1627, "text": " ArrayList<Integer> countChars (String s) { // code here ArrayList<Integer> ans = new ArrayList<>(); String a[]=s.split(\" \"); int count=0; for(int i=0;i<a.length;i++){ String S=a[i]; ans.add(S.length()); } return ans; }" }, { "code": null, "e": 1960, "s": 1957, "text": "+1" }, { "code": null, "e": 1989, "s": 1960, "text": "badgujarsachin836 months ago" }, { "code": null, "e": 2345, "s": 1989, "text": "vector<int> countChars (string s)\n {\n // code here\n int c=0;\n vector<int> v;\n for(int i=0;i<s.size();i++){\n if(s[i]==' '){\n v.push_back(c);\n c=0;\n }else{\n c++;\n }\n \n }\n \n v.push_back(c);\n return v;\n \n }" }, { "code": null, "e": 2348, "s": 2345, "text": "-1" }, { "code": null, "e": 2369, "s": 2348, "text": "ybrijesh7 months ago" }, { "code": null, "e": 2903, "s": 2369, "text": " vector<int> v; int count=0; for(int i=0;i<s.length();i++) { if(s[i]==' ') { count=0; } else { count++; } v.push_back(count); } vector<int> v1; for(int i=0;i<v.size();i++) { if(v[i]==0) { v1.push_back(v[i-1]); } } v1.push_back(v[v.size()-1]); return v1; " }, { "code": null, "e": 2905, "s": 2903, "text": "0" }, { "code": null, "e": 2924, "s": 2905, "text": "Ashwani2 years ago" }, { "code": null, "e": 2932, "s": 2924, "text": "Ashwani" }, { "code": null, "e": 3050, "s": 2932, "text": "PYTHONfor t in range(int(input())): s=list(input().split()) for i in s: print(len(i),end=\" \") print()" }, { "code": null, "e": 3052, "s": 3050, "text": "0" }, { "code": null, "e": 3075, "s": 3052, "text": "Manjot Kaur2 years ago" }, { "code": null, "e": 3087, "s": 3075, "text": "Manjot Kaur" }, { "code": null, "e": 3152, "s": 3087, "text": "https://practice.geeksforge....Correct AnswerExecution Time:0.24" }, { "code": null, "e": 3154, "s": 3152, "text": "0" }, { "code": null, "e": 3178, "s": 3154, "text": "Riya kashyap2 years ago" }, { "code": null, "e": 3191, "s": 3178, "text": "Riya kashyap" }, { "code": null, "e": 3753, "s": 3191, "text": "solution in javaimport java.util.*;import java.lang.*;import java.io.*;class GFG {public static void main (String[] args) { //code Scanner sc = new Scanner(System.in); int t = sc.nextInt(); sc.nextLine(); while(t--!=0) { String aa = sc.nextLine(); int count = 0; char y[] = aa.toCharArray(); for(int i=0;i<aa.length();i++) {=\"\" if(y[i]=\"\">='a' && y[i]<='z') count++; if(y[i]==' ') { System.out.print(count+\" \"); count=0; } } System.out.print(count); System.out.println(); } }}" }, { "code": null, "e": 3755, "s": 3753, "text": "0" }, { "code": null, "e": 3780, "s": 3755, "text": "Chandan Kumar2 years ago" }, { "code": null, "e": 3794, "s": 3780, "text": "Chandan Kumar" }, { "code": null, "e": 3909, "s": 3794, "text": "Solution:for _ in range(int(input())): s=input().split() for x in s: print(len(x),end=\" \") print()" }, { "code": null, "e": 3911, "s": 3909, "text": "0" }, { "code": null, "e": 3937, "s": 3911, "text": "Naresh_Vishram3 years ago" }, { "code": null, "e": 3952, "s": 3937, "text": "Naresh_Vishram" }, { "code": null, "e": 4008, "s": 3952, "text": "for java userTake input with the help of BufferedReader" }, { "code": null, "e": 4154, "s": 4008, "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": 4190, "s": 4154, "text": " Login to access your submissions. " }, { "code": null, "e": 4200, "s": 4190, "text": "\nProblem\n" }, { "code": null, "e": 4210, "s": 4200, "text": "\nContest\n" }, { "code": null, "e": 4273, "s": 4210, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4421, "s": 4273, "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": 4629, "s": 4421, "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": 4735, "s": 4629, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Addition & Product of 2 Graphs Rank and Nullity of a Graph - GeeksforGeeks
22 Jun, 2021 Introduction :A Graph G consists of vertices & edges. The edges are lines or arcs that connect any two nodes in the graph, and the nodes are also known as vertices. A simple Graph G = (V, E) consists of : V : Finite set of vertices E : Set of edges Example – In the diagram below, Graph G consists of :V = { A, B, C, D}E = { {A, C}, {C, B}, {A, D}} Addition Of 2 Graphs :If we have 2 graphs, G1 & G2 such that their vertices intersection is null ( V(G1)∩ V(G2) = ∅ ) , then the sum :G1 + G2 is defined as the graph whose vertex set V(G1+G2) is V(G1) + V(G2) and the edge set consists of these edges, which are inG1 & in G2 & the edges contained by joining each vertex of G1 to each vertex of G2.Example : The addition of 2 graphs shown G1 & G2 are : Here : V(G1)∩ V(G2) = ∅ The already contained edges in G1 are, E(G1) : {{A, B}} and the vertices are : V(G1) = {A, B}The already contained edges in G2 are, E(G2) : {{A’, B’} ,{B’,C’} }and the vertices are : V(G2) = {A’, B’, C’}So the graph , G1 + G2 will have (i) vertices as : V(G1+G2 ) = V(G1) + V(G2) = { A, B. A’, B’, C’}(ii) and E(G1 + G2 ) = E(G1) + E(G2) + edges contained by joining each vertex of G1 to each vertex of G2 ={ {A, B}, {A’, B’} ,{B’,C’} , {A,A’} , {A, B’}, {A, C’}, {B,A’} , {B, B’}, {B, C’}} Product of 2 Graphs :We define the product of 2 graphs, G1*G2, as (G1*G2)(V, E) such that :(i) Vertices : V(G1*G2 ) = Cartesian product of V(G1) & V(G2) = V(G1) * V(G2) and (ii) Edges : Considering any 2 vertices in the set of vertices of the graph G1*G2 (i.e, the cartesian product of V(G1) & V(G2) ) , say A & V (Note : A & V are vertex that is a pair of 2 elements) such that : A = (a1, a2) & V = (v1,v2) , then {A, V} is an edge in graph G1*G2 if one of the following is satisfied –(i) a1 = v1 ( the first element of the pair is same) and a2 is adjacent to v2(ii) a2 = v2 ( the second element of the pair is same) and a1 is adjacent to v1 Example : Consider 2 Graphs, G1 & G2 such that :V(G1) = {A, B} E(G1) = { {A, B} }V(G2) = {A’, B’, C’}E(G2) ={ {A’, B’} ,{B’,C’} } Then Graph G1*G2 will have : (i) Vertices : V(G1*G2 ) = cartesian product of V(G1) & V(G2) = V(G1) * V(G2) = { (A, A’) , (A, B’), (A, C’), (B, A’) , (B, B’), (B, C’) }(ii) Edges : We need to check for every pair of vertex in G1 * G2 that it can form an edge / not . As we know, that if we have 2 vertices A & V in (G1 * G2) such that : A = (a1, a2) & V = (v1,v2) , then {A, V} is an edge in graph G1*G2 if one of the following is satisfied –(i) a1 = v1 (first element of pair is same) AND a2 is adjacent to v2(ii) a2 = v2 (second element of pair is same) AND a1 is adjacent to v1 Graph Product G1 * G2 We find that :1. { (A, A’) , (A, B’) } is an edge because the first element of the pair is same (A = A) and A’ is adjacent to B’ in G22. { (A, C’) , (A, B’) } is an edge because the first element of the pair is same (A = A) and C’ is adjacent to B’ in G23. { (B, A’) , (B, B’) } is an edge because the first element of the pair is same (B = B) and A’ is adjacent to B’ in G24. { (B, C’) , (B, B’) } is an edge because the first element of the pair is same (A = A) and C’ is adjacent to B’ in G25. { (A, A’) , (B, A’) } is an edge because the second element of the pair is same (A’ = A’) and A is adjacent to B in G16. { (A, B’) , (B, B’) } is an edge because the second element of the pair is same (B’ = B’) and A is adjacent to B in G17. { (A, C’) , (B, C’) } is an edge because the second element of the pair is same (C’ = C’) and A is adjacent to B in G1 So E(G1*G2) = { { (A, A’) , (A, B’) } , { (A, C’) , (A, B’) } , { (B, A’) , (B, B’) } , { (B, C’) , (B, B’) } , { (A, A’) , (B, A’) } , { (A, B’) , (B, B’) } , { (A, C’) , (B, C’) } } In this way we can find the addition & product of any 2 graphs. Rank & Nullity of a Graph :Let G(V,E) be a graph with n vertices & m edges and K Components.i.e.; |G(V)| = n & |G(E)| = m we define the rank P(G) & nullity μ(G) as follows : If G Is not connected : P(G) = Rank of G = n - k μ(G) = Nullity of G = m - n + k If G Is connected : P(G) = Rank of G = n - 1 μ(G) = Nullity of G = m - n + 1 Example 1 :The Graph shown below is connected : Graph G |G(V)| = n = 4 &|G(E)| = m = 3P(G) = Rank of G = n – 1 = 4 -1 = 3μ(G) = Nullity of G = m – n + 1 = 3 – 4 + 1 = 0 Example 2 : The Graph shown below is not connected : |G(V)| = n = 6 &|G(E)| = m = 4 &No of components = k = 2P(G) = Rank of G = n – k = 6 – 2 = 4μ(G) = Nullity of G = m – n + k = 4 – 6 + 2 = 0 Engineering Mathematics GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Univariate, Bivariate and Multivariate data and its analysis Activation Functions Difference between Propositional Logic and Predicate Logic Z-test Proof that vertex cover is NP complete Layers of OSI Model ACID Properties in DBMS Types of Operating Systems Normal Forms in DBMS Page Replacement Algorithms in Operating Systems
[ { "code": null, "e": 24812, "s": 24784, "text": "\n22 Jun, 2021" }, { "code": null, "e": 24977, "s": 24812, "text": "Introduction :A Graph G consists of vertices & edges. The edges are lines or arcs that connect any two nodes in the graph, and the nodes are also known as vertices." }, { "code": null, "e": 25017, "s": 24977, "text": "A simple Graph G = (V, E) consists of :" }, { "code": null, "e": 25044, "s": 25017, "text": "V : Finite set of vertices" }, { "code": null, "e": 25061, "s": 25044, "text": "E : Set of edges" }, { "code": null, "e": 25161, "s": 25061, "text": "Example – In the diagram below, Graph G consists of :V = { A, B, C, D}E = { {A, C}, {C, B}, {A, D}}" }, { "code": null, "e": 25563, "s": 25161, "text": "Addition Of 2 Graphs :If we have 2 graphs, G1 & G2 such that their vertices intersection is null ( V(G1)∩ V(G2) = ∅ ) , then the sum :G1 + G2 is defined as the graph whose vertex set V(G1+G2) is V(G1) + V(G2) and the edge set consists of these edges, which are inG1 & in G2 & the edges contained by joining each vertex of G1 to each vertex of G2.Example : The addition of 2 graphs shown G1 & G2 are : " }, { "code": null, "e": 25587, "s": 25563, "text": "Here : V(G1)∩ V(G2) = ∅" }, { "code": null, "e": 26080, "s": 25587, "text": "The already contained edges in G1 are, E(G1) : {{A, B}} and the vertices are : V(G1) = {A, B}The already contained edges in G2 are, E(G2) : {{A’, B’} ,{B’,C’} }and the vertices are : V(G2) = {A’, B’, C’}So the graph , G1 + G2 will have (i) vertices as : V(G1+G2 ) = V(G1) + V(G2) = { A, B. A’, B’, C’}(ii) and E(G1 + G2 ) = E(G1) + E(G2) + edges contained by joining each vertex of G1 to each vertex of G2 ={ {A, B}, {A’, B’} ,{B’,C’} , {A,A’} , {A, B’}, {A, C’}, {B,A’} , {B, B’}, {B, C’}}" }, { "code": null, "e": 26726, "s": 26080, "text": "Product of 2 Graphs :We define the product of 2 graphs, G1*G2, as (G1*G2)(V, E) such that :(i) Vertices : V(G1*G2 ) = Cartesian product of V(G1) & V(G2) = V(G1) * V(G2) and (ii) Edges : Considering any 2 vertices in the set of vertices of the graph G1*G2 (i.e, the cartesian product of V(G1) & V(G2) ) , say A & V (Note : A & V are vertex that is a pair of 2 elements) such that : A = (a1, a2) & V = (v1,v2) , then {A, V} is an edge in graph G1*G2 if one of the following is satisfied –(i) a1 = v1 ( the first element of the pair is same) and a2 is adjacent to v2(ii) a2 = v2 ( the second element of the pair is same) and a1 is adjacent to v1" }, { "code": null, "e": 26856, "s": 26726, "text": "Example : Consider 2 Graphs, G1 & G2 such that :V(G1) = {A, B} E(G1) = { {A, B} }V(G2) = {A’, B’, C’}E(G2) ={ {A’, B’} ,{B’,C’} }" }, { "code": null, "e": 27440, "s": 26856, "text": "Then Graph G1*G2 will have : (i) Vertices : V(G1*G2 ) = cartesian product of V(G1) & V(G2) = V(G1) * V(G2) = { (A, A’) , (A, B’), (A, C’), (B, A’) , (B, B’), (B, C’) }(ii) Edges : We need to check for every pair of vertex in G1 * G2 that it can form an edge / not . As we know, that if we have 2 vertices A & V in (G1 * G2) such that : A = (a1, a2) & V = (v1,v2) , then {A, V} is an edge in graph G1*G2 if one of the following is satisfied –(i) a1 = v1 (first element of pair is same) AND a2 is adjacent to v2(ii) a2 = v2 (second element of pair is same) AND a1 is adjacent to v1" }, { "code": null, "e": 27462, "s": 27440, "text": "Graph Product G1 * G2" }, { "code": null, "e": 28327, "s": 27462, "text": "We find that :1. { (A, A’) , (A, B’) } is an edge because the first element of the pair is same (A = A) and A’ is adjacent to B’ in G22. { (A, C’) , (A, B’) } is an edge because the first element of the pair is same (A = A) and C’ is adjacent to B’ in G23. { (B, A’) , (B, B’) } is an edge because the first element of the pair is same (B = B) and A’ is adjacent to B’ in G24. { (B, C’) , (B, B’) } is an edge because the first element of the pair is same (A = A) and C’ is adjacent to B’ in G25. { (A, A’) , (B, A’) } is an edge because the second element of the pair is same (A’ = A’) and A is adjacent to B in G16. { (A, B’) , (B, B’) } is an edge because the second element of the pair is same (B’ = B’) and A is adjacent to B in G17. { (A, C’) , (B, C’) } is an edge because the second element of the pair is same (C’ = C’) and A is adjacent to B in G1" }, { "code": null, "e": 28517, "s": 28327, "text": "So E(G1*G2) = { { (A, A’) , (A, B’) } , { (A, C’) , (A, B’) } , { (B, A’) , (B, B’) } , { (B, C’) , (B, B’) } , { (A, A’) , (B, A’) } , { (A, B’) , (B, B’) } , { (A, C’) , (B, C’) } }" }, { "code": null, "e": 28581, "s": 28517, "text": "In this way we can find the addition & product of any 2 graphs." }, { "code": null, "e": 28756, "s": 28581, "text": "Rank & Nullity of a Graph :Let G(V,E) be a graph with n vertices & m edges and K Components.i.e.; |G(V)| = n & |G(E)| = m we define the rank P(G) & nullity μ(G) as follows :" }, { "code": null, "e": 28917, "s": 28756, "text": "If G Is not connected : \nP(G) = Rank of G = n - k\nμ(G) = Nullity of G = m - n + k\n\nIf G Is connected : \nP(G) = Rank of G = n - 1\nμ(G) = Nullity of G = m - n + 1" }, { "code": null, "e": 28966, "s": 28917, "text": "Example 1 :The Graph shown below is connected : " }, { "code": null, "e": 28974, "s": 28966, "text": "Graph G" }, { "code": null, "e": 29088, "s": 28974, "text": "|G(V)| = n = 4 &|G(E)| = m = 3P(G) = Rank of G = n – 1 = 4 -1 = 3μ(G) = Nullity of G = m – n + 1 = 3 – 4 + 1 = 0" }, { "code": null, "e": 29141, "s": 29088, "text": "Example 2 : The Graph shown below is not connected :" }, { "code": null, "e": 29283, "s": 29141, "text": "|G(V)| = n = 6 &|G(E)| = m = 4 &No of components = k = 2P(G) = Rank of G = n – k = 6 – 2 = 4μ(G) = Nullity of G = m – n + k = 4 – 6 + 2 = 0 " }, { "code": null, "e": 29307, "s": 29283, "text": "Engineering Mathematics" }, { "code": null, "e": 29315, "s": 29307, "text": "GATE CS" }, { "code": null, "e": 29413, "s": 29315, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29422, "s": 29413, "text": "Comments" }, { "code": null, "e": 29435, "s": 29422, "text": "Old Comments" }, { "code": null, "e": 29496, "s": 29435, "text": "Univariate, Bivariate and Multivariate data and its analysis" }, { "code": null, "e": 29517, "s": 29496, "text": "Activation Functions" }, { "code": null, "e": 29576, "s": 29517, "text": "Difference between Propositional Logic and Predicate Logic" }, { "code": null, "e": 29583, "s": 29576, "text": "Z-test" }, { "code": null, "e": 29622, "s": 29583, "text": "Proof that vertex cover is NP complete" }, { "code": null, "e": 29642, "s": 29622, "text": "Layers of OSI Model" }, { "code": null, "e": 29666, "s": 29642, "text": "ACID Properties in DBMS" }, { "code": null, "e": 29693, "s": 29666, "text": "Types of Operating Systems" }, { "code": null, "e": 29714, "s": 29693, "text": "Normal Forms in DBMS" } ]
Why Protected access modifier used in Java?
The data members and methods of a class can be accessed from the same package or sub-classes in a different package if they are specified with the protected access modifier. The keyword protected is used to specify this modifier. A program that demonstrates the protected access modifier in Java is given as follows: Live Demo class A { protected int a = 9; public void printA() { System.out.println("Value of a = " + a); } } public class Demo { public static void main(String args[]) { A obj = new A(); obj.a = 18; obj.printA(); } } Value of a = 18 Now let us understand the above program. The class A has a protected data member a that can be accessed from the same package or sub-classes in a different package. The public method printA() displays the value of a. A code snippet which demonstrates this is as follows: class A { protected int a = 9; public void printA() { System.out.println("Value of a = " + a); } } In the main() method in class Demo, an object obj of class A is created. The value of obj.a is modified which is possible as it is protected and the modification is done in the same package. Then printA() method is called. A code snippet which demonstrates this is as follows: public class Demo { public static void main(String args[]) { A obj = new A(); obj.a = 18; obj.printA(); } }
[ { "code": null, "e": 1292, "s": 1062, "text": "The data members and methods of a class can be accessed from the same package or sub-classes in a different package if they are specified with the protected access modifier. The keyword protected is used to specify this modifier." }, { "code": null, "e": 1379, "s": 1292, "text": "A program that demonstrates the protected access modifier in Java is given as follows:" }, { "code": null, "e": 1390, "s": 1379, "text": " Live Demo" }, { "code": null, "e": 1636, "s": 1390, "text": "class A {\n protected int a = 9;\n public void printA() {\n System.out.println(\"Value of a = \" + a);\n }\n}\npublic class Demo {\n public static void main(String args[]) {\n A obj = new A();\n obj.a = 18;\n obj.printA();\n }\n}" }, { "code": null, "e": 1652, "s": 1636, "text": "Value of a = 18" }, { "code": null, "e": 1693, "s": 1652, "text": "Now let us understand the above program." }, { "code": null, "e": 1923, "s": 1693, "text": "The class A has a protected data member a that can be accessed from the same package or sub-classes in a different package. The public method printA() displays the value of a. A code snippet which demonstrates this is as follows:" }, { "code": null, "e": 2037, "s": 1923, "text": "class A {\n protected int a = 9;\n public void printA() {\n System.out.println(\"Value of a = \" + a);\n }\n}" }, { "code": null, "e": 2314, "s": 2037, "text": "In the main() method in class Demo, an object obj of class A is created. The value of obj.a is modified which is possible as it is protected and the modification is done in the same package. Then printA() method is called. A code snippet which demonstrates this is as follows:" }, { "code": null, "e": 2446, "s": 2314, "text": "public class Demo {\n public static void main(String args[]) {\n A obj = new A();\n obj.a = 18;\n obj.printA();\n }\n}" } ]
How to map a step definition to a feature file in Cucumber?
We can map a step definition file to a feature file in Cucumber. This can be done using the below steps − Step1− Create a feature file with .feature extension(say Login.feature) with the following − Feature − Login Module Scenario − Welcome Page Login verification Given User is on Welcome Page Then Welcome page should be displayed Step2− Create a step definition java file(say stepDefination.java) having the mapping of the step definition file to the feature file. package stepDefinations; import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; public class stepDefination { @Given("^User is on Welcome Page$") public void user_on_welcome_page() { System.out.println("User on welcome page"); } @Then("^Welcome page should be displayed$") public void verify_user_on_welcome_page() { System.out.println("User should be on welcome page"); } }
[ { "code": null, "e": 1168, "s": 1062, "text": "We can map a step definition file to a feature file in Cucumber. This can be done using the below steps −" }, { "code": null, "e": 1261, "s": 1168, "text": "Step1− Create a feature file with .feature extension(say Login.feature) with the following −" }, { "code": null, "e": 1284, "s": 1261, "text": "Feature − Login Module" }, { "code": null, "e": 1327, "s": 1284, "text": "Scenario − Welcome Page Login verification" }, { "code": null, "e": 1357, "s": 1327, "text": "Given User is on Welcome Page" }, { "code": null, "e": 1395, "s": 1357, "text": "Then Welcome page should be displayed" }, { "code": null, "e": 1530, "s": 1395, "text": "Step2− Create a step definition java file(say stepDefination.java) having the mapping of the step definition file to the feature file." }, { "code": null, "e": 1947, "s": 1530, "text": "package stepDefinations;\nimport io.cucumber.java.en.Given;\nimport io.cucumber.java.en.Then;\npublic class stepDefination {\n @Given(\"^User is on Welcome Page$\")\n public void user_on_welcome_page() {\n System.out.println(\"User on welcome page\");\n }\n @Then(\"^Welcome page should be displayed$\")\n public void verify_user_on_welcome_page() {\n System.out.println(\"User should be on welcome page\");\n }\n}" } ]
How to Use Column Alias in SELECT Statement? - GeeksforGeeks
08 Oct, 2021 Alias is used to give a temporary name(only for the duration of the query) to the column or table in order to make the column name or table name more readable. It does not change the name of the column permanently. Alias can be performed using the ‘AS’ keyword or without any keyword. But it is recommended to use the ‘AS’ keyword to avoid confusion between the initial column name and column alias. If alias name contain space or any special character, enclose alias name in single(‘ ‘) or double(” “) quotes. In SQL strings are also enclosed in single(‘ ‘) quotes. To avoid confusion, it is recommended to use double quotes for alias name. Syntax for Table Alias: SELECT * FROM table_name AS alias_name; Syntax for Column Alias: SELECT column_name AS alias_name FROM table_name; For the purpose of the demonstration, we will be creating demo_table in a database called “geeks“. Step 1: Creating the Database Use the below SQL statement to create a database called geeks. Query: CREATE DATABASE geeks; Step 2: Using the Database Use the below SQL statement to switch the database context to geeks. Query: USE geeks; Step 3: Table definition We have the following demo_table in our geeks database. Query: CREATE TABLE demo_table (FIRSTNAME VARCHAR(20), ENDNAME VARCHAR(20), AGE INT,GENDER VARCHAR(20)); Step 4: Insert data into the table INSERT INTO demo_table VALUES ('Romy', 'Kumari', 22, 'female'), ('Meenakshi', 'Jha', 20, 'female'), ('Shalini', 'Jha', 22, 'female'), ('Akanksha', 'Gupta', 23, 'female'), ('Rinkle', 'Arora', 23, 'female'); Step 5: See the content of the table Use the below command to see the content of the demo_table: Query: SELECT * FROM demo_table; Step 6: Perform column alias on ENDNAME column. We will use LASTNAME as alias name for ENDNAME column Query: SELECT FIRSTNAME, ENDNAME AS LASTNAME, AGE, GENDER FROM demo_table; Output: Use (LAST NAME) and (FIRST NAME) as alias name If we have a special character or spaces in the alias name, we enclose the alias name within double brackets: Query: SELECT FIRSTNAME AS "FIRST NAME", ENDNAME AS "LAST NAME", AGE, GENDER FROM demo_table; Output: Picked SQL-Server TrueGeek-2021 SQL TrueGeek SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Update Multiple Columns in Single Update Statement in SQL? SQL | DROP, TRUNCATE Composite Key in SQL SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python Types of Internet Protocols How to redirect to another page in ReactJS ? How to remove duplicate elements from JavaScript Array ? Types of Network Firewall Introduction to CUDA Programming
[ { "code": null, "e": 23877, "s": 23849, "text": "\n08 Oct, 2021" }, { "code": null, "e": 24093, "s": 23877, "text": "Alias is used to give a temporary name(only for the duration of the query) to the column or table in order to make the column name or table name more readable. It does not change the name of the column permanently. " }, { "code": null, "e": 24278, "s": 24093, "text": "Alias can be performed using the ‘AS’ keyword or without any keyword. But it is recommended to use the ‘AS’ keyword to avoid confusion between the initial column name and column alias." }, { "code": null, "e": 24389, "s": 24278, "text": "If alias name contain space or any special character, enclose alias name in single(‘ ‘) or double(” “) quotes." }, { "code": null, "e": 24521, "s": 24389, "text": "In SQL strings are also enclosed in single(‘ ‘) quotes. To avoid confusion, it is recommended to use double quotes for alias name." }, { "code": null, "e": 24545, "s": 24521, "text": "Syntax for Table Alias:" }, { "code": null, "e": 24585, "s": 24545, "text": "SELECT * FROM table_name AS alias_name;" }, { "code": null, "e": 24610, "s": 24585, "text": "Syntax for Column Alias:" }, { "code": null, "e": 24660, "s": 24610, "text": "SELECT column_name AS alias_name FROM table_name;" }, { "code": null, "e": 24759, "s": 24660, "text": "For the purpose of the demonstration, we will be creating demo_table in a database called “geeks“." }, { "code": null, "e": 24789, "s": 24759, "text": "Step 1: Creating the Database" }, { "code": null, "e": 24852, "s": 24789, "text": "Use the below SQL statement to create a database called geeks." }, { "code": null, "e": 24859, "s": 24852, "text": "Query:" }, { "code": null, "e": 24882, "s": 24859, "text": "CREATE DATABASE geeks;" }, { "code": null, "e": 24909, "s": 24882, "text": "Step 2: Using the Database" }, { "code": null, "e": 24978, "s": 24909, "text": "Use the below SQL statement to switch the database context to geeks." }, { "code": null, "e": 24985, "s": 24978, "text": "Query:" }, { "code": null, "e": 24996, "s": 24985, "text": "USE geeks;" }, { "code": null, "e": 25021, "s": 24996, "text": "Step 3: Table definition" }, { "code": null, "e": 25077, "s": 25021, "text": "We have the following demo_table in our geeks database." }, { "code": null, "e": 25084, "s": 25077, "text": "Query:" }, { "code": null, "e": 25182, "s": 25084, "text": "CREATE TABLE demo_table\n(FIRSTNAME VARCHAR(20),\nENDNAME VARCHAR(20),\nAGE INT,GENDER VARCHAR(20));" }, { "code": null, "e": 25217, "s": 25182, "text": "Step 4: Insert data into the table" }, { "code": null, "e": 25423, "s": 25217, "text": "INSERT INTO demo_table VALUES\n('Romy', 'Kumari', 22, 'female'),\n('Meenakshi', 'Jha', 20, 'female'),\n('Shalini', 'Jha', 22, 'female'),\n('Akanksha', 'Gupta', 23, 'female'),\n('Rinkle', 'Arora', 23, 'female');" }, { "code": null, "e": 25460, "s": 25423, "text": "Step 5: See the content of the table" }, { "code": null, "e": 25520, "s": 25460, "text": "Use the below command to see the content of the demo_table:" }, { "code": null, "e": 25527, "s": 25520, "text": "Query:" }, { "code": null, "e": 25553, "s": 25527, "text": "SELECT * FROM demo_table;" }, { "code": null, "e": 25601, "s": 25553, "text": "Step 6: Perform column alias on ENDNAME column." }, { "code": null, "e": 25656, "s": 25601, "text": "We will use LASTNAME as alias name for ENDNAME column " }, { "code": null, "e": 25663, "s": 25656, "text": "Query:" }, { "code": null, "e": 25731, "s": 25663, "text": "SELECT FIRSTNAME, ENDNAME AS LASTNAME, AGE, GENDER FROM demo_table;" }, { "code": null, "e": 25739, "s": 25731, "text": "Output:" }, { "code": null, "e": 25787, "s": 25739, "text": "Use (LAST NAME) and (FIRST NAME) as alias name " }, { "code": null, "e": 25897, "s": 25787, "text": "If we have a special character or spaces in the alias name, we enclose the alias name within double brackets:" }, { "code": null, "e": 25904, "s": 25897, "text": "Query:" }, { "code": null, "e": 25991, "s": 25904, "text": "SELECT FIRSTNAME AS \"FIRST NAME\", ENDNAME AS \"LAST NAME\", AGE, GENDER FROM demo_table;" }, { "code": null, "e": 25999, "s": 25991, "text": "Output:" }, { "code": null, "e": 26006, "s": 25999, "text": "Picked" }, { "code": null, "e": 26017, "s": 26006, "text": "SQL-Server" }, { "code": null, "e": 26031, "s": 26017, "text": "TrueGeek-2021" }, { "code": null, "e": 26035, "s": 26031, "text": "SQL" }, { "code": null, "e": 26044, "s": 26035, "text": "TrueGeek" }, { "code": null, "e": 26048, "s": 26044, "text": "SQL" }, { "code": null, "e": 26146, "s": 26048, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26155, "s": 26146, "text": "Comments" }, { "code": null, "e": 26168, "s": 26155, "text": "Old Comments" }, { "code": null, "e": 26234, "s": 26168, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 26255, "s": 26234, "text": "SQL | DROP, TRUNCATE" }, { "code": null, "e": 26276, "s": 26255, "text": "Composite Key in SQL" }, { "code": null, "e": 26354, "s": 26276, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 26371, "s": 26354, "text": "SQL using Python" }, { "code": null, "e": 26399, "s": 26371, "text": "Types of Internet Protocols" }, { "code": null, "e": 26444, "s": 26399, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 26501, "s": 26444, "text": "How to remove duplicate elements from JavaScript Array ?" }, { "code": null, "e": 26527, "s": 26501, "text": "Types of Network Firewall" } ]
JPA - ORM Components
Most contemporary applications use relational database to store data. Recently, many vendors switched to object database to reduce their burden on data maintenance. It means object database or object relational technologies are taking care of storing, retrieving, updating, and maintenance. The core part of this object relational technologies are mapping orm.xml file. As xml does not require compilation, we can easily make changes to multiple data sources with less administration. Object Relational Mapping (ORM) briefly tells you about what is ORM and how it works. ORM is a programming ability to covert data from object type to relational type and vice versa. The main feature of ORM is mapping or binding an object to its data in the database. While mapping we have to consider the data, type of data and its relations with its self-entity or entity in any other table. Idiomatic persistence : It enables you to write the persistence classes using object oriented classes. Idiomatic persistence : It enables you to write the persistence classes using object oriented classes. High Performance : It has many fetching techniques and hopeful locking techniques. High Performance : It has many fetching techniques and hopeful locking techniques. Reliable : It is highly stable and eminent. Used by many industrial programmers. Reliable : It is highly stable and eminent. Used by many industrial programmers. Here follow the ORM architecture. The above architecture explains how object data is stored into relational database in three phases. The first phase, named as the Object data phase contains POJO classes, service interfaces and classes. It is the main business component layer, which has business logic operations and attributes. For example let us take an employee database as schema- Employee POJO class contain attributes such as ID, name, salary, and designation. And methods like setter and getter methods of those attributes. Employee POJO class contain attributes such as ID, name, salary, and designation. And methods like setter and getter methods of those attributes. Employee DAO/Service classes contains service methods such as create employee, find employee, and delete employee. Employee DAO/Service classes contains service methods such as create employee, find employee, and delete employee. The second phase named as mapping or persistence phase which contains JPA provider, mapping file (ORM.xml), JPA Loader, and Object Grid. JPA Provider : The vendor product which contains JPA flavor (javax.persistence). For example Eclipselink, Toplink, Hibernate, etc. JPA Provider : The vendor product which contains JPA flavor (javax.persistence). For example Eclipselink, Toplink, Hibernate, etc. Mapping file : The mapping file (ORM.xml) contains mapping configuration between the data in a POJO class and data in a relational database. Mapping file : The mapping file (ORM.xml) contains mapping configuration between the data in a POJO class and data in a relational database. JPA Loader : The JPA loader works like cache memory, which can load the relational grid data. It works like a copy of database to interact with service classes for POJO data (Attributes of POJO class). JPA Loader : The JPA loader works like cache memory, which can load the relational grid data. It works like a copy of database to interact with service classes for POJO data (Attributes of POJO class). Object Grid : The Object grid is a temporary location which can store the copy of relational data, i.e. like a cache memory. All queries against the database is first effected on the data in the object grid. Only after it is committed, it effects the main database. Object Grid : The Object grid is a temporary location which can store the copy of relational data, i.e. like a cache memory. All queries against the database is first effected on the data in the object grid. Only after it is committed, it effects the main database. The third phase is the Relational data phase. It contains the relational data which is logically connected to the business component. As discussed above, only when the business component commit the data, it is stored into the database physically. Until then the modified data is stored in a cache memory as a grid format. Same is the process for obtaining data. The mechanism of the programmatic interaction of above three phases is called as object relational mapping. The mapping.xml file is to instruct the JPA vendor for mapping the Entity classes with database tables. Let us take an example of Employee entity which contains four attributes. The POJO class of Employee entity named Employee.java is as follows: public class Employee { private int eid; private String ename; private double salary; private String deg; public Employee(int eid, String ename, double salary, String deg) { super( ); this.eid = eid; this.ename = ename; this.salary = salary; this.deg = deg; } public Employee( ) { super(); } public int getEid( ) { return eid; } public void setEid(int eid) { this.eid = eid; } public String getEname( ) { return ename; } public void setEname(String ename) { this.ename = ename; } public double getSalary( ) { return salary; } public void setSalary(double salary) { this.salary = salary; } public String getDeg( ) { return deg; } public void setDeg(String deg) { this.deg = deg; } } The above code is the Employee entity POJO class. It contain four attributes eid, ename, salary, and deg. Consider these attributes are the table fields in the database and eid is the primary key of this table. Now we have to design hibernate mapping file for it. The mapping file named mapping.xml is as follows: <? xml version="1.0" encoding="UTF-8" ?> <entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_1_0.xsd" version="1.0"> <description> XML Mapping file</description> <entity class="Employee"> <table name="EMPLOYEETABLE"/> <attributes> <id name="eid"> <generated-value strategy="TABLE"/> </id> <basic name="ename"> <column name="EMP_NAME" length="100"/> </basic> <basic name="salary"> </basic> <basic name="deg"> </basic> </attributes> </entity> </entity-mappings> The above script for mapping the entity class with database table. In this file <entity-mappings> : tag defines the schema definition to allow entity tags into xml file. <entity-mappings> : tag defines the schema definition to allow entity tags into xml file. <description> : tag defines description about application. <description> : tag defines description about application. <entity> : tag defines the entity class which you want to convert into table in a database. Attribute class defines the POJO entity class name. <entity> : tag defines the entity class which you want to convert into table in a database. Attribute class defines the POJO entity class name. <table> : tag defines the table name. If you want to keep class name as table name then this tag is not necessary. <table> : tag defines the table name. If you want to keep class name as table name then this tag is not necessary. <attributes> : tag defines the attributes (fields in a table). <attributes> : tag defines the attributes (fields in a table). <id> : tag defines the primary key of the table. The <generated-value> tag defines how to assign the primary key value such as Automatic, Manual, or taken from Sequence. <id> : tag defines the primary key of the table. The <generated-value> tag defines how to assign the primary key value such as Automatic, Manual, or taken from Sequence. <basic> : tag is used for defining remaining attributes for table. <basic> : tag is used for defining remaining attributes for table. <column-name> : tag is used to define user defined table field name. <column-name> : tag is used to define user defined table field name. Generally Xml files are used to configure specific component, or mapping two different specifications of components. In our case, we have to maintain xml separately in a framework. That means while writing a mapping xml file we need to compare the POJO class attributes with entity tags in mapping.xml file. Here is the solution: In the class definition, we can write the configuration part using annotations. The annotations are used for classes, properties, and methods. Annotations starts with ‘@’ symbol. Annotations are declared before the class, property or method is declared. All annotations of JPA are defined in javax.persistence package. Here follows the list of annotations used in our examples Java class, encapsulates the instance values and behaviors into a single unit callled object. Java Bean is a temporary storage and reusable component or an object. It is a serializable class which has default constructor and getter & setter methods to initialize the instance attributes individually. Bean contains the default constructor or a file that contains serialized instance. Therefore, a bean can instantiate the bean. Bean contains the default constructor or a file that contains serialized instance. Therefore, a bean can instantiate the bean. The properties of a bean can be segregated into Boolean properties and non-Boolean properties. The properties of a bean can be segregated into Boolean properties and non-Boolean properties. Non-Boolean property contains getter and setter methods. Non-Boolean property contains getter and setter methods. Boolean property contain setter and is method. Boolean property contain setter and is method. Getter method of any property should start with small lettered ‘get’ (java method convention) and continued with a field name that starts with capital letter. E.g. the field name is ‘salary’ therefore the getter method of this field is ‘getSalary ()’. Getter method of any property should start with small lettered ‘get’ (java method convention) and continued with a field name that starts with capital letter. E.g. the field name is ‘salary’ therefore the getter method of this field is ‘getSalary ()’. Setter method of any property should start with small lettered ‘set’ (java method convention), continued with a field name that starts with capital letter and the argument value to set to field. E.g. the field name is ‘salary’ therefore the setter method of this field is ‘setSalary (double sal)’. Setter method of any property should start with small lettered ‘set’ (java method convention), continued with a field name that starts with capital letter and the argument value to set to field. E.g. the field name is ‘salary’ therefore the setter method of this field is ‘setSalary (double sal)’. For Boolean property, is method to check if it is true or false. E.g. the Boolean property ‘empty’, the is method of this field is ‘isEmpty ()’. For Boolean property, is method to check if it is true or false. E.g. the Boolean property ‘empty’, the is method of this field is ‘isEmpty ()’. Print Add Notes Bookmark this page
[ { "code": null, "e": 2224, "s": 1739, "text": "Most contemporary applications use relational database to store data. Recently, many vendors switched to object database to reduce their burden on data maintenance. It means object database or object relational technologies are taking care of storing, retrieving, updating, and maintenance. The core part of this object relational technologies are mapping orm.xml file. As xml does not require compilation, we can easily make changes to multiple data sources with less administration." }, { "code": null, "e": 2406, "s": 2224, "text": "Object Relational Mapping (ORM) briefly tells you about what is ORM and how it works. ORM is a programming ability to covert data from object type to relational type and vice versa." }, { "code": null, "e": 2617, "s": 2406, "text": "The main feature of ORM is mapping or binding an object to its data in the database. While mapping we have to consider the data, type of data and its relations with its self-entity or entity in any other table." }, { "code": null, "e": 2720, "s": 2617, "text": "Idiomatic persistence : It enables you to write the persistence classes using object oriented classes." }, { "code": null, "e": 2823, "s": 2720, "text": "Idiomatic persistence : It enables you to write the persistence classes using object oriented classes." }, { "code": null, "e": 2906, "s": 2823, "text": "High Performance : It has many fetching techniques and hopeful locking techniques." }, { "code": null, "e": 2989, "s": 2906, "text": "High Performance : It has many fetching techniques and hopeful locking techniques." }, { "code": null, "e": 3070, "s": 2989, "text": "Reliable : It is highly stable and eminent. Used by many industrial programmers." }, { "code": null, "e": 3151, "s": 3070, "text": "Reliable : It is highly stable and eminent. Used by many industrial programmers." }, { "code": null, "e": 3185, "s": 3151, "text": "Here follow the ORM architecture." }, { "code": null, "e": 3285, "s": 3185, "text": "The above architecture explains how object data is stored into relational database in three phases." }, { "code": null, "e": 3481, "s": 3285, "text": "The first phase, named as the Object data phase contains POJO classes, service interfaces and classes. It is the main business component layer, which has business logic operations and attributes." }, { "code": null, "e": 3537, "s": 3481, "text": "For example let us take an employee database as schema-" }, { "code": null, "e": 3683, "s": 3537, "text": "Employee POJO class contain attributes such as ID, name, salary, and designation. And methods like setter and getter methods of those attributes." }, { "code": null, "e": 3829, "s": 3683, "text": "Employee POJO class contain attributes such as ID, name, salary, and designation. And methods like setter and getter methods of those attributes." }, { "code": null, "e": 3944, "s": 3829, "text": "Employee DAO/Service classes contains service methods such as create employee, find employee, and delete employee." }, { "code": null, "e": 4059, "s": 3944, "text": "Employee DAO/Service classes contains service methods such as create employee, find employee, and delete employee." }, { "code": null, "e": 4196, "s": 4059, "text": "The second phase named as mapping or persistence phase which contains JPA provider, mapping file (ORM.xml), JPA Loader, and Object Grid." }, { "code": null, "e": 4327, "s": 4196, "text": "JPA Provider : The vendor product which contains JPA flavor (javax.persistence). For example Eclipselink, Toplink, Hibernate, etc." }, { "code": null, "e": 4458, "s": 4327, "text": "JPA Provider : The vendor product which contains JPA flavor (javax.persistence). For example Eclipselink, Toplink, Hibernate, etc." }, { "code": null, "e": 4599, "s": 4458, "text": "Mapping file : The mapping file (ORM.xml) contains mapping configuration between the data in a POJO class and data in a relational database." }, { "code": null, "e": 4740, "s": 4599, "text": "Mapping file : The mapping file (ORM.xml) contains mapping configuration between the data in a POJO class and data in a relational database." }, { "code": null, "e": 4942, "s": 4740, "text": "JPA Loader : The JPA loader works like cache memory, which can load the relational grid data. It works like a copy of database to interact with service classes for POJO data (Attributes of POJO class)." }, { "code": null, "e": 5144, "s": 4942, "text": "JPA Loader : The JPA loader works like cache memory, which can load the relational grid data. It works like a copy of database to interact with service classes for POJO data (Attributes of POJO class)." }, { "code": null, "e": 5412, "s": 5144, "text": "Object Grid : The Object grid is a temporary location which can store the copy of relational data, i.e. like a cache memory. All queries against the database is first effected on the data in the object grid. Only after it is committed, it effects the main database." }, { "code": null, "e": 5680, "s": 5412, "text": "Object Grid : The Object grid is a temporary location which can store the copy of relational data, i.e. like a cache memory. All queries against the database is first effected on the data in the object grid. Only after it is committed, it effects the main database." }, { "code": null, "e": 6042, "s": 5680, "text": "The third phase is the Relational data phase. It contains the relational data which is logically connected to the business component. As discussed above, only when the business component commit the data, it is stored into the database physically. Until then the modified data is stored in a cache memory as a grid format. Same is the process for obtaining data." }, { "code": null, "e": 6150, "s": 6042, "text": "The mechanism of the programmatic interaction of above three phases is called as object relational mapping." }, { "code": null, "e": 6254, "s": 6150, "text": "The mapping.xml file is to instruct the JPA vendor for mapping the Entity classes with database tables." }, { "code": null, "e": 6397, "s": 6254, "text": "Let us take an example of Employee entity which contains four attributes. The POJO class of Employee entity named Employee.java is as follows:" }, { "code": null, "e": 7261, "s": 6397, "text": "public class Employee {\n\n private int eid;\n private String ename;\n private double salary;\n private String deg;\n\n public Employee(int eid, String ename, double salary, String deg) {\n super( );\n this.eid = eid;\n this.ename = ename;\n this.salary = salary;\n this.deg = deg;\n }\n\n public Employee( ) {\n super();\n }\n\n public int getEid( ) {\n return eid;\n }\n \n public void setEid(int eid) {\n this.eid = eid;\n }\n \n public String getEname( ) {\n return ename;\n }\n \n public void setEname(String ename) {\n this.ename = ename;\n }\n\n public double getSalary( ) {\n return salary;\n }\n \n public void setSalary(double salary) {\n this.salary = salary;\n }\n\n public String getDeg( ) {\n return deg;\n }\n \n public void setDeg(String deg) {\n this.deg = deg;\n }\n}" }, { "code": null, "e": 7575, "s": 7261, "text": "The above code is the Employee entity POJO class. It contain four attributes eid, ename, salary, and deg. Consider these attributes are the table fields in the database and eid is the primary key of this table. Now we have to design hibernate mapping file for it. The mapping file named mapping.xml is as follows:" }, { "code": null, "e": 8415, "s": 7575, "text": "<? xml version=\"1.0\" encoding=\"UTF-8\" ?>\n\n<entity-mappings xmlns=\"http://java.sun.com/xml/ns/persistence/orm\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence/orm \n http://java.sun.com/xml/ns/persistence/orm_1_0.xsd\"\n version=\"1.0\">\n \n <description> XML Mapping file</description>\n \n <entity class=\"Employee\"> \n <table name=\"EMPLOYEETABLE\"/>\n <attributes>\n \n <id name=\"eid\">\n <generated-value strategy=\"TABLE\"/>\n </id>\n\n <basic name=\"ename\">\n <column name=\"EMP_NAME\" length=\"100\"/>\n </basic>\n \n <basic name=\"salary\">\n </basic>\n \n <basic name=\"deg\">\n </basic>\n \n </attributes>\n </entity>\n \n</entity-mappings>" }, { "code": null, "e": 8495, "s": 8415, "text": "The above script for mapping the entity class with database table. In this file" }, { "code": null, "e": 8585, "s": 8495, "text": "<entity-mappings> : tag defines the schema definition to allow entity tags into xml file." }, { "code": null, "e": 8675, "s": 8585, "text": "<entity-mappings> : tag defines the schema definition to allow entity tags into xml file." }, { "code": null, "e": 8734, "s": 8675, "text": "<description> : tag defines description about application." }, { "code": null, "e": 8793, "s": 8734, "text": "<description> : tag defines description about application." }, { "code": null, "e": 8937, "s": 8793, "text": "<entity> : tag defines the entity class which you want to convert into table in a database. Attribute class defines the POJO entity class name." }, { "code": null, "e": 9081, "s": 8937, "text": "<entity> : tag defines the entity class which you want to convert into table in a database. Attribute class defines the POJO entity class name." }, { "code": null, "e": 9196, "s": 9081, "text": "<table> : tag defines the table name. If you want to keep class name as table name then this tag is not necessary." }, { "code": null, "e": 9311, "s": 9196, "text": "<table> : tag defines the table name. If you want to keep class name as table name then this tag is not necessary." }, { "code": null, "e": 9374, "s": 9311, "text": "<attributes> : tag defines the attributes (fields in a table)." }, { "code": null, "e": 9437, "s": 9374, "text": "<attributes> : tag defines the attributes (fields in a table)." }, { "code": null, "e": 9608, "s": 9437, "text": "<id> : tag defines the primary key of the table. The <generated-value> tag defines how to assign the primary key value such as Automatic, Manual, or taken from Sequence.\n" }, { "code": null, "e": 9778, "s": 9608, "text": "<id> : tag defines the primary key of the table. The <generated-value> tag defines how to assign the primary key value such as Automatic, Manual, or taken from Sequence." }, { "code": null, "e": 9845, "s": 9778, "text": "<basic> : tag is used for defining remaining attributes for table." }, { "code": null, "e": 9912, "s": 9845, "text": "<basic> : tag is used for defining remaining attributes for table." }, { "code": null, "e": 9981, "s": 9912, "text": "<column-name> : tag is used to define user defined table field name." }, { "code": null, "e": 10050, "s": 9981, "text": "<column-name> : tag is used to define user defined table field name." }, { "code": null, "e": 10358, "s": 10050, "text": "Generally Xml files are used to configure specific component, or mapping two different specifications of components. In our case, we have to maintain xml separately in a framework. That means while writing a mapping xml file we need to compare the POJO class attributes with entity tags in mapping.xml file." }, { "code": null, "e": 10699, "s": 10358, "text": "Here is the solution: In the class definition, we can write the configuration part using annotations. The annotations are used for classes, properties, and methods. Annotations starts with ‘@’ symbol. Annotations are declared before the class, property or method is declared. All annotations of JPA are defined in javax.persistence package." }, { "code": null, "e": 10757, "s": 10699, "text": "Here follows the list of annotations used in our examples" }, { "code": null, "e": 11058, "s": 10757, "text": "Java class, encapsulates the instance values and behaviors into a single unit callled object. Java Bean is a temporary storage and reusable component or an object. It is a serializable class which has default constructor and getter & setter methods to initialize the instance attributes individually." }, { "code": null, "e": 11185, "s": 11058, "text": "Bean contains the default constructor or a file that contains serialized instance. Therefore, a bean can instantiate the bean." }, { "code": null, "e": 11312, "s": 11185, "text": "Bean contains the default constructor or a file that contains serialized instance. Therefore, a bean can instantiate the bean." }, { "code": null, "e": 11407, "s": 11312, "text": "The properties of a bean can be segregated into Boolean properties and non-Boolean properties." }, { "code": null, "e": 11502, "s": 11407, "text": "The properties of a bean can be segregated into Boolean properties and non-Boolean properties." }, { "code": null, "e": 11559, "s": 11502, "text": "Non-Boolean property contains getter and setter methods." }, { "code": null, "e": 11616, "s": 11559, "text": "Non-Boolean property contains getter and setter methods." }, { "code": null, "e": 11663, "s": 11616, "text": "Boolean property contain setter and is method." }, { "code": null, "e": 11710, "s": 11663, "text": "Boolean property contain setter and is method." }, { "code": null, "e": 11962, "s": 11710, "text": "Getter method of any property should start with small lettered ‘get’ (java method convention) and continued with a field name that starts with capital letter. E.g. the field name is ‘salary’ therefore the getter method of this field is ‘getSalary ()’." }, { "code": null, "e": 12214, "s": 11962, "text": "Getter method of any property should start with small lettered ‘get’ (java method convention) and continued with a field name that starts with capital letter. E.g. the field name is ‘salary’ therefore the getter method of this field is ‘getSalary ()’." }, { "code": null, "e": 12512, "s": 12214, "text": "Setter method of any property should start with small lettered ‘set’ (java method convention), continued with a field name that starts with capital letter and the argument value to set to field. E.g. the field name is ‘salary’ therefore the setter method of this field is ‘setSalary (double sal)’." }, { "code": null, "e": 12810, "s": 12512, "text": "Setter method of any property should start with small lettered ‘set’ (java method convention), continued with a field name that starts with capital letter and the argument value to set to field. E.g. the field name is ‘salary’ therefore the setter method of this field is ‘setSalary (double sal)’." }, { "code": null, "e": 12955, "s": 12810, "text": "For Boolean property, is method to check if it is true or false. E.g. the Boolean property ‘empty’, the is method of this field is ‘isEmpty ()’." }, { "code": null, "e": 13100, "s": 12955, "text": "For Boolean property, is method to check if it is true or false. E.g. the Boolean property ‘empty’, the is method of this field is ‘isEmpty ()’." }, { "code": null, "e": 13107, "s": 13100, "text": " Print" }, { "code": null, "e": 13118, "s": 13107, "text": " Add Notes" } ]
Extract domain of Email from table in SQL Server - GeeksforGeeks
07 Dec, 2020 Introduction :As a DBA, you might come across a request where you need to extract the domain of the email address, the email address that is stored in the database table. In case you want to count the most used domain names from email addresses in any given table, you can count the number of extracted domains from Email in SQL Server as shown below. SQL Queries could be used to extract the domain from the Email address.Let us created table named “email_demo” – create table (ID int, Email varchar (200)); Inserting values in the table email_demo – insert into email_demo values( (1, 'Sam@gfg.com'), (2, 'Khushi@gfg.com'), (3, 'Komal@gfg.org'), (4, 'Priya@xyz.com'), (5, 'Sam@xyz.com'), (6, 'Krish@xyz.com'), (7, 'Neha@gfg.com'), (8, 'Pam@gfg.com'), (9, 'Mohan@abc.com'), (10, 'Ankit@mno.com'), (11, 'Kumari@gfg.com'), (12, 'Hina@abc.com'), (13, 'Jaya@mno.com'), (14, 'Piyush@abc.com'), (15, 'Khushi@xyz.com'), (16, 'Mona@gfg.org'), (17, 'Roza@abc.com')); Displaying the table contents – select * from email_demo; 1. Extract Domain From Email in SQL Server :In below example we will use SUBSTRING function to select the string after the @ symbol in each of the value. SQL Extract Domain From Email – SELECT ID, SUBSTRING ([Email], CHARINDEX( '@', [Email]) + 1, LEN([Email])) AS [Domain] FROM [email_demo]; OUTPUT : Approached used : Here we assigned the Source as our Column Name ‘Email’ in the SUBSTRING function. Next, we used the CHARINDEX function to find the @ symbol, and then added 1, so that the starting point will be after the @ symbol. Then, we used the LEN function to specify the end value. 2. Count the number of extracted Domain From Email in SQL Server :Approach 1 : SQL Query to Count Number of Records for Extract Domain name From Email – SELECT RIGHT ([Email], LEN([Email]) - CHARINDEX( '@', [Email])) AS [Domain], COUNT(*) AS [Total Number of Domain] FROM [email_demo] WHERE LEN([Email ]) > 0 GROUP BY RIGHT([Email], LEN([Email]) - CHARINDEX( '@', [Email])); OUTPUT : Approach 2 : SQL Query to Count Number of Records for Extract Domain name From Email – SELECT SUBSTRING ([Email], CHARINDEX( '@', [Email] ) + 1, LEN([Email])) AS [Domain], COUNT(*) AS [Total Number of Domain] FROM [email_demo] WHERE LEN([Email]) > 1 GROUP BY SUBSTRING ([Email], CHARINDEX( '@', [Email] ) + 1, LEN([Email])); OUTPUT : SQL-Server DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Second Normal Form (2NF) Introduction of Relational Algebra in DBMS Types of Functional dependencies in DBMS What is Temporary Table in SQL? Relational Model in DBMS SQL | DDL, DQL, DML, DCL and TCL Commands How to find Nth highest salary from a table SQL | ALTER (RENAME) How to Update Multiple Columns in Single Update Statement in SQL? What is Temporary Table in SQL?
[ { "code": null, "e": 23913, "s": 23885, "text": "\n07 Dec, 2020" }, { "code": null, "e": 24265, "s": 23913, "text": "Introduction :As a DBA, you might come across a request where you need to extract the domain of the email address, the email address that is stored in the database table. In case you want to count the most used domain names from email addresses in any given table, you can count the number of extracted domains from Email in SQL Server as shown below." }, { "code": null, "e": 24378, "s": 24265, "text": "SQL Queries could be used to extract the domain from the Email address.Let us created table named “email_demo” –" }, { "code": null, "e": 24422, "s": 24378, "text": "create table (ID int, Email varchar (200));" }, { "code": null, "e": 24465, "s": 24422, "text": "Inserting values in the table email_demo –" }, { "code": null, "e": 24872, "s": 24465, "text": "insert into email_demo values(\n(1, 'Sam@gfg.com'), (2, 'Khushi@gfg.com'),\n(3, 'Komal@gfg.org'), (4, 'Priya@xyz.com'),\n(5, 'Sam@xyz.com'), (6, 'Krish@xyz.com'),\n(7, 'Neha@gfg.com'), (8, 'Pam@gfg.com'),\n(9, 'Mohan@abc.com'), (10, 'Ankit@mno.com'),\n(11, 'Kumari@gfg.com'), (12, 'Hina@abc.com'),\n(13, 'Jaya@mno.com'), (14, 'Piyush@abc.com'),\n(15, 'Khushi@xyz.com'), (16, 'Mona@gfg.org'),\n(17, 'Roza@abc.com'));" }, { "code": null, "e": 24904, "s": 24872, "text": "Displaying the table contents –" }, { "code": null, "e": 24930, "s": 24904, "text": "select * from email_demo;" }, { "code": null, "e": 25084, "s": 24930, "text": "1. Extract Domain From Email in SQL Server :In below example we will use SUBSTRING function to select the string after the @ symbol in each of the value." }, { "code": null, "e": 25116, "s": 25084, "text": "SQL Extract Domain From Email –" }, { "code": null, "e": 25222, "s": 25116, "text": "SELECT ID,\nSUBSTRING ([Email], CHARINDEX( '@', [Email]) + 1,\nLEN([Email])) AS [Domain]\nFROM [email_demo];" }, { "code": null, "e": 25231, "s": 25222, "text": "OUTPUT :" }, { "code": null, "e": 25249, "s": 25231, "text": "Approached used :" }, { "code": null, "e": 25331, "s": 25249, "text": "Here we assigned the Source as our Column Name ‘Email’ in the SUBSTRING function." }, { "code": null, "e": 25463, "s": 25331, "text": "Next, we used the CHARINDEX function to find the @ symbol, and then added 1, so that the starting point will be after the @ symbol." }, { "code": null, "e": 25520, "s": 25463, "text": "Then, we used the LEN function to specify the end value." }, { "code": null, "e": 25673, "s": 25520, "text": "2. Count the number of extracted Domain From Email in SQL Server :Approach 1 : SQL Query to Count Number of Records for Extract Domain name From Email –" }, { "code": null, "e": 25895, "s": 25673, "text": "SELECT RIGHT ([Email],\nLEN([Email]) - CHARINDEX( '@', [Email])) AS [Domain],\nCOUNT(*) AS [Total Number of Domain]\nFROM [email_demo]\nWHERE LEN([Email ]) > 0\nGROUP BY RIGHT([Email],\nLEN([Email]) - CHARINDEX( '@', [Email]));" }, { "code": null, "e": 25904, "s": 25895, "text": "OUTPUT :" }, { "code": null, "e": 25991, "s": 25904, "text": "Approach 2 : SQL Query to Count Number of Records for Extract Domain name From Email –" }, { "code": null, "e": 26229, "s": 25991, "text": "SELECT SUBSTRING ([Email],\nCHARINDEX( '@', [Email] ) + 1, LEN([Email])) AS [Domain],\nCOUNT(*) AS [Total Number of Domain]\nFROM [email_demo]\nWHERE LEN([Email]) > 1\nGROUP BY SUBSTRING ([Email], CHARINDEX( '@', [Email] ) + 1,\nLEN([Email]));" }, { "code": null, "e": 26238, "s": 26229, "text": "OUTPUT :" }, { "code": null, "e": 26249, "s": 26238, "text": "SQL-Server" }, { "code": null, "e": 26254, "s": 26249, "text": "DBMS" }, { "code": null, "e": 26258, "s": 26254, "text": "SQL" }, { "code": null, "e": 26263, "s": 26258, "text": "DBMS" }, { "code": null, "e": 26267, "s": 26263, "text": "SQL" }, { "code": null, "e": 26365, "s": 26267, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26374, "s": 26365, "text": "Comments" }, { "code": null, "e": 26387, "s": 26374, "text": "Old Comments" }, { "code": null, "e": 26412, "s": 26387, "text": "Second Normal Form (2NF)" }, { "code": null, "e": 26455, "s": 26412, "text": "Introduction of Relational Algebra in DBMS" }, { "code": null, "e": 26496, "s": 26455, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 26528, "s": 26496, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 26553, "s": 26528, "text": "Relational Model in DBMS" }, { "code": null, "e": 26595, "s": 26553, "text": "SQL | DDL, DQL, DML, DCL and TCL Commands" }, { "code": null, "e": 26639, "s": 26595, "text": "How to find Nth highest salary from a table" }, { "code": null, "e": 26660, "s": 26639, "text": "SQL | ALTER (RENAME)" }, { "code": null, "e": 26726, "s": 26660, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" } ]
Foundation - Slider Two Handles
To use two handles you need to use .slider-handle span and input field. It works for both horizontal and vertical sliders. The JavaScript will allocate ids for input fields, until you change it. If you do not change, then the handles and inputs match in the way they are in the DOM tree. The following example demonstrates how to use two handles slider in Foundation. <html> <head> <title>Slider Two Handles</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/css/foundation.min.css" integrity="sha256-1mcRjtAxlSjp6XJBgrBeeCORfBp/ppyX4tsvpQVCcpA= sha384-b5S5X654rX3Wo6z5/hnQ4GBmKuIJKMPwrJXn52ypjztlnDK2w9+9hSMBz/asy9Gw sha512-M1VveR2JGzpgWHb0elGqPTltHK3xbvu3Brgjfg4cg5ZNtyyApxw/45yHYsZ/rCVbfoO5MSZxB241wWq642jLtA==" crossorigin="anonymous"> <!-- Compressed JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.0.1/js/vendor/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/js/foundation.min.js" integrity="sha256-WUKHnLrIrx8dew//IpSEmPN/NT3DGAEmIePQYIEJLLs= sha384-53StQWuVbn6figscdDC3xV00aYCPEz3srBdV/QGSXw3f19og3Tq2wTRe0vJqRTEO sha512-X9O+2f1ty1rzBJOC8AXBnuNUdyJg0m8xMKmbt9I3Vu/UOWmSg5zG+dtnje4wAZrKtkopz/PEDClHZ1LXx5IeOw==" crossorigin="anonymous"></script> </head> <body> <div class = "slider" data-slider data-initial-start = "30" data-initial-end = "60"> <span class = "slider-handle" data-slider-handle role = "slider" tabindex = "1"></span> <span class = "slider-fill" data-slider-fill></span> <span class = "slider-handle" data-slider-handle role = "slider" tabindex = "1"></span> <input type = "hidden"> <input type = "hidden"> </div> <script> $(document).ready(function() { $(document).foundation(); }) </script> </body> </html> Let us carry out the following steps to see how the above given code works − Save the above given html code slider_two_handles.html file. Save the above given html code slider_two_handles.html file. Open this HTML file in a browser, an output is displayed as shown below. Open this HTML file in a browser, an output is displayed as shown below. 117 Lectures 5.5 hours Shakthi Swaroop 61 Lectures 1.5 hours Hans Weemaes 17 Lectures 4 hours Stephen Kahuria 8 Lectures 50 mins Zenva 28 Lectures 2 hours Sandra L 16 Lectures 2.5 hours GreyCampus Inc. Print Add Notes Bookmark this page
[ { "code": null, "e": 2526, "s": 2238, "text": "To use two handles you need to use .slider-handle span and input field. It works for both horizontal and vertical sliders. The JavaScript will allocate ids for input fields, until you change it. If you do not change, then the handles and inputs match in the way they are in the DOM tree." }, { "code": null, "e": 2606, "s": 2526, "text": "The following example demonstrates how to use two handles slider in Foundation." }, { "code": null, "e": 4139, "s": 2606, "text": "<html>\n <head>\n <title>Slider Two Handles</title>\n <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/css/foundation.min.css\" integrity=\"sha256-1mcRjtAxlSjp6XJBgrBeeCORfBp/ppyX4tsvpQVCcpA= sha384-b5S5X654rX3Wo6z5/hnQ4GBmKuIJKMPwrJXn52ypjztlnDK2w9+9hSMBz/asy9Gw sha512-M1VveR2JGzpgWHb0elGqPTltHK3xbvu3Brgjfg4cg5ZNtyyApxw/45yHYsZ/rCVbfoO5MSZxB241wWq642jLtA==\" crossorigin=\"anonymous\">\n\n <!-- Compressed JavaScript -->\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/foundation/6.0.1/js/vendor/jquery.min.js\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/js/foundation.min.js\" integrity=\"sha256-WUKHnLrIrx8dew//IpSEmPN/NT3DGAEmIePQYIEJLLs= sha384-53StQWuVbn6figscdDC3xV00aYCPEz3srBdV/QGSXw3f19og3Tq2wTRe0vJqRTEO sha512-X9O+2f1ty1rzBJOC8AXBnuNUdyJg0m8xMKmbt9I3Vu/UOWmSg5zG+dtnje4wAZrKtkopz/PEDClHZ1LXx5IeOw==\" crossorigin=\"anonymous\"></script>\n\n </head>\n\n <body>\n <div class = \"slider\" data-slider data-initial-start = \"30\" data-initial-end = \"60\">\n <span class = \"slider-handle\" data-slider-handle role = \"slider\" tabindex = \"1\"></span>\n <span class = \"slider-fill\" data-slider-fill></span>\n <span class = \"slider-handle\" data-slider-handle role = \"slider\" tabindex = \"1\"></span>\n <input type = \"hidden\">\n <input type = \"hidden\">\n </div>\n\n\n <script>\n $(document).ready(function() {\n $(document).foundation();\n })\n </script>\n </body>\n</html>" }, { "code": null, "e": 4216, "s": 4139, "text": "Let us carry out the following steps to see how the above given code works −" }, { "code": null, "e": 4277, "s": 4216, "text": "Save the above given html code slider_two_handles.html file." }, { "code": null, "e": 4338, "s": 4277, "text": "Save the above given html code slider_two_handles.html file." }, { "code": null, "e": 4411, "s": 4338, "text": "Open this HTML file in a browser, an output is displayed as shown below." }, { "code": null, "e": 4484, "s": 4411, "text": "Open this HTML file in a browser, an output is displayed as shown below." }, { "code": null, "e": 4520, "s": 4484, "text": "\n 117 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4537, "s": 4520, "text": " Shakthi Swaroop" }, { "code": null, "e": 4572, "s": 4537, "text": "\n 61 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4586, "s": 4572, "text": " Hans Weemaes" }, { "code": null, "e": 4619, "s": 4586, "text": "\n 17 Lectures \n 4 hours \n" }, { "code": null, "e": 4636, "s": 4619, "text": " Stephen Kahuria" }, { "code": null, "e": 4667, "s": 4636, "text": "\n 8 Lectures \n 50 mins\n" }, { "code": null, "e": 4674, "s": 4667, "text": " Zenva" }, { "code": null, "e": 4707, "s": 4674, "text": "\n 28 Lectures \n 2 hours \n" }, { "code": null, "e": 4717, "s": 4707, "text": " Sandra L" }, { "code": null, "e": 4752, "s": 4717, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4769, "s": 4752, "text": " GreyCampus Inc." }, { "code": null, "e": 4776, "s": 4769, "text": " Print" }, { "code": null, "e": 4787, "s": 4776, "text": " Add Notes" } ]
How to count digits of given number? JavaScript
The requirements here are simple, we are required to write a JavaScript function that takes in a number and returns the number of digits in it. For example − The number of digits in 4567 is 4 The number of digits in 423467 is 6 The number of digits in 457 is 3 Let's write the code for this function − const num = 2353454; const digits = (num, count = 0) => { if(num){ return digits(Math.floor(num / 10), ++count); }; return count; }; console.log(digits(num)); console.log(digits(123456)); console.log(digits(53453)); console.log(digits(5334534534)); The output in the console will be − 7 6 5 10
[ { "code": null, "e": 1206, "s": 1062, "text": "The requirements here are simple, we are required to write a JavaScript function that takes in a\nnumber and returns the number of digits in it." }, { "code": null, "e": 1220, "s": 1206, "text": "For example −" }, { "code": null, "e": 1323, "s": 1220, "text": "The number of digits in 4567 is 4\nThe number of digits in 423467 is 6\nThe number of digits in 457 is 3" }, { "code": null, "e": 1364, "s": 1323, "text": "Let's write the code for this function −" }, { "code": null, "e": 1628, "s": 1364, "text": "const num = 2353454;\nconst digits = (num, count = 0) => {\n if(num){\n return digits(Math.floor(num / 10), ++count);\n };\n return count;\n};\nconsole.log(digits(num));\nconsole.log(digits(123456));\nconsole.log(digits(53453));\nconsole.log(digits(5334534534));" }, { "code": null, "e": 1664, "s": 1628, "text": "The output in the console will be −" }, { "code": null, "e": 1673, "s": 1664, "text": "7\n6\n5\n10" } ]
AtomicInteger getAndAccumulate() method in Java with Examples - GeeksforGeeks
03 Jun, 2019 The Java.AtomicInteger.getAndAccumulate() method is an inbuilt method, which updates the current value of the object by applying the specified operation on the current value and value passed as a parameter. It takes an integer as its parameter and an object of IntBinaryOperator interface and applies the operation specified in the object to the values. It returns the previous value. Syntax: public final int getAndAccumulate(int y, IntBinaryOperator function) Parameters: This method accepts two parameters: y: an integer on which the function is to be applied. function: function applied to the current value of the object and the value y. Return Value: The function returns the previous value of the current object. Example to demonstrate the function. // Java program to demonstrate// working of getAndAccumulate() method import java.util.concurrent.atomic.AtomicInteger;import java.util.function.IntBinaryOperator; public class Demo { public static void main(String[] args) { new UserThread("Thread A"); new UserThread("Thread B"); }} class Shared { static AtomicInteger ai = new AtomicInteger(1);} class UserThread implements Runnable { String name; UserThread(String name) { this.name = name; new Thread(this).start(); } IntBinaryOperator ibo = (x, y) -> (x * y); int value = 5; @Override public void run() { for (int i = 0; i < 3; i++) { int ans = Shared.ai .getAndAccumulate(value, ibo); System.out.println(name + " " + ans); } }} Thread A 1 Thread A 5 Thread A 25 Thread B 125 Thread B 625 Thread B 3125 Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html Java-AtomicInteger Java-Functions Java-util-concurrent-atomic 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": 24055, "s": 24027, "text": "\n03 Jun, 2019" }, { "code": null, "e": 24440, "s": 24055, "text": "The Java.AtomicInteger.getAndAccumulate() method is an inbuilt method, which updates the current value of the object by applying the specified operation on the current value and value passed as a parameter. It takes an integer as its parameter and an object of IntBinaryOperator interface and applies the operation specified in the object to the values. It returns the previous value." }, { "code": null, "e": 24448, "s": 24440, "text": "Syntax:" }, { "code": null, "e": 24538, "s": 24448, "text": "public final int getAndAccumulate(int y, \n IntBinaryOperator function)\n" }, { "code": null, "e": 24586, "s": 24538, "text": "Parameters: This method accepts two parameters:" }, { "code": null, "e": 24640, "s": 24586, "text": "y: an integer on which the function is to be applied." }, { "code": null, "e": 24719, "s": 24640, "text": "function: function applied to the current value of the object and the value y." }, { "code": null, "e": 24796, "s": 24719, "text": "Return Value: The function returns the previous value of the current object." }, { "code": null, "e": 24833, "s": 24796, "text": "Example to demonstrate the function." }, { "code": "// Java program to demonstrate// working of getAndAccumulate() method import java.util.concurrent.atomic.AtomicInteger;import java.util.function.IntBinaryOperator; public class Demo { public static void main(String[] args) { new UserThread(\"Thread A\"); new UserThread(\"Thread B\"); }} class Shared { static AtomicInteger ai = new AtomicInteger(1);} class UserThread implements Runnable { String name; UserThread(String name) { this.name = name; new Thread(this).start(); } IntBinaryOperator ibo = (x, y) -> (x * y); int value = 5; @Override public void run() { for (int i = 0; i < 3; i++) { int ans = Shared.ai .getAndAccumulate(value, ibo); System.out.println(name + \" \" + ans); } }}", "e": 25710, "s": 24833, "text": null }, { "code": null, "e": 25785, "s": 25710, "text": "Thread A 1\nThread A 5\nThread A 25\nThread B 125\nThread B 625\nThread B 3125\n" }, { "code": null, "e": 25885, "s": 25785, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html" }, { "code": null, "e": 25904, "s": 25885, "text": "Java-AtomicInteger" }, { "code": null, "e": 25919, "s": 25904, "text": "Java-Functions" }, { "code": null, "e": 25955, "s": 25919, "text": "Java-util-concurrent-atomic package" }, { "code": null, "e": 25960, "s": 25955, "text": "Java" }, { "code": null, "e": 25965, "s": 25960, "text": "Java" }, { "code": null, "e": 26063, "s": 25965, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26072, "s": 26063, "text": "Comments" }, { "code": null, "e": 26085, "s": 26072, "text": "Old Comments" }, { "code": null, "e": 26136, "s": 26085, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 26166, "s": 26136, "text": "HashMap in Java with Examples" }, { "code": null, "e": 26197, "s": 26166, "text": "How to iterate any Map in Java" }, { "code": null, "e": 26216, "s": 26197, "text": "Interfaces in Java" }, { "code": null, "e": 26248, "s": 26216, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 26266, "s": 26248, "text": "ArrayList in Java" }, { "code": null, "e": 26286, "s": 26266, "text": "Stack Class in Java" }, { "code": null, "e": 26318, "s": 26286, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 26342, "s": 26318, "text": "Singleton Class in Java" } ]
Spring JDBC - SimpleJdbcInsert Class
The org.springframework.jdbc.core.SimpleJdbcInsert class is a multi-threaded, reusable object providing easy insert capabilities for a table. It provides meta data processing to simplify the code needed to construct a basic insert statement. The actual insert is being handled using Spring's JdbcTemplate Following is the declaration for org.springframework.jdbc.core.SimpleJdbcInsert class − public class SimpleJdbcInsert extends AbstractJdbcInsert implements SimpleJdbcInsertOperations Following example will demonstrate how to insert a query using Spring JDBC. We'll insert one record in Student Table using SimpleJdbcInsert object. jdbcInsert = new SimpleJdbcInsert(dataSource).withTableName("Student"); Map<String,Object> parameters = new HashMap<String,Object>(); parameters.put("name", name); parameters.put("age", age); jdbcInsert.execute(parameters); Where, jdbcInsert − SimpleJdbcInsert object to insert record in student table. jdbcInsert − SimpleJdbcInsert object to insert record in student table. jdbcTemplateObject − StudentJDBCTemplate object to read student object in database. jdbcTemplateObject − StudentJDBCTemplate object to read student object in database. To understand the above-mentioned concepts related to Spring JDBC, let us write an example which will insert a query. To write our example, let us have a working Eclipse IDE in place and use the following steps to create a Spring application. Following is the content of the Data Access Object interface file StudentDAO.java. package com.tutorialspoint; import java.util.List; import javax.sql.DataSource; public interface StudentDAO { /** * This is the method to be used to initialize * database resources ie. connection. */ public void setDataSource(DataSource ds); /** * This is the method to be used to create * a record in the Student table. */ public void create(String name, Integer age); /** * This is the method to be used to list down * all the records from the Student table. */ public List<Student> listStudents(); } Following is the content of the Student.java file. package com.tutorialspoint; public class Student { private Integer age; private String name; private Integer id; public void setAge(Integer age) { this.age = age; } public Integer getAge() { return age; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setId(Integer id) { this.id = id; } public Integer getId() { return id; } } Following is the content of the StudentMapper.java file. package com.tutorialspoint; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; public class StudentMapper implements RowMapper<Student> { public Student mapRow(ResultSet rs, int rowNum) throws SQLException { Student student = new Student(); student.setId(rs.getInt("id")); student.setName(rs.getString("name")); student.setAge(rs.getInt("age")); return student; } } Following is the implementation class file StudentJDBCTemplate.java for the defined DAO interface StudentDAO. package com.tutorialspoint; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; public class StudentJDBCTemplate implements StudentDao { private DataSource dataSource; private JdbcTemplate jdbcTemplateObject; SimpleJdbcInsert jdbcInsert; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; this.jdbcTemplateObject = new JdbcTemplate(dataSource); this.jdbcInsert = new SimpleJdbcInsert(dataSource).withTableName("Student"); } public void create(String name, Integer age) { Map<String,Object> parameters = new HashMap<String,Object>(); parameters.put("name", name); parameters.put("age", age); jdbcInsert.execute(parameters); System.out.println("Created Record Name = " + name + " Age = " + age); return; } public List<Student> listStudents() { String SQL = "select * from Student"; List <Student> students = jdbcTemplateObject.query(SQL, new StudentMapper()); return students; } } Following is the content of the MainApp.java file. package com.tutorialspoint; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.tutorialspoint.StudentJDBCTemplate; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate)context.getBean("studentJDBCTemplate"); System.out.println("------Records Creation--------" ); studentJDBCTemplate.create("Nuha", 2); System.out.println("------Listing Multiple Records--------" ); List<Student> students = studentJDBCTemplate.listStudents(); for (Student record : students) { System.out.print("ID : " + record.getId() ); System.out.print(", Name : " + record.getName() ); System.out.println(", Age : " + record.getAge()); } } } Following is the configuration file Beans.xml. <?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd "> <!-- Initialization for data source --> <bean id = "dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name = "driverClassName" value = "com.mysql.cj.jdbc.Driver"/> <property name = "url" value = "jdbc:mysql://localhost:3306/TEST"/> <property name = "username" value = "root"/> <property name = "password" value = "admin"/> </bean> <!-- Definition for studentJDBCTemplate bean --> <bean id = "studentJDBCTemplate" class = "com.tutorialspoint.StudentJDBCTemplate"> <property name = "dataSource" ref = "dataSource" /> </bean> </beans> Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message. ------Records Creation-------- Created Record Name = Nuha Age = 12 ------Listing Multiple Records-------- ID : 1, Name : Zara, Age : 17 ID : 3, Name : Ayan, Age : 18 ID : 4, Name : Nuha, Age : 12 Print Add Notes Bookmark this page
[ { "code": null, "e": 2701, "s": 2396, "text": "The org.springframework.jdbc.core.SimpleJdbcInsert class is a multi-threaded, reusable object providing easy insert capabilities for a table. It provides meta data processing to simplify the code needed to construct a basic insert statement. The actual insert is being handled using Spring's JdbcTemplate" }, { "code": null, "e": 2789, "s": 2701, "text": "Following is the declaration for org.springframework.jdbc.core.SimpleJdbcInsert class −" }, { "code": null, "e": 2894, "s": 2789, "text": "public class SimpleJdbcInsert\n extends AbstractJdbcInsert\n implements SimpleJdbcInsertOperations\n" }, { "code": null, "e": 3042, "s": 2894, "text": "Following example will demonstrate how to insert a query using Spring JDBC. We'll insert one record in Student Table using SimpleJdbcInsert object." }, { "code": null, "e": 3267, "s": 3042, "text": "jdbcInsert = new SimpleJdbcInsert(dataSource).withTableName(\"Student\");\nMap<String,Object> parameters = new HashMap<String,Object>();\n\nparameters.put(\"name\", name);\nparameters.put(\"age\", age);\njdbcInsert.execute(parameters);" }, { "code": null, "e": 3274, "s": 3267, "text": "Where," }, { "code": null, "e": 3346, "s": 3274, "text": "jdbcInsert − SimpleJdbcInsert object to insert record in student table." }, { "code": null, "e": 3418, "s": 3346, "text": "jdbcInsert − SimpleJdbcInsert object to insert record in student table." }, { "code": null, "e": 3502, "s": 3418, "text": "jdbcTemplateObject − StudentJDBCTemplate object to read student object in database." }, { "code": null, "e": 3586, "s": 3502, "text": "jdbcTemplateObject − StudentJDBCTemplate object to read student object in database." }, { "code": null, "e": 3829, "s": 3586, "text": "To understand the above-mentioned concepts related to Spring JDBC, let us write an example which will insert a query. To write our example, let us have a working Eclipse IDE in place and use the following steps to create a Spring application." }, { "code": null, "e": 3912, "s": 3829, "text": "Following is the content of the Data Access Object interface file StudentDAO.java." }, { "code": null, "e": 4494, "s": 3912, "text": "package com.tutorialspoint;\n\nimport java.util.List;\nimport javax.sql.DataSource;\n\npublic interface StudentDAO {\n /** \n * This is the method to be used to initialize\n * database resources ie. connection.\n */\n public void setDataSource(DataSource ds);\n \n /** \n * This is the method to be used to create\n * a record in the Student table.\n */\n public void create(String name, Integer age);\n \n /** \n * This is the method to be used to list down\n * all the records from the Student table.\n */\n public List<Student> listStudents(); \n}" }, { "code": null, "e": 4545, "s": 4494, "text": "Following is the content of the Student.java file." }, { "code": null, "e": 5017, "s": 4545, "text": "package com.tutorialspoint;\n\npublic class Student {\n private Integer age;\n private String name;\n private Integer id;\n\n public void setAge(Integer age) {\n this.age = age;\n }\n public Integer getAge() {\n return age;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getName() {\n return name;\n }\n public void setId(Integer id) {\n this.id = id;\n }\n public Integer getId() {\n return id;\n }\n}" }, { "code": null, "e": 5074, "s": 5017, "text": "Following is the content of the StudentMapper.java file." }, { "code": null, "e": 5532, "s": 5074, "text": "package com.tutorialspoint;\n\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport org.springframework.jdbc.core.RowMapper;\n\npublic class StudentMapper implements RowMapper<Student> {\n public Student mapRow(ResultSet rs, int rowNum) throws SQLException {\n Student student = new Student();\n student.setId(rs.getInt(\"id\"));\n student.setName(rs.getString(\"name\"));\n student.setAge(rs.getInt(\"age\"));\n return student;\n }\n}" }, { "code": null, "e": 5642, "s": 5532, "text": "Following is the implementation class file StudentJDBCTemplate.java for the defined DAO interface StudentDAO." }, { "code": null, "e": 6821, "s": 5642, "text": "package com.tutorialspoint;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport javax.sql.DataSource;\nimport org.springframework.jdbc.core.JdbcTemplate;\nimport org.springframework.jdbc.core.simple.SimpleJdbcInsert;\n\npublic class StudentJDBCTemplate implements StudentDao {\n private DataSource dataSource;\n private JdbcTemplate jdbcTemplateObject;\n SimpleJdbcInsert jdbcInsert;\n\n public void setDataSource(DataSource dataSource) {\n this.dataSource = dataSource;\n this.jdbcTemplateObject = new JdbcTemplate(dataSource);\n this.jdbcInsert = new SimpleJdbcInsert(dataSource).withTableName(\"Student\");\n }\n public void create(String name, Integer age) {\n Map<String,Object> parameters = new HashMap<String,Object>();\n parameters.put(\"name\", name);\n parameters.put(\"age\", age);\n \n jdbcInsert.execute(parameters);\n System.out.println(\"Created Record Name = \" + name + \" Age = \" + age);\n return;\n }\n public List<Student> listStudents() {\n String SQL = \"select * from Student\";\n List <Student> students = jdbcTemplateObject.query(SQL, new StudentMapper());\n return students;\n }\n}" }, { "code": null, "e": 6872, "s": 6821, "text": "Following is the content of the MainApp.java file." }, { "code": null, "e": 7847, "s": 6872, "text": "package com.tutorialspoint;\n\nimport java.util.List;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\nimport com.tutorialspoint.StudentJDBCTemplate;\n\npublic class MainApp {\n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate)context.getBean(\"studentJDBCTemplate\");\n \n System.out.println(\"------Records Creation--------\" );\n studentJDBCTemplate.create(\"Nuha\", 2);\n\n System.out.println(\"------Listing Multiple Records--------\" );\n List<Student> students = studentJDBCTemplate.listStudents();\n \n for (Student record : students) {\n System.out.print(\"ID : \" + record.getId() );\n System.out.print(\", Name : \" + record.getName() );\n System.out.println(\", Age : \" + record.getAge());\n }\n }\n}" }, { "code": null, "e": 7894, "s": 7847, "text": "Following is the configuration file Beans.xml." }, { "code": null, "e": 8839, "s": 7894, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<beans xmlns=\"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd \">\n\n <!-- Initialization for data source -->\n <bean id = \"dataSource\" \n class = \"org.springframework.jdbc.datasource.DriverManagerDataSource\">\n <property name = \"driverClassName\" value = \"com.mysql.cj.jdbc.Driver\"/>\n <property name = \"url\" value = \"jdbc:mysql://localhost:3306/TEST\"/>\n <property name = \"username\" value = \"root\"/>\n <property name = \"password\" value = \"admin\"/>\n </bean>\n\n <!-- Definition for studentJDBCTemplate bean -->\n <bean id = \"studentJDBCTemplate\" \n class = \"com.tutorialspoint.StudentJDBCTemplate\">\n <property name = \"dataSource\" ref = \"dataSource\" /> \n </bean>\n</beans>" }, { "code": null, "e": 9017, "s": 8839, "text": "Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message." }, { "code": null, "e": 9214, "s": 9017, "text": "------Records Creation--------\nCreated Record Name = Nuha Age = 12\n------Listing Multiple Records--------\nID : 1, Name : Zara, Age : 17\nID : 3, Name : Ayan, Age : 18\nID : 4, Name : Nuha, Age : 12\n" }, { "code": null, "e": 9221, "s": 9214, "text": " Print" }, { "code": null, "e": 9232, "s": 9221, "text": " Add Notes" } ]
Program to find number of solutions in Quadratic Equation in C++
In this problem, we are given a quadratic equation of type ax2 + bx + c, where a,b and c are constants. Our task is to create a program to find number of solutions in Quadratic Equation in C++. Problem Description − Here, we need to find the numbers of solutions for a quadratic equation that can have at max 2 solutions. Let’s take a few examples to understand the problem, Input − 3x2 + 7x + 4 Output − 2 Explanation − the two solutions of the equation are 1 and 4/3. Input − x2 - 4x + 4 Output − 1 Explanation − The solution to the equation is 2. Input − 2x2 + 2x + 2 Output − 0 Explanation: There is no solution to the equation. To find the number of solutions, we need the nature of solutions of the quadratic equation which is found using the value of discriminant (D). The roots of the equation are given by the formula, = −b ± √b. D = ( (b^2) - (4*a*c) ) So, the discriminant’s value gives the number of roots of the quadratic equation. If D = 0, the number of solutions is 1. If D = 0, the number of solutions is 1. If D > 0, the number of solutions is 2. If D > 0, the number of solutions is 2. If D < 0, the number of solutions is 0. As the value of the root of a negative number is imaginary. If D < 0, the number of solutions is 0. As the value of the root of a negative number is imaginary. Step 1 − find the value of D, D = ((b^2) - 4*a*c). Step 1 − find the value of D, D = ((b^2) - 4*a*c). Step 2 − if(D > 0), print 2 solutions Step 2 − if(D > 0), print 2 solutions Step 3 − if(D = 0), print 1 solution Step 3 − if(D = 0), print 1 solution Step 4 − if(D < 0), print 0 solution Step 4 − if(D < 0), print 0 solution #include <iostream> using namespace std; int checkSolution(int a, int b, int c) { if (((b * b) - (4 * a * c)) > 0) return 2; else if (((b * b) - (4 * a * c)) == 0) return 1; else return 0; } int main() { int a = 2, b = 2, c = 3; cout<<"The quadratic equation is "<<a<<"x^2 + "<<b<<"x + "<<c<<" has "; cout<<checkSolution(a, b, c)<<" solutions "; return 0; } The quadratic equation is 2x^2 + 2x + 3 has 0 solutions
[ { "code": null, "e": 1256, "s": 1062, "text": "In this problem, we are given a quadratic equation of type ax2 + bx + c, where a,b and c are constants. Our task is to create a program to find number of solutions in Quadratic Equation in C++." }, { "code": null, "e": 1384, "s": 1256, "text": "Problem Description − Here, we need to find the numbers of solutions for a quadratic equation that can have at max 2 solutions." }, { "code": null, "e": 1437, "s": 1384, "text": "Let’s take a few examples to understand the problem," }, { "code": null, "e": 1458, "s": 1437, "text": "Input − 3x2 + 7x + 4" }, { "code": null, "e": 1469, "s": 1458, "text": "Output − 2" }, { "code": null, "e": 1532, "s": 1469, "text": "Explanation − the two solutions of the equation are 1 and 4/3." }, { "code": null, "e": 1552, "s": 1532, "text": "Input − x2 - 4x + 4" }, { "code": null, "e": 1563, "s": 1552, "text": "Output − 1" }, { "code": null, "e": 1612, "s": 1563, "text": "Explanation − The solution to the equation is 2." }, { "code": null, "e": 1633, "s": 1612, "text": "Input − 2x2 + 2x + 2" }, { "code": null, "e": 1644, "s": 1633, "text": "Output − 0" }, { "code": null, "e": 1695, "s": 1644, "text": "Explanation: There is no solution to the equation." }, { "code": null, "e": 1838, "s": 1695, "text": "To find the number of solutions, we need the nature of solutions of the quadratic equation which is found using the value of discriminant (D)." }, { "code": null, "e": 1890, "s": 1838, "text": "The roots of the equation are given by the formula," }, { "code": null, "e": 1925, "s": 1890, "text": "= −b ± √b.\nD = ( (b^2) - (4*a*c) )" }, { "code": null, "e": 2007, "s": 1925, "text": "So, the discriminant’s value gives the number of roots of the quadratic equation." }, { "code": null, "e": 2047, "s": 2007, "text": "If D = 0, the number of solutions is 1." }, { "code": null, "e": 2087, "s": 2047, "text": "If D = 0, the number of solutions is 1." }, { "code": null, "e": 2127, "s": 2087, "text": "If D > 0, the number of solutions is 2." }, { "code": null, "e": 2167, "s": 2127, "text": "If D > 0, the number of solutions is 2." }, { "code": null, "e": 2267, "s": 2167, "text": "If D < 0, the number of solutions is 0. As the value of the root of a negative number is imaginary." }, { "code": null, "e": 2367, "s": 2267, "text": "If D < 0, the number of solutions is 0. As the value of the root of a negative number is imaginary." }, { "code": null, "e": 2418, "s": 2367, "text": "Step 1 − find the value of D, D = ((b^2) - 4*a*c)." }, { "code": null, "e": 2469, "s": 2418, "text": "Step 1 − find the value of D, D = ((b^2) - 4*a*c)." }, { "code": null, "e": 2507, "s": 2469, "text": "Step 2 − if(D > 0), print 2 solutions" }, { "code": null, "e": 2545, "s": 2507, "text": "Step 2 − if(D > 0), print 2 solutions" }, { "code": null, "e": 2582, "s": 2545, "text": "Step 3 − if(D = 0), print 1 solution" }, { "code": null, "e": 2619, "s": 2582, "text": "Step 3 − if(D = 0), print 1 solution" }, { "code": null, "e": 2656, "s": 2619, "text": "Step 4 − if(D < 0), print 0 solution" }, { "code": null, "e": 2693, "s": 2656, "text": "Step 4 − if(D < 0), print 0 solution" }, { "code": null, "e": 3093, "s": 2693, "text": "#include <iostream>\nusing namespace std;\nint checkSolution(int a, int b, int c) {\n if (((b * b) - (4 * a * c)) > 0)\n return 2;\n else if (((b * b) - (4 * a * c)) == 0)\n return 1;\n else\n return 0;\n}\nint main() {\n int a = 2, b = 2, c = 3;\n cout<<\"The quadratic equation is \"<<a<<\"x^2 + \"<<b<<\"x +\n \"<<c<<\" has \";\n cout<<checkSolution(a, b, c)<<\" solutions \";\n return 0;\n}" }, { "code": null, "e": 3149, "s": 3093, "text": "The quadratic equation is 2x^2 + 2x + 3 has 0 solutions" } ]
Next.js - Pages
In Next.js, we can create pages and navigate between them using file system routing feature. We'll use Link component to have a client side navigation between pages. In Next.js, a page is a React Component and are exported from pages directory. Each page is associated with a route based on its file name. For example pages/index.js is linked with '/' route. pages/index.js is linked with '/' route. pages/posts/first.js is linked with '/posts/first' route and so on. pages/posts/first.js is linked with '/posts/first' route and so on. Let's update the nextjs project created in Environment Setup chapter. Create post directory and first.js within it with following contents. export default function FirstPost() { return <h1>My First Post</h1> } Add Link Support to go back to Home page. Update first.js as follows − import Link from 'next/link' export default function FirstPost() { return ( <> <h1>My First Post</h1> <h2> <Link href="/"> <a>Home</a> </Link> </h2> </> ) } Add Link Support to home page to navigate to first page. Update index.js as follows − import Link from 'next/link' function HomePage() { return ( <> <div>Welcome to Next.js!</div> <Link href="/posts/first"><a>First Post</a></Link> </> ) } export default HomePage Run the following command to start the server −. npm run dev > nextjs@1.0.0 dev \Node\nextjs > next ready - started server on http://localhost:3000 event - compiled successfully event - build page: / wait - compiling... event - compiled successfully event - build page: /next/dist/pages/_error wait - compiling... event - compiled successfully Open localhost:3000 in a browser and you will see the following output. Click on First Link and you will see the following output. Print Add Notes Bookmark this page
[ { "code": null, "e": 2273, "s": 2107, "text": "In Next.js, we can create pages and navigate between them using file system routing feature. We'll use Link component to have a client side navigation between pages." }, { "code": null, "e": 2425, "s": 2273, "text": "In Next.js, a page is a React Component and are exported from pages directory. Each page is associated with a route based on its file name. For example" }, { "code": null, "e": 2466, "s": 2425, "text": "pages/index.js is linked with '/' route." }, { "code": null, "e": 2507, "s": 2466, "text": "pages/index.js is linked with '/' route." }, { "code": null, "e": 2575, "s": 2507, "text": "pages/posts/first.js is linked with '/posts/first' route and so on." }, { "code": null, "e": 2643, "s": 2575, "text": "pages/posts/first.js is linked with '/posts/first' route and so on." }, { "code": null, "e": 2713, "s": 2643, "text": "Let's update the nextjs project created in Environment Setup chapter." }, { "code": null, "e": 2783, "s": 2713, "text": "Create post directory and first.js within it with following contents." }, { "code": null, "e": 2856, "s": 2783, "text": "export default function FirstPost() {\n return <h1>My First Post</h1>\n}" }, { "code": null, "e": 2927, "s": 2856, "text": "Add Link Support to go back to Home page. Update first.js as follows −" }, { "code": null, "e": 3172, "s": 2927, "text": "import Link from 'next/link'\n\nexport default function FirstPost() {\n return (\n <>\n <h1>My First Post</h1>\n <h2>\n <Link href=\"/\">\n <a>Home</a>\n </Link>\n </h2>\n </>\t \n )\n}" }, { "code": null, "e": 3258, "s": 3172, "text": "Add Link Support to home page to navigate to first page. Update index.js as follows −" }, { "code": null, "e": 3478, "s": 3258, "text": "import Link from 'next/link'\n\nfunction HomePage() {\n return (\n <>\n <div>Welcome to Next.js!</div>\n <Link href=\"/posts/first\"><a>First Post</a></Link>\n </>\t \n )\n}\n\nexport default HomePage" }, { "code": null, "e": 3527, "s": 3478, "text": "Run the following command to start the server −." }, { "code": null, "e": 3826, "s": 3527, "text": "npm run dev\n> nextjs@1.0.0 dev \\Node\\nextjs\n> next\n\nready - started server on http://localhost:3000\nevent - compiled successfully\nevent - build page: /\nwait - compiling...\nevent - compiled successfully\nevent - build page: /next/dist/pages/_error\nwait - compiling...\nevent - compiled successfully\n" }, { "code": null, "e": 3898, "s": 3826, "text": "Open localhost:3000 in a browser and you will see the following output." }, { "code": null, "e": 3957, "s": 3898, "text": "Click on First Link and you will see the following output." }, { "code": null, "e": 3964, "s": 3957, "text": " Print" }, { "code": null, "e": 3975, "s": 3964, "text": " Add Notes" } ]
Extract Leaves of a Binary Tree in a Doubly Linked List - GeeksforGeeks
18 Jan, 2022 Given a Binary Tree, extract all leaves of it in a Doubly Linked List (DLL). Note that the DLL need to be created in-place. Assume that the node structure of DLL and Binary Tree is same, only the meaning of left and right pointers are different. In DLL, left means previous pointer, and right means next pointer. Let the following be input binary tree 1 / \ 2 3 / \ \ 4 5 6 / \ / \ 7 8 9 10 Output: Doubly Linked List 785910 Modified Tree: 1 / \ 2 3 / \ 4 6 We need to traverse all leaves and connect them by changing their left and right pointers. We also need to remove them from the Binary Tree by changing left or right pointers in parent nodes. There can be many ways to solve this. In the following implementation, we add leaves at the beginning of the current linked list and update the head of the list using the pointer to head pointer. Since we insert at the beginning, we need to process leaves in reverse order. For reverse order, we first traverse the right subtree, then the left subtree. We use return values to update left or right pointers in parent nodes. C++ C Java Python3 C# Javascript // C++ program to extract leaves of// a Binary Tree in a Doubly Linked List#include <bits/stdc++.h>using namespace std; // Structure for tree and linked listclass Node{ public: int data; Node *left, *right;}; // Main function which extracts all// leaves from given Binary Tree.// The function returns new root of// Binary Tree (Note that root may change// if Binary Tree has only one node).// The function also sets *head_ref as// head of doubly linked list. left pointer// of tree is used as prev in DLL// and right pointer is used as nextNode* extractLeafList(Node *root, Node **head_ref){// Base casesif (root == NULL) return NULL; if (root->left == NULL && root->right == NULL){ // This node is going to be added // to doubly linked list of leaves, // set right pointer of this node // as previous head of DLL. We // don't need to set left pointer // as left is already NULL root->right = *head_ref; // Change left pointer of previous head if (*head_ref != NULL) (*head_ref)->left = root; // Change head of linked list *head_ref = root; return NULL; // Return new root} // Recur for right and left subtreesroot->right = extractLeafList(root->right, head_ref);root->left = extractLeafList(root->left, head_ref); return root;} // Utility function for allocating node for Binary Tree.Node* newNode(int data){ Node* node = new Node(); node->data = data; node->left = node->right = NULL; return node;} // Utility function for printing tree in In-Order.void print(Node *root){ if (root != NULL) { print(root->left); cout<<root->data<<" "; print(root->right); }} // Utility function for printing double linked list.void printList(Node *head){ while (head) { cout<<head->data<<" "; head = head->right; }} // Driver codeint main(){ Node *head = NULL; Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(6); root->left->left->left = newNode(7); root->left->left->right = newNode(8); root->right->right->left = newNode(9); root->right->right->right = newNode(10); cout << "Inorder Traversal of given Tree is:\n"; print(root); root = extractLeafList(root, &head); cout << "\nExtracted Double Linked list is:\n"; printList(head); cout << "\nInorder traversal of modified tree is:\n"; print(root); return 0;} // This code is contributed by rathbhupendra // C program to extract leaves of a Binary Tree in a Doubly Linked List#include <stdio.h>#include <stdlib.h> // Structure for tree and linked liststruct Node{ int data; struct Node *left, *right;}; // Main function which extracts all leaves from given Binary Tree.// The function returns new root of Binary Tree (Note that root may change// if Binary Tree has only one node). The function also sets *head_ref as// head of doubly linked list. left pointer of tree is used as prev in DLL// and right pointer is used as nextstruct Node* extractLeafList(struct Node *root, struct Node **head_ref){ // Base cases if (root == NULL) return NULL; if (root->left == NULL && root->right == NULL) { // This node is going to be added to doubly linked list // of leaves, set right pointer of this node as previous // head of DLL. We don't need to set left pointer as left // is already NULL root->right = *head_ref; // Change left pointer of previous head if (*head_ref != NULL) (*head_ref)->left = root; // Change head of linked list *head_ref = root; return NULL; // Return new root } // Recur for right and left subtrees root->right = extractLeafList(root->right, head_ref); root->left = extractLeafList(root->left, head_ref); return root;} // Utility function for allocating node for Binary Tree.struct Node* newNode(int data){ struct Node* node = (struct Node*)malloc(sizeof(struct Node)); node->data = data; node->left = node->right = NULL; return node;} // Utility function for printing tree in In-Order.void print(struct Node *root){ if (root != NULL) { print(root->left); printf("%d ",root->data); print(root->right); }} // Utility function for printing double linked list.void printList(struct Node *head){ while (head) { printf("%d ", head->data); head = head->right; }} // Driver program to test above functionint main(){ struct Node *head = NULL; struct Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(6); root->left->left->left = newNode(7); root->left->left->right = newNode(8); root->right->right->left = newNode(9); root->right->right->right = newNode(10); printf("Inorder Traversal of given Tree is:\n"); print(root); root = extractLeafList(root, &head); printf("\nExtracted Double Linked list is:\n"); printList(head); printf("\nInorder traversal of modified tree is:\n"); print(root); return 0;} // Java program to extract leaf nodes from binary tree// using double linked list // A binary tree nodeclass Node{ int data; Node left, right; Node(int item) { data = item; right = left = null; }} public class BinaryTree{ Node root; Node head; // will point to head of DLL Node prev; // temporary pointer // The main function that links the list list to be traversed public Node extractLeafList(Node root) { if (root == null) return null; if (root.left == null && root.right == null) { if (head == null) { head = root; prev = root; } else { prev.right = root; root.left = prev; prev = root; } return null; } root.left = extractLeafList(root.left); root.right = extractLeafList(root.right); return root; } //Prints the DLL in both forward and reverse directions. public void printDLL(Node head) { Node last = null; while (head != null) { System.out.print(head.data + " "); last = head; head = head.right; } } void inorder(Node node) { if (node == null) return; inorder(node.left); System.out.print(node.data + " "); inorder(node.right); } // Driver program to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.right = new Node(6); tree.root.left.left.left = new Node(7); tree.root.left.left.right = new Node(8); tree.root.right.right.left = new Node(9); tree.root.right.right.right = new Node(10); System.out.println("Inorder traversal of given tree is : "); tree.inorder(tree.root); tree.extractLeafList(tree.root); System.out.println(""); System.out.println("Extracted double link list is : "); tree.printDLL(tree.head); System.out.println(""); System.out.println("Inorder traversal of modified tree is : "); tree.inorder(tree.root); }} // This code has been contributed by Mayank Jaiswal(mayank_24) # Python program to extract leaf nodes from binary tree# using double linked list # A binary tree nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Main function which extracts all leaves from given Binary Tree.# The function returns new root of Binary Tree (Note that# root may change if Binary Tree has only one node).# The function also sets *head_ref as head of doubly linked list.# left pointer of tree is used as prev in DLL# and right pointer is used as nextdef extractLeafList(root): # Base Case if root is None: return None if root.left is None and root.right is None: # This node is going to be added to doubly linked # list of leaves, set pointer of this node as # previous head of DLL. We don't need to set left # pointer as left is already None root.right = extractLeafList.head # Change the left pointer of previous head if extractLeafList.head is not None: extractLeafList.head.left = root # Change head of linked list extractLeafList.head = root return None # Return new root # Recur for right and left subtrees root.right = extractLeafList(root.right) root.left = extractLeafList(root.left) return root # Utility function for printing tree in InOrderdef printInorder(root): if root is not None: printInorder(root.left) print (root.data,end=" ") printInorder(root.right) def printList(head): while(head): if head.data is not None: print (head.data,end=" ") head = head.right # Driver program to test above functionextractLeafList.head = Node(None)root = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.right = Node(6)root.left.left.left = Node(7)root.left.left.right = Node(8)root.right.right.left = Node(9)root.right.right.right = Node(10) print ("Inorder traversal of given tree is:")printInorder(root) root = extractLeafList(root) print ("\nExtract Double Linked List is:")printList(extractLeafList.head) print ("\nInorder traversal of modified tree is:")printInorder(root) // C# program to extract leaf// nodes from binary tree// using double linked listusing System; // A binary tree nodepublic class Node{ public int data; public Node left, right; public Node(int item) { data = item; right = left = null; }} public class BinaryTree{ Node root; Node head; // will point to head of DLL Node prev; // temporary pointer // The main function that links // the list list to be traversed public Node extractLeafList(Node root) { if (root == null) return null; if (root.left == null && root.right == null) { if (head == null) { head = root; prev = root; } else { prev.right = root; root.left = prev; prev = root; } return null; } root.left = extractLeafList(root.left); root.right = extractLeafList(root.right); return root; } // Prints the DLL in both forward // and reverse directions. public void printDLL(Node head) { Node last = null; while (head != null) { Console.Write(head.data + " "); last = head; head = head.right; } } void inorder(Node node) { if (node == null) return; inorder(node.left); Console.Write(node.data + " "); inorder(node.right); } // Driver code public static void Main(String []args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.right = new Node(6); tree.root.left.left.left = new Node(7); tree.root.left.left.right = new Node(8); tree.root.right.right.left = new Node(9); tree.root.right.right.right = new Node(10); Console.WriteLine("Inorder traversal of given tree is : "); tree.inorder(tree.root); tree.extractLeafList(tree.root); Console.WriteLine(""); Console.WriteLine("Extracted double link list is : "); tree.printDLL(tree.head); Console.WriteLine(""); Console.WriteLine("Inorder traversal of modified tree is : "); tree.inorder(tree.root); }} // This code has been contributed by 29AjayKumar <script> // javascript program to extract leaf nodes from binary tree // using var linked list // A binary tree node class Node { constructor(val) { this.data = val; this.left = null; this.right = null; } } var root; var head; // will point to head of DLL var prev; // temporary pointer // The main function that links the list list to be traversed function extractLeafList(root) { if (root == null) return null; if (root.left == null && root.right == null) { if (head == null) { head = root; prev = root; } else { prev.right = root; root.left = prev; prev = root; } return null; } root.left = extractLeafList(root.left); root.right = extractLeafList(root.right); return root; } // Prints the DLL in both forward and reverse directions. function printDLL(head) { var last = null; while (head != null) { document.write(head.data + " "); last = head; head = head.right; } } function inorder(node) { if (node == null) return; inorder(node.left); document.write(node.data + " "); inorder(node.right); } // Driver program to test above functions root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.right = new Node(6); root.left.left.left = new Node(7); root.left.left.right = new Node(8); root.right.right.left = new Node(9); root.right.right.right = new Node(10); document.write("Inorder traversal of given tree is :<br/> "); inorder(root); extractLeafList(root); document.write("<br/>"); document.write("Extracted var link list is :<br/> "); printDLL(head); document.write("<br/>"); document.write("Inorder traversal of modified tree is : <br/>"); inorder(root); // This code contributed by umadevi9616</script> Inorder Traversal of given Tree is: 7 4 8 2 5 1 3 9 6 10 Extracted Double Linked list is: 7 8 5 9 10 Inorder traversal of modified tree is: 4 2 1 3 6 Time Complexity: O(n), the solution does a single traversal of a given Binary Tree. YouTubeGeeksforGeeks502K subscribersExtract Leaves of a Binary Tree in a Doubly Linked List | 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 / 4:53•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=JH9Jea12MEI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Chandra Prakash. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 29AjayKumar rathbhupendra Akanksha_Rai umadevi9616 simmytarika5 khushboogoyal499 sagar0719kumar amartyaghoshgfg Amazon doubly linked list Linkedin Linked List Tree Amazon Linkedin Linked List Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Reverse a linked list Stack Data Structure (Introduction and Program) Linked List | Set 3 (Deleting a node) Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Inorder Tree Traversal without Recursion
[ { "code": null, "e": 35848, "s": 35820, "text": "\n18 Jan, 2022" }, { "code": null, "e": 36163, "s": 35848, "text": "Given a Binary Tree, extract all leaves of it in a Doubly Linked List (DLL). Note that the DLL need to be created in-place. Assume that the node structure of DLL and Binary Tree is same, only the meaning of left and right pointers are different. In DLL, left means previous pointer, and right means next pointer. " }, { "code": null, "e": 36427, "s": 36163, "text": "Let the following be input binary tree\n 1\n / \\\n 2 3\n / \\ \\\n 4 5 6\n / \\ / \\\n7 8 9 10\n\n\nOutput:\nDoubly Linked List\n785910\n\nModified Tree:\n 1\n / \\\n 2 3\n / \\\n 4 6 " }, { "code": null, "e": 37045, "s": 36427, "text": "We need to traverse all leaves and connect them by changing their left and right pointers. We also need to remove them from the Binary Tree by changing left or right pointers in parent nodes. There can be many ways to solve this. In the following implementation, we add leaves at the beginning of the current linked list and update the head of the list using the pointer to head pointer. Since we insert at the beginning, we need to process leaves in reverse order. For reverse order, we first traverse the right subtree, then the left subtree. We use return values to update left or right pointers in parent nodes. " }, { "code": null, "e": 37049, "s": 37045, "text": "C++" }, { "code": null, "e": 37051, "s": 37049, "text": "C" }, { "code": null, "e": 37056, "s": 37051, "text": "Java" }, { "code": null, "e": 37064, "s": 37056, "text": "Python3" }, { "code": null, "e": 37067, "s": 37064, "text": "C#" }, { "code": null, "e": 37078, "s": 37067, "text": "Javascript" }, { "code": "// C++ program to extract leaves of// a Binary Tree in a Doubly Linked List#include <bits/stdc++.h>using namespace std; // Structure for tree and linked listclass Node{ public: int data; Node *left, *right;}; // Main function which extracts all// leaves from given Binary Tree.// The function returns new root of// Binary Tree (Note that root may change// if Binary Tree has only one node).// The function also sets *head_ref as// head of doubly linked list. left pointer// of tree is used as prev in DLL// and right pointer is used as nextNode* extractLeafList(Node *root, Node **head_ref){// Base casesif (root == NULL) return NULL; if (root->left == NULL && root->right == NULL){ // This node is going to be added // to doubly linked list of leaves, // set right pointer of this node // as previous head of DLL. We // don't need to set left pointer // as left is already NULL root->right = *head_ref; // Change left pointer of previous head if (*head_ref != NULL) (*head_ref)->left = root; // Change head of linked list *head_ref = root; return NULL; // Return new root} // Recur for right and left subtreesroot->right = extractLeafList(root->right, head_ref);root->left = extractLeafList(root->left, head_ref); return root;} // Utility function for allocating node for Binary Tree.Node* newNode(int data){ Node* node = new Node(); node->data = data; node->left = node->right = NULL; return node;} // Utility function for printing tree in In-Order.void print(Node *root){ if (root != NULL) { print(root->left); cout<<root->data<<\" \"; print(root->right); }} // Utility function for printing double linked list.void printList(Node *head){ while (head) { cout<<head->data<<\" \"; head = head->right; }} // Driver codeint main(){ Node *head = NULL; Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(6); root->left->left->left = newNode(7); root->left->left->right = newNode(8); root->right->right->left = newNode(9); root->right->right->right = newNode(10); cout << \"Inorder Traversal of given Tree is:\\n\"; print(root); root = extractLeafList(root, &head); cout << \"\\nExtracted Double Linked list is:\\n\"; printList(head); cout << \"\\nInorder traversal of modified tree is:\\n\"; print(root); return 0;} // This code is contributed by rathbhupendra", "e": 39613, "s": 37078, "text": null }, { "code": "// C program to extract leaves of a Binary Tree in a Doubly Linked List#include <stdio.h>#include <stdlib.h> // Structure for tree and linked liststruct Node{ int data; struct Node *left, *right;}; // Main function which extracts all leaves from given Binary Tree.// The function returns new root of Binary Tree (Note that root may change// if Binary Tree has only one node). The function also sets *head_ref as// head of doubly linked list. left pointer of tree is used as prev in DLL// and right pointer is used as nextstruct Node* extractLeafList(struct Node *root, struct Node **head_ref){ // Base cases if (root == NULL) return NULL; if (root->left == NULL && root->right == NULL) { // This node is going to be added to doubly linked list // of leaves, set right pointer of this node as previous // head of DLL. We don't need to set left pointer as left // is already NULL root->right = *head_ref; // Change left pointer of previous head if (*head_ref != NULL) (*head_ref)->left = root; // Change head of linked list *head_ref = root; return NULL; // Return new root } // Recur for right and left subtrees root->right = extractLeafList(root->right, head_ref); root->left = extractLeafList(root->left, head_ref); return root;} // Utility function for allocating node for Binary Tree.struct Node* newNode(int data){ struct Node* node = (struct Node*)malloc(sizeof(struct Node)); node->data = data; node->left = node->right = NULL; return node;} // Utility function for printing tree in In-Order.void print(struct Node *root){ if (root != NULL) { print(root->left); printf(\"%d \",root->data); print(root->right); }} // Utility function for printing double linked list.void printList(struct Node *head){ while (head) { printf(\"%d \", head->data); head = head->right; }} // Driver program to test above functionint main(){ struct Node *head = NULL; struct Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(6); root->left->left->left = newNode(7); root->left->left->right = newNode(8); root->right->right->left = newNode(9); root->right->right->right = newNode(10); printf(\"Inorder Traversal of given Tree is:\\n\"); print(root); root = extractLeafList(root, &head); printf(\"\\nExtracted Double Linked list is:\\n\"); printList(head); printf(\"\\nInorder traversal of modified tree is:\\n\"); print(root); return 0;}", "e": 42284, "s": 39613, "text": null }, { "code": "// Java program to extract leaf nodes from binary tree// using double linked list // A binary tree nodeclass Node{ int data; Node left, right; Node(int item) { data = item; right = left = null; }} public class BinaryTree{ Node root; Node head; // will point to head of DLL Node prev; // temporary pointer // The main function that links the list list to be traversed public Node extractLeafList(Node root) { if (root == null) return null; if (root.left == null && root.right == null) { if (head == null) { head = root; prev = root; } else { prev.right = root; root.left = prev; prev = root; } return null; } root.left = extractLeafList(root.left); root.right = extractLeafList(root.right); return root; } //Prints the DLL in both forward and reverse directions. public void printDLL(Node head) { Node last = null; while (head != null) { System.out.print(head.data + \" \"); last = head; head = head.right; } } void inorder(Node node) { if (node == null) return; inorder(node.left); System.out.print(node.data + \" \"); inorder(node.right); } // Driver program to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.right = new Node(6); tree.root.left.left.left = new Node(7); tree.root.left.left.right = new Node(8); tree.root.right.right.left = new Node(9); tree.root.right.right.right = new Node(10); System.out.println(\"Inorder traversal of given tree is : \"); tree.inorder(tree.root); tree.extractLeafList(tree.root); System.out.println(\"\"); System.out.println(\"Extracted double link list is : \"); tree.printDLL(tree.head); System.out.println(\"\"); System.out.println(\"Inorder traversal of modified tree is : \"); tree.inorder(tree.root); }} // This code has been contributed by Mayank Jaiswal(mayank_24)", "e": 44758, "s": 42284, "text": null }, { "code": "# Python program to extract leaf nodes from binary tree# using double linked list # A binary tree nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Main function which extracts all leaves from given Binary Tree.# The function returns new root of Binary Tree (Note that# root may change if Binary Tree has only one node).# The function also sets *head_ref as head of doubly linked list.# left pointer of tree is used as prev in DLL# and right pointer is used as nextdef extractLeafList(root): # Base Case if root is None: return None if root.left is None and root.right is None: # This node is going to be added to doubly linked # list of leaves, set pointer of this node as # previous head of DLL. We don't need to set left # pointer as left is already None root.right = extractLeafList.head # Change the left pointer of previous head if extractLeafList.head is not None: extractLeafList.head.left = root # Change head of linked list extractLeafList.head = root return None # Return new root # Recur for right and left subtrees root.right = extractLeafList(root.right) root.left = extractLeafList(root.left) return root # Utility function for printing tree in InOrderdef printInorder(root): if root is not None: printInorder(root.left) print (root.data,end=\" \") printInorder(root.right) def printList(head): while(head): if head.data is not None: print (head.data,end=\" \") head = head.right # Driver program to test above functionextractLeafList.head = Node(None)root = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.right = Node(6)root.left.left.left = Node(7)root.left.left.right = Node(8)root.right.right.left = Node(9)root.right.right.right = Node(10) print (\"Inorder traversal of given tree is:\")printInorder(root) root = extractLeafList(root) print (\"\\nExtract Double Linked List is:\")printList(extractLeafList.head) print (\"\\nInorder traversal of modified tree is:\")printInorder(root)", "e": 47015, "s": 44758, "text": null }, { "code": "// C# program to extract leaf// nodes from binary tree// using double linked listusing System; // A binary tree nodepublic class Node{ public int data; public Node left, right; public Node(int item) { data = item; right = left = null; }} public class BinaryTree{ Node root; Node head; // will point to head of DLL Node prev; // temporary pointer // The main function that links // the list list to be traversed public Node extractLeafList(Node root) { if (root == null) return null; if (root.left == null && root.right == null) { if (head == null) { head = root; prev = root; } else { prev.right = root; root.left = prev; prev = root; } return null; } root.left = extractLeafList(root.left); root.right = extractLeafList(root.right); return root; } // Prints the DLL in both forward // and reverse directions. public void printDLL(Node head) { Node last = null; while (head != null) { Console.Write(head.data + \" \"); last = head; head = head.right; } } void inorder(Node node) { if (node == null) return; inorder(node.left); Console.Write(node.data + \" \"); inorder(node.right); } // Driver code public static void Main(String []args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.right = new Node(6); tree.root.left.left.left = new Node(7); tree.root.left.left.right = new Node(8); tree.root.right.right.left = new Node(9); tree.root.right.right.right = new Node(10); Console.WriteLine(\"Inorder traversal of given tree is : \"); tree.inorder(tree.root); tree.extractLeafList(tree.root); Console.WriteLine(\"\"); Console.WriteLine(\"Extracted double link list is : \"); tree.printDLL(tree.head); Console.WriteLine(\"\"); Console.WriteLine(\"Inorder traversal of modified tree is : \"); tree.inorder(tree.root); }} // This code has been contributed by 29AjayKumar", "e": 49481, "s": 47015, "text": null }, { "code": "<script> // javascript program to extract leaf nodes from binary tree // using var linked list // A binary tree node class Node { constructor(val) { this.data = val; this.left = null; this.right = null; } } var root; var head; // will point to head of DLL var prev; // temporary pointer // The main function that links the list list to be traversed function extractLeafList(root) { if (root == null) return null; if (root.left == null && root.right == null) { if (head == null) { head = root; prev = root; } else { prev.right = root; root.left = prev; prev = root; } return null; } root.left = extractLeafList(root.left); root.right = extractLeafList(root.right); return root; } // Prints the DLL in both forward and reverse directions. function printDLL(head) { var last = null; while (head != null) { document.write(head.data + \" \"); last = head; head = head.right; } } function inorder(node) { if (node == null) return; inorder(node.left); document.write(node.data + \" \"); inorder(node.right); } // Driver program to test above functions root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.right = new Node(6); root.left.left.left = new Node(7); root.left.left.right = new Node(8); root.right.right.left = new Node(9); root.right.right.right = new Node(10); document.write(\"Inorder traversal of given tree is :<br/> \"); inorder(root); extractLeafList(root); document.write(\"<br/>\"); document.write(\"Extracted var link list is :<br/> \"); printDLL(head); document.write(\"<br/>\"); document.write(\"Inorder traversal of modified tree is : <br/>\"); inorder(root); // This code contributed by umadevi9616</script>", "e": 51625, "s": 49481, "text": null }, { "code": null, "e": 51778, "s": 51625, "text": "Inorder Traversal of given Tree is:\n7 4 8 2 5 1 3 9 6 10 \nExtracted Double Linked list is:\n7 8 5 9 10 \nInorder traversal of modified tree is:\n4 2 1 3 6 " }, { "code": null, "e": 51862, "s": 51778, "text": "Time Complexity: O(n), the solution does a single traversal of a given Binary Tree." }, { "code": null, "e": 52716, "s": 51862, "text": "YouTubeGeeksforGeeks502K subscribersExtract Leaves of a Binary Tree in a Doubly Linked List | 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 / 4:53•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=JH9Jea12MEI\" 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": 52890, "s": 52716, "text": "This article is contributed by Chandra Prakash. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 52902, "s": 52890, "text": "29AjayKumar" }, { "code": null, "e": 52916, "s": 52902, "text": "rathbhupendra" }, { "code": null, "e": 52929, "s": 52916, "text": "Akanksha_Rai" }, { "code": null, "e": 52941, "s": 52929, "text": "umadevi9616" }, { "code": null, "e": 52954, "s": 52941, "text": "simmytarika5" }, { "code": null, "e": 52971, "s": 52954, "text": "khushboogoyal499" }, { "code": null, "e": 52986, "s": 52971, "text": "sagar0719kumar" }, { "code": null, "e": 53002, "s": 52986, "text": "amartyaghoshgfg" }, { "code": null, "e": 53009, "s": 53002, "text": "Amazon" }, { "code": null, "e": 53028, "s": 53009, "text": "doubly linked list" }, { "code": null, "e": 53037, "s": 53028, "text": "Linkedin" }, { "code": null, "e": 53049, "s": 53037, "text": "Linked List" }, { "code": null, "e": 53054, "s": 53049, "text": "Tree" }, { "code": null, "e": 53061, "s": 53054, "text": "Amazon" }, { "code": null, "e": 53070, "s": 53061, "text": "Linkedin" }, { "code": null, "e": 53082, "s": 53070, "text": "Linked List" }, { "code": null, "e": 53087, "s": 53082, "text": "Tree" }, { "code": null, "e": 53185, "s": 53087, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 53220, "s": 53185, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 53259, "s": 53220, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 53281, "s": 53259, "text": "Reverse a linked list" }, { "code": null, "e": 53329, "s": 53281, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 53367, "s": 53329, "text": "Linked List | Set 3 (Deleting a node)" }, { "code": null, "e": 53417, "s": 53367, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 53452, "s": 53417, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 53486, "s": 53452, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 53515, "s": 53486, "text": "AVL Tree | Set 1 (Insertion)" } ]
How to use Push-Location and Pop-Location command in PowerShell?
Push-Location command in PowerShell is used to push (add) the current location to the location stack (Last In First Out (LIFO) - queue) while the Pop-Location is to retrieve the last location from the stack. When the PowerShell console opens there are no locations set to the stack. PS C:\> Get-Location -Stack PS C:\> When you type the Push-Location command it performs two operations at a time. First, it saves the current location to the top of the stack, and second, it browse the path specified. If there is no path specified then it only moves the current location to the stack. For example, PS C:\> Push-Location PS C:\> Get-Location -Stack Path ---- C:\ We will specify the path now, PS C:\> Push-Location C:\Temp\ PS C:\Temp> Get-Location -Stack Path ---- C:\ C:\ In the above example, the current location was C:\ so the command pushed it to the stack and it moved to that specified directory. Let say we are pushing one more location to the stack. PS C:\Temp> Push-Location C:\Temp\iisadministration\ PS C:\Temp\iisadministration> Get-Location -Stack Path ---- C:\Temp C:\ C:\ In the above example, C:\Temp was the current location so it is top of the stack. To jump to the last location we need to use the Pop-Location command. For example, PS C:\Temp\iisadministration> Pop-Location PS C:\Temp> When you run the Pop-Location command, the last item (recent item) from the queue is deleted. Let’s check the stack. PS C:\Temp> Get-Location -Stack Path ---- C:\ C:\ You can also create a new stack to push the location and then you can retrieve the location using the Pop-Location command from the specific stack. For example, PS C:\Windows\System32> Push-Location WindowsPowerShell -StackName Stack2 PS C:\Windows\System32\WindowsPowerShell> Get-Location -StackName Stack2 Path ---- C:\Windows\System32 In the above example, we have created a new stack called ‘Stack2’ and pushed a current location there, you can see the location was inserted in the new stack using the Get-Location command for the specific stack. To retrieve the data from that stack, PS C:\Windows\System32\WindowsPowerShell> Pop-Location -StackName stack2 PS C:\Windows\System32>
[ { "code": null, "e": 1270, "s": 1062, "text": "Push-Location command in PowerShell is used to push (add) the current location to the location stack (Last In First Out (LIFO) - queue) while the Pop-Location is to retrieve the last location from the stack." }, { "code": null, "e": 1345, "s": 1270, "text": "When the PowerShell console opens there are no locations set to the stack." }, { "code": null, "e": 1381, "s": 1345, "text": "PS C:\\> Get-Location -Stack\nPS C:\\>" }, { "code": null, "e": 1660, "s": 1381, "text": "When you type the Push-Location command it performs two operations at a time. First, it saves the current location to the top of the stack, and second, it browse the path specified. If there is no path specified then it only moves the current location to the stack. For example," }, { "code": null, "e": 1724, "s": 1660, "text": "PS C:\\> Push-Location\nPS C:\\> Get-Location -Stack\nPath\n----\nC:\\" }, { "code": null, "e": 1754, "s": 1724, "text": "We will specify the path now," }, { "code": null, "e": 1835, "s": 1754, "text": "PS C:\\> Push-Location C:\\Temp\\\nPS C:\\Temp> Get-Location -Stack\nPath\n----\nC:\\\nC:\\" }, { "code": null, "e": 2021, "s": 1835, "text": "In the above example, the current location was C:\\ so the command pushed it to the stack and it moved to that specified directory. Let say we are pushing one more location to the stack." }, { "code": null, "e": 2150, "s": 2021, "text": "PS C:\\Temp> Push-Location C:\\Temp\\iisadministration\\\nPS C:\\Temp\\iisadministration> Get-Location -Stack\nPath\n----\nC:\\Temp\nC:\\\nC:\\" }, { "code": null, "e": 2315, "s": 2150, "text": "In the above example, C:\\Temp was the current location so it is top of the stack. To jump to the last location we need to use the Pop-Location command. For example," }, { "code": null, "e": 2370, "s": 2315, "text": "PS C:\\Temp\\iisadministration> Pop-Location\nPS C:\\Temp>" }, { "code": null, "e": 2487, "s": 2370, "text": "When you run the Pop-Location command, the last item (recent item) from the queue is deleted. Let’s check the stack." }, { "code": null, "e": 2537, "s": 2487, "text": "PS C:\\Temp> Get-Location -Stack\nPath\n----\nC:\\\nC:\\" }, { "code": null, "e": 2698, "s": 2537, "text": "You can also create a new stack to push the location and then you can retrieve the location using the Pop-Location command from the specific stack. For example," }, { "code": null, "e": 2875, "s": 2698, "text": "PS C:\\Windows\\System32> Push-Location WindowsPowerShell -StackName Stack2\nPS C:\\Windows\\System32\\WindowsPowerShell> Get-Location -StackName Stack2\nPath\n----\nC:\\Windows\\System32" }, { "code": null, "e": 3088, "s": 2875, "text": "In the above example, we have created a new stack called ‘Stack2’ and pushed a current location there, you can see the location was inserted in the new stack using the Get-Location command for the specific stack." }, { "code": null, "e": 3126, "s": 3088, "text": "To retrieve the data from that stack," }, { "code": null, "e": 3223, "s": 3126, "text": "PS C:\\Windows\\System32\\WindowsPowerShell> Pop-Location -StackName stack2\nPS C:\\Windows\\System32>" } ]
Beautiful Soup - Installation
As BeautifulSoup is not a standard python library, we need to install it first. We are going to install the BeautifulSoup 4 library (also known as BS4), which is the latest one. To isolate our working environment so as not to disturb the existing setup, let us first create a virtual environment. A virtual environment allows us to create an isolated working copy of python for a specific project without affecting the outside setup. Best way to install any python package machine is using pip, however, if pip is not installed already (you can check it using – “pip –version” in your command or shell prompt), you can install by giving below command − $sudo apt-get install python-pip To install pip in windows, do the following − Download the get-pip.py from https://bootstrap.pypa.io/get-pip.py or from the github to your computer. Download the get-pip.py from https://bootstrap.pypa.io/get-pip.py or from the github to your computer. Open the command prompt and navigate to the folder containing get-pip.py file. Open the command prompt and navigate to the folder containing get-pip.py file. Run the following command − Run the following command − >python get-pip.py That’s it, pip is now installed in your windows machine. You can verify your pip installed by running below command − >pip --version pip 19.2.3 from c:\users\yadur\appdata\local\programs\python\python37\lib\site-packages\pip (python 3.7) Run the below command in your command prompt − >pip install virtualenv After running, you will see the below screenshot − Below command will create a virtual environment (“myEnv”) in your current directory − >virtualenv myEnv To activate your virtual environment, run the following command − >myEnv\Scripts\activate In the above screenshot, you can see we have “myEnv” as prefix which tells us that we are under virtual environment “myEnv”. To come out of virtual environment, run deactivate. (myEnv) C:\Users\yadur>deactivate C:\Users\yadur> As our virtual environment is ready, now let us install beautifulsoup. As BeautifulSoup is not a standard library, we need to install it. We are going to use the BeautifulSoup 4 package (known as bs4). To install bs4 on Debian or Ubuntu linux using system package manager, run the below command − $sudo apt-get install python-bs4 (for python 2.x) $sudo apt-get install python3-bs4 (for python 3.x) You can install bs4 using easy_install or pip (in case you find problem in installing using system packager). $easy_install beautifulsoup4 $pip install beautifulsoup4 (You may need to use easy_install3 or pip3 respectively if you’re using python3) To install beautifulsoup4 in windows is very simple, especially if you have pip already installed. >pip install beautifulsoup4 So now beautifulsoup4 is installed in our machine. Let us talk about some problems encountered after installation. On windows machine you might encounter, wrong version being installed error mainly through − error: ImportError “No module named HTMLParser”, then you must be running python 2 version of the code under Python 3. error: ImportError “No module named HTMLParser”, then you must be running python 2 version of the code under Python 3. error: ImportError “No module named html.parser” error, then you must be running Python 3 version of the code under Python 2. error: ImportError “No module named html.parser” error, then you must be running Python 3 version of the code under Python 2. Best way to get out of above two situations is to re-install the BeautifulSoup again, completely removing existing installation. If you get the SyntaxError “Invalid syntax” on the line ROOT_TAG_NAME = u’[document]’, then you need to convert the python 2 code to python 3, just by either installing the package − $ python3 setup.py install or by manually running python’s 2 to 3 conversion script on the bs4 directory − $ 2to3-3.2 -w bs4 By default, Beautiful Soup supports the HTML parser included in Python’s standard library, however it also supports many external third party python parsers like lxml parser or html5lib parser. To install lxml or html5lib parser, use the command − $apt-get install python-lxml $apt-get insall python-html5lib $pip install lxml $pip install html5lib Generally, users use lxml for speed and it is recommended to use lxml or html5lib parser if you are using older version of python 2 (before 2.7.3 version) or python 3 (before 3.2.2) as python’s built-in HTML parser is not very good in handling older version. It is time to test our Beautiful Soup package in one of the html pages (taking web page – https://www.tutorialspoint.com/index.htm, you can choose any-other web page you want) and extract some information from it. In the below code, we are trying to extract the title from the webpage − from bs4 import BeautifulSoup import requests url = "https://www.tutorialspoint.com/index.htm" req = requests.get(url) soup = BeautifulSoup(req.text, "html.parser") print(soup.title) <title>H2O, Colab, Theano, Flutter, KNime, Mean.js, Weka, Solidity, Org.Json, AWS QuickSight, JSON.Simple, Jackson Annotations, Passay, Boon, MuleSoft, Nagios, Matplotlib, Java NIO, PyTorch, SLF4J, Parallax Scrolling, Java Cryptography</title> One common task is to extract all the URLs within a webpage. For that we just need to add the below line of code − for link in soup.find_all('a'): print(link.get('href')) https://www.tutorialspoint.com/index.htm https://www.tutorialspoint.com/about/about_careers.htm https://www.tutorialspoint.com/questions/index.php https://www.tutorialspoint.com/online_dev_tools.htm https://www.tutorialspoint.com/codingground.htm https://www.tutorialspoint.com/current_affairs.htm https://www.tutorialspoint.com/upsc_ias_exams.htm https://www.tutorialspoint.com/tutor_connect/index.php https://www.tutorialspoint.com/whiteboard.htm https://www.tutorialspoint.com/netmeeting.php https://www.tutorialspoint.com/index.htm https://www.tutorialspoint.com/tutorialslibrary.htm https://www.tutorialspoint.com/videotutorials/index.php https://store.tutorialspoint.com https://www.tutorialspoint.com/gate_exams_tutorials.htm https://www.tutorialspoint.com/html_online_training/index.asp https://www.tutorialspoint.com/css_online_training/index.asp https://www.tutorialspoint.com/3d_animation_online_training/index.asp https://www.tutorialspoint.com/swift_4_online_training/index.asp https://www.tutorialspoint.com/blockchain_online_training/index.asp https://www.tutorialspoint.com/reactjs_online_training/index.asp https://www.tutorix.com https://www.tutorialspoint.com/videotutorials/top-courses.php https://www.tutorialspoint.com/the_full_stack_web_development/index.asp .... .... https://www.tutorialspoint.com/online_dev_tools.htm https://www.tutorialspoint.com/free_web_graphics.htm https://www.tutorialspoint.com/online_file_conversion.htm https://www.tutorialspoint.com/netmeeting.php https://www.tutorialspoint.com/free_online_whiteboard.htm http://www.tutorialspoint.com https://www.facebook.com/tutorialspointindia https://plus.google.com/u/0/+tutorialspoint http://www.twitter.com/tutorialspoint http://www.linkedin.com/company/tutorialspoint https://www.youtube.com/channel/UCVLbzhxVTiTLiVKeGV7WEBg https://www.tutorialspoint.com/index.htm /about/about_privacy.htm#cookies /about/faq.htm /about/about_helping.htm /about/contact_us.htm Similarly, we can extract useful information using beautifulsoup4. Now let us understand more about “soup” in above example. 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": 2163, "s": 1985, "text": "As BeautifulSoup is not a standard python library, we need to install it first. We are going to install the BeautifulSoup 4 library (also known as BS4), which is the latest one." }, { "code": null, "e": 2282, "s": 2163, "text": "To isolate our working environment so as not to disturb the existing setup, let us first create a virtual environment." }, { "code": null, "e": 2419, "s": 2282, "text": "A virtual environment allows us to create an isolated working copy of python for a specific project without affecting the outside setup." }, { "code": null, "e": 2638, "s": 2419, "text": "Best way to install any python package machine is using pip, however, if pip is not installed already (you can check it using – “pip –version” in your command or shell prompt), you can install by giving below command −" }, { "code": null, "e": 2672, "s": 2638, "text": "$sudo apt-get install python-pip\n" }, { "code": null, "e": 2718, "s": 2672, "text": "To install pip in windows, do the following −" }, { "code": null, "e": 2821, "s": 2718, "text": "Download the get-pip.py from https://bootstrap.pypa.io/get-pip.py or from the github to your computer." }, { "code": null, "e": 2924, "s": 2821, "text": "Download the get-pip.py from https://bootstrap.pypa.io/get-pip.py or from the github to your computer." }, { "code": null, "e": 3003, "s": 2924, "text": "Open the command prompt and navigate to the folder containing get-pip.py file." }, { "code": null, "e": 3082, "s": 3003, "text": "Open the command prompt and navigate to the folder containing get-pip.py file." }, { "code": null, "e": 3110, "s": 3082, "text": "Run the following command −" }, { "code": null, "e": 3138, "s": 3110, "text": "Run the following command −" }, { "code": null, "e": 3158, "s": 3138, "text": ">python get-pip.py\n" }, { "code": null, "e": 3215, "s": 3158, "text": "That’s it, pip is now installed in your windows machine." }, { "code": null, "e": 3276, "s": 3215, "text": "You can verify your pip installed by running below command −" }, { "code": null, "e": 3396, "s": 3276, "text": ">pip --version\npip 19.2.3 from c:\\users\\yadur\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\pip (python 3.7)" }, { "code": null, "e": 3443, "s": 3396, "text": "Run the below command in your command prompt −" }, { "code": null, "e": 3468, "s": 3443, "text": ">pip install virtualenv\n" }, { "code": null, "e": 3519, "s": 3468, "text": "After running, you will see the below screenshot −" }, { "code": null, "e": 3605, "s": 3519, "text": "Below command will create a virtual environment (“myEnv”) in your current directory −" }, { "code": null, "e": 3624, "s": 3605, "text": ">virtualenv myEnv\n" }, { "code": null, "e": 3690, "s": 3624, "text": "To activate your virtual environment, run the following command −" }, { "code": null, "e": 3715, "s": 3690, "text": ">myEnv\\Scripts\\activate\n" }, { "code": null, "e": 3840, "s": 3715, "text": "In the above screenshot, you can see we have “myEnv” as prefix which tells us that we are under virtual environment “myEnv”." }, { "code": null, "e": 3892, "s": 3840, "text": "To come out of virtual environment, run deactivate." }, { "code": null, "e": 3942, "s": 3892, "text": "(myEnv) C:\\Users\\yadur>deactivate\nC:\\Users\\yadur>" }, { "code": null, "e": 4013, "s": 3942, "text": "As our virtual environment is ready, now let us install beautifulsoup." }, { "code": null, "e": 4144, "s": 4013, "text": "As BeautifulSoup is not a standard library, we need to install it. We are going to use the BeautifulSoup 4 package (known as bs4)." }, { "code": null, "e": 4239, "s": 4144, "text": "To install bs4 on Debian or Ubuntu linux using system package manager, run the below command −" }, { "code": null, "e": 4340, "s": 4239, "text": "$sudo apt-get install python-bs4 (for python 2.x)\n$sudo apt-get install python3-bs4 (for python 3.x)" }, { "code": null, "e": 4450, "s": 4340, "text": "You can install bs4 using easy_install or pip (in case you find problem in installing using system packager)." }, { "code": null, "e": 4507, "s": 4450, "text": "$easy_install beautifulsoup4\n$pip install beautifulsoup4" }, { "code": null, "e": 4588, "s": 4507, "text": "(You may need to use easy_install3 or pip3 respectively if you’re using python3)" }, { "code": null, "e": 4687, "s": 4588, "text": "To install beautifulsoup4 in windows is very simple, especially if you have pip already installed." }, { "code": null, "e": 4716, "s": 4687, "text": ">pip install beautifulsoup4\n" }, { "code": null, "e": 4831, "s": 4716, "text": "So now beautifulsoup4 is installed in our machine. Let us talk about some problems encountered after installation." }, { "code": null, "e": 4924, "s": 4831, "text": "On windows machine you might encounter, wrong version being installed error mainly through −" }, { "code": null, "e": 5043, "s": 4924, "text": "error: ImportError “No module named HTMLParser”, then you must be running python 2 version of the code under Python 3." }, { "code": null, "e": 5162, "s": 5043, "text": "error: ImportError “No module named HTMLParser”, then you must be running python 2 version of the code under Python 3." }, { "code": null, "e": 5288, "s": 5162, "text": "error: ImportError “No module named html.parser” error, then you must be running Python 3 version of the code under Python 2." }, { "code": null, "e": 5414, "s": 5288, "text": "error: ImportError “No module named html.parser” error, then you must be running Python 3 version of the code under Python 2." }, { "code": null, "e": 5543, "s": 5414, "text": "Best way to get out of above two situations is to re-install the BeautifulSoup again, completely removing existing installation." }, { "code": null, "e": 5726, "s": 5543, "text": "If you get the SyntaxError “Invalid syntax” on the line ROOT_TAG_NAME = u’[document]’, then you need to convert the python 2 code to python 3, just by either installing the package −" }, { "code": null, "e": 5754, "s": 5726, "text": "$ python3 setup.py install\n" }, { "code": null, "e": 5834, "s": 5754, "text": "or by manually running python’s 2 to 3 conversion script on the bs4 directory −" }, { "code": null, "e": 5853, "s": 5834, "text": "$ 2to3-3.2 -w bs4\n" }, { "code": null, "e": 6047, "s": 5853, "text": "By default, Beautiful Soup supports the HTML parser included in Python’s standard library, however it also supports many external third party python parsers like lxml parser or html5lib parser." }, { "code": null, "e": 6101, "s": 6047, "text": "To install lxml or html5lib parser, use the command −" }, { "code": null, "e": 6162, "s": 6101, "text": "$apt-get install python-lxml\n$apt-get insall python-html5lib" }, { "code": null, "e": 6202, "s": 6162, "text": "$pip install lxml\n$pip install html5lib" }, { "code": null, "e": 6461, "s": 6202, "text": "Generally, users use lxml for speed and it is recommended to use lxml or html5lib parser if you are using older version of python 2 (before 2.7.3 version) or python 3 (before 3.2.2) as python’s built-in HTML parser is not very good in handling older version." }, { "code": null, "e": 6675, "s": 6461, "text": "It is time to test our Beautiful Soup package in one of the html pages (taking web page – https://www.tutorialspoint.com/index.htm, you can choose any-other web page you want) and extract some information from it." }, { "code": null, "e": 6748, "s": 6675, "text": "In the below code, we are trying to extract the title from the webpage −" }, { "code": null, "e": 6931, "s": 6748, "text": "from bs4 import BeautifulSoup\nimport requests\nurl = \"https://www.tutorialspoint.com/index.htm\"\nreq = requests.get(url)\nsoup = BeautifulSoup(req.text, \"html.parser\")\nprint(soup.title)" }, { "code": null, "e": 7176, "s": 6931, "text": "<title>H2O, Colab, Theano, Flutter, KNime, Mean.js, Weka, Solidity, Org.Json, AWS QuickSight, JSON.Simple, Jackson Annotations, Passay, Boon, MuleSoft, Nagios, Matplotlib, Java NIO, PyTorch, SLF4J, Parallax Scrolling, Java Cryptography</title>\n" }, { "code": null, "e": 7291, "s": 7176, "text": "One common task is to extract all the URLs within a webpage. For that we just need to add the below line of code −" }, { "code": null, "e": 7347, "s": 7291, "text": "for link in soup.find_all('a'):\nprint(link.get('href'))" }, { "code": null, "e": 9304, "s": 7347, "text": "https://www.tutorialspoint.com/index.htm\nhttps://www.tutorialspoint.com/about/about_careers.htm\nhttps://www.tutorialspoint.com/questions/index.php\nhttps://www.tutorialspoint.com/online_dev_tools.htm\nhttps://www.tutorialspoint.com/codingground.htm\nhttps://www.tutorialspoint.com/current_affairs.htm\nhttps://www.tutorialspoint.com/upsc_ias_exams.htm\nhttps://www.tutorialspoint.com/tutor_connect/index.php\nhttps://www.tutorialspoint.com/whiteboard.htm\nhttps://www.tutorialspoint.com/netmeeting.php\nhttps://www.tutorialspoint.com/index.htm\nhttps://www.tutorialspoint.com/tutorialslibrary.htm\nhttps://www.tutorialspoint.com/videotutorials/index.php\nhttps://store.tutorialspoint.com\nhttps://www.tutorialspoint.com/gate_exams_tutorials.htm\nhttps://www.tutorialspoint.com/html_online_training/index.asp\nhttps://www.tutorialspoint.com/css_online_training/index.asp\nhttps://www.tutorialspoint.com/3d_animation_online_training/index.asp\nhttps://www.tutorialspoint.com/swift_4_online_training/index.asp\nhttps://www.tutorialspoint.com/blockchain_online_training/index.asp\nhttps://www.tutorialspoint.com/reactjs_online_training/index.asp\nhttps://www.tutorix.com\nhttps://www.tutorialspoint.com/videotutorials/top-courses.php\nhttps://www.tutorialspoint.com/the_full_stack_web_development/index.asp\n....\n....\nhttps://www.tutorialspoint.com/online_dev_tools.htm\nhttps://www.tutorialspoint.com/free_web_graphics.htm\nhttps://www.tutorialspoint.com/online_file_conversion.htm\nhttps://www.tutorialspoint.com/netmeeting.php\nhttps://www.tutorialspoint.com/free_online_whiteboard.htm\nhttp://www.tutorialspoint.com\nhttps://www.facebook.com/tutorialspointindia\nhttps://plus.google.com/u/0/+tutorialspoint\nhttp://www.twitter.com/tutorialspoint\nhttp://www.linkedin.com/company/tutorialspoint\nhttps://www.youtube.com/channel/UCVLbzhxVTiTLiVKeGV7WEBg\nhttps://www.tutorialspoint.com/index.htm\n/about/about_privacy.htm#cookies\n/about/faq.htm\n/about/about_helping.htm\n/about/contact_us.htm\n" }, { "code": null, "e": 9371, "s": 9304, "text": "Similarly, we can extract useful information using beautifulsoup4." }, { "code": null, "e": 9429, "s": 9371, "text": "Now let us understand more about “soup” in above example." }, { "code": null, "e": 9464, "s": 9429, "text": "\n 38 Lectures \n 3.5 hours \n" }, { "code": null, "e": 9488, "s": 9464, "text": " Chandramouli Jayendran" }, { "code": null, "e": 9521, "s": 9488, "text": "\n 22 Lectures \n 1 hours \n" }, { "code": null, "e": 9537, "s": 9521, "text": " TELCOMA Global" }, { "code": null, "e": 9569, "s": 9537, "text": "\n 6 Lectures \n 1 hours \n" }, { "code": null, "e": 9586, "s": 9569, "text": " AlexanderSchlee" }, { "code": null, "e": 9618, "s": 9586, "text": "\n 6 Lectures \n 1 hours \n" }, { "code": null, "e": 9635, "s": 9618, "text": " AlexanderSchlee" }, { "code": null, "e": 9667, "s": 9635, "text": "\n 6 Lectures \n 1 hours \n" }, { "code": null, "e": 9684, "s": 9667, "text": " AlexanderSchlee" }, { "code": null, "e": 9717, "s": 9684, "text": "\n 22 Lectures \n 4 hours \n" }, { "code": null, "e": 9734, "s": 9717, "text": " AlexanderSchlee" }, { "code": null, "e": 9741, "s": 9734, "text": " Print" }, { "code": null, "e": 9752, "s": 9741, "text": " Add Notes" } ]
Get the powers of a NumPy array values element-wise - GeeksforGeeks
19 Dec, 2021 NumPy is a powerful N-dimensional array object and its use in linear algebra, Fourier transform, and random number capabilities. It provides an array object much faster than traditional Python lists. numpy.power() is used to calculate the power of elements. It treats first array elements raised to powers from the second array, element-wise. Syntax: numpy.power(arr1, arr2, out = None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None) Parameters : arr1 : [array_like]Input array or object which works as base. arr2 : [array_like]Input array or object which works as exponent. out : [ndarray, optional]Output array with same dimensions as Input array, placed with result. **kwargs : Allows you to pass keyword variable length of argument to a function. It is used when we want to handle named argument in a function. where : [array_like, optional]True value means to calculate the universal functions(ufunc) at that position, False value means to leave the value in the output alone. So, let’s discuss some examples related to the getting power of an array. Example 1: compute the power of an array with different element-Wise values. Python3 # import required modulesimport numpy as np # creating the arraysample_array1 = np.arange(5)sample_array2 = np.arange(0, 10, 2) print("Original array ")print("array1 ", sample_array1)print("array2 ", sample_array2) # calculating element-wise powerpower_array = np.power(sample_array1, sample_array2) print("power to the array1 and array 2 : ", power_array) Output: Original array array1 [0 1 2 3 4] array2 [0 2 4 6 8] power to the array1 and array 2 : [ 1 1 16 729 65536] Examples 2: computing the same power for every element in the array. Python3 # import required moduleimport numpy as np # creating the arrayarray = np.arange(8)print("Original array")print(array) # computing the power of arrayprint("power of 3 for every element-wise:")print(np.power(array, 3)) Output: Original array [0 1 2 3 4 5 6 7] power of 3 for every element-wise: [ 0 1 8 27 64 125 216 343] Examples 3: computing the power of decimal value. Python3 # import required modulesimport numpy as np # creating the arraysample_array1 = np.arange(5) # initialization the decimal numbersample_array2 = [1.0, 2.0, 3.0, 3.0, 2.0] print("Original array ")print("array1 ", sample_array1)print("array2 ", sample_array2) # calculating element-wise powerpower_array = np.power(sample_array1, sample_array2) print("power to the array1 and array 2 : ", power_array) Output: Original array array1 [0 1 2 3 4] array2 [1.0, 2.0, 3.0, 3.0, 2.0] power to the array1 and array 2 : [ 0. 1. 8. 27. 16.] Note: you can not compute negative power Example 4: Python3 # importing moduleimport numpy as np # creating the arrayarray = np.arange(8)print("Original array")print(array)print("power of 3 for every element-wise:") # computing the negative power elementprint(np.power(array, -3)) Output: akshaysingh98088 Python numpy-arrayManipulation Python numpy-program Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n19 Dec, 2021" }, { "code": null, "e": 24245, "s": 23901, "text": "NumPy is a powerful N-dimensional array object and its use in linear algebra, Fourier transform, and random number capabilities. It provides an array object much faster than traditional Python lists. numpy.power() is used to calculate the power of elements. It treats first array elements raised to powers from the second array, element-wise. " }, { "code": null, "e": 24353, "s": 24245, "text": "Syntax: numpy.power(arr1, arr2, out = None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None)" }, { "code": null, "e": 24366, "s": 24353, "text": "Parameters :" }, { "code": null, "e": 24957, "s": 24366, "text": "arr1 : [array_like]Input array or object which works as base. arr2 : [array_like]Input array or object which works as exponent. out : [ndarray, optional]Output array with same dimensions as Input array, placed with result. **kwargs : Allows you to pass keyword variable length of argument to a function. It is used when we want to handle named argument in a function. where : [array_like, optional]True value means to calculate the universal functions(ufunc) at that position, False value means to leave the value in the output alone." }, { "code": null, "e": 25031, "s": 24957, "text": "So, let’s discuss some examples related to the getting power of an array." }, { "code": null, "e": 25108, "s": 25031, "text": "Example 1: compute the power of an array with different element-Wise values." }, { "code": null, "e": 25116, "s": 25108, "text": "Python3" }, { "code": "# import required modulesimport numpy as np # creating the arraysample_array1 = np.arange(5)sample_array2 = np.arange(0, 10, 2) print(\"Original array \")print(\"array1 \", sample_array1)print(\"array2 \", sample_array2) # calculating element-wise powerpower_array = np.power(sample_array1, sample_array2) print(\"power to the array1 and array 2 : \", power_array)", "e": 25474, "s": 25116, "text": null }, { "code": null, "e": 25482, "s": 25474, "text": "Output:" }, { "code": null, "e": 25605, "s": 25482, "text": "Original array \narray1 [0 1 2 3 4]\narray2 [0 2 4 6 8]\npower to the array1 and array 2 : [ 1 1 16 729 65536]" }, { "code": null, "e": 25674, "s": 25605, "text": "Examples 2: computing the same power for every element in the array." }, { "code": null, "e": 25682, "s": 25674, "text": "Python3" }, { "code": "# import required moduleimport numpy as np # creating the arrayarray = np.arange(8)print(\"Original array\")print(array) # computing the power of arrayprint(\"power of 3 for every element-wise:\")print(np.power(array, 3))", "e": 25901, "s": 25682, "text": null }, { "code": null, "e": 25909, "s": 25901, "text": "Output:" }, { "code": null, "e": 26011, "s": 25909, "text": "Original array\n[0 1 2 3 4 5 6 7]\npower of 3 for every element-wise:\n[ 0 1 8 27 64 125 216 343]" }, { "code": null, "e": 26061, "s": 26011, "text": "Examples 3: computing the power of decimal value." }, { "code": null, "e": 26069, "s": 26061, "text": "Python3" }, { "code": "# import required modulesimport numpy as np # creating the arraysample_array1 = np.arange(5) # initialization the decimal numbersample_array2 = [1.0, 2.0, 3.0, 3.0, 2.0] print(\"Original array \")print(\"array1 \", sample_array1)print(\"array2 \", sample_array2) # calculating element-wise powerpower_array = np.power(sample_array1, sample_array2) print(\"power to the array1 and array 2 : \", power_array)", "e": 26469, "s": 26069, "text": null }, { "code": null, "e": 26477, "s": 26469, "text": "Output:" }, { "code": null, "e": 26604, "s": 26477, "text": "Original array \narray1 [0 1 2 3 4]\narray2 [1.0, 2.0, 3.0, 3.0, 2.0]\npower to the array1 and array 2 : [ 0. 1. 8. 27. 16.]" }, { "code": null, "e": 26645, "s": 26604, "text": "Note: you can not compute negative power" }, { "code": null, "e": 26656, "s": 26645, "text": "Example 4:" }, { "code": null, "e": 26664, "s": 26656, "text": "Python3" }, { "code": "# importing moduleimport numpy as np # creating the arrayarray = np.arange(8)print(\"Original array\")print(array)print(\"power of 3 for every element-wise:\") # computing the negative power elementprint(np.power(array, -3))", "e": 26886, "s": 26664, "text": null }, { "code": null, "e": 26894, "s": 26886, "text": "Output:" }, { "code": null, "e": 26911, "s": 26894, "text": "akshaysingh98088" }, { "code": null, "e": 26942, "s": 26911, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 26963, "s": 26942, "text": "Python numpy-program" }, { "code": null, "e": 26976, "s": 26963, "text": "Python-numpy" }, { "code": null, "e": 26983, "s": 26976, "text": "Python" }, { "code": null, "e": 27081, "s": 26983, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27090, "s": 27081, "text": "Comments" }, { "code": null, "e": 27103, "s": 27090, "text": "Old Comments" }, { "code": null, "e": 27135, "s": 27103, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27191, "s": 27135, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27233, "s": 27191, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27275, "s": 27233, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27311, "s": 27275, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 27333, "s": 27311, "text": "Defaultdict in Python" }, { "code": null, "e": 27372, "s": 27333, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27399, "s": 27372, "text": "Python Classes and Objects" }, { "code": null, "e": 27430, "s": 27399, "text": "Python | os.path.join() method" } ]
C function argument and return values
Here we will see what are the different types of C functions based on the return values and arguments. So a function either can take some arguments, or nothing is taken. Similarly, a function can return something, otherwise does not return anything. So we can categorize them into four types. Function with No argument and No return type. Function with No argument and Return something. A function that takes argument but returns nothing. Functions that take an argument and also return something. #include <stdio.h> void my_function() { printf("This is a function that takes no argument, and returns nothing."); } main() { my_function(); } This is a function that takes no argument, and returns nothing. Here this function is not taking any input argument, and also the return type is void. So this returns nothing. #include <stdio.h> int my_function() { printf("This function takes no argument, But returns 50\n"); return 50; } main() { int x; x = my_function(); printf("Returned Value: %d", x); } This function takes no argument, But returns 50 Returned Value: 50 Here this function is not taking any input argument, but its return type is int. So this returns a value. #include <stdio.h> void my_function(int x) { printf("This function is taking %d as argument, but returns nothing", x); return 50; } main() { int x; x = 10; my_function(x); } This function is taking 10 as argument, but returns nothing Here this function is taking an input argument, but its return type is void. So this returns nothing. #include <stdio.h> int my_function(int x) { printf("This will take an argument, and will return its squared value\n"); return x * x; } main() { int x, res; x = 12; res = my_function(12); printf("Returned Value: %d", res); } This function is taking 10 as argument, but returns nothing Here this function is taking any input argument, and also returns value.
[ { "code": null, "e": 1165, "s": 1062, "text": "Here we will see what are the different types of C functions based on the return values and arguments." }, { "code": null, "e": 1355, "s": 1165, "text": "So a function either can take some arguments, or nothing is taken. Similarly, a function can return something, otherwise does not return anything. So we can categorize them into four types." }, { "code": null, "e": 1401, "s": 1355, "text": "Function with No argument and No return type." }, { "code": null, "e": 1449, "s": 1401, "text": "Function with No argument and Return something." }, { "code": null, "e": 1501, "s": 1449, "text": "A function that takes argument but returns nothing." }, { "code": null, "e": 1560, "s": 1501, "text": "Functions that take an argument and also return something." }, { "code": null, "e": 1709, "s": 1560, "text": "#include <stdio.h>\nvoid my_function() {\n printf(\"This is a function that takes no argument, and returns nothing.\");\n}\nmain() {\n my_function();\n}" }, { "code": null, "e": 1773, "s": 1709, "text": "This is a function that takes no argument, and returns nothing." }, { "code": null, "e": 1885, "s": 1773, "text": "Here this function is not taking any input argument, and also the return type is void. So this returns nothing." }, { "code": null, "e": 2083, "s": 1885, "text": "#include <stdio.h>\nint my_function() {\n printf(\"This function takes no argument, But returns 50\\n\");\n return 50;\n}\nmain() {\n int x;\n x = my_function();\n printf(\"Returned Value: %d\", x);\n}" }, { "code": null, "e": 2150, "s": 2083, "text": "This function takes no argument, But returns 50\nReturned Value: 50" }, { "code": null, "e": 2256, "s": 2150, "text": "Here this function is not taking any input argument, but its return type is int. So this returns a value." }, { "code": null, "e": 2445, "s": 2256, "text": "#include <stdio.h>\nvoid my_function(int x) {\n printf(\"This function is taking %d as argument, but returns nothing\", x);\n return 50;\n}\nmain() {\n int x;\n x = 10;\n my_function(x);\n}" }, { "code": null, "e": 2505, "s": 2445, "text": "This function is taking 10 as argument, but returns nothing" }, { "code": null, "e": 2607, "s": 2505, "text": "Here this function is taking an input argument, but its return type is void. So this returns nothing." }, { "code": null, "e": 2849, "s": 2607, "text": "#include <stdio.h>\nint my_function(int x) {\n printf(\"This will take an argument, and will return its squared value\\n\");\n return x * x;\n}\nmain() {\n int x, res;\n x = 12;\n res = my_function(12);\n printf(\"Returned Value: %d\", res);\n}" }, { "code": null, "e": 2909, "s": 2849, "text": "This function is taking 10 as argument, but returns nothing" }, { "code": null, "e": 2982, "s": 2909, "text": "Here this function is taking any input argument, and also returns value." } ]
C++ Program for Find k pairs with smallest sums in two arrays - GeeksforGeeks
25 Jan, 2022 Given two integer arrays arr1[] and arr2[] sorted in ascending order and an integer k. Find k pairs with smallest sums such that one element of a pair belongs to arr1[] and other element belongs to arr2[]Examples: Input : arr1[] = {1, 7, 11} arr2[] = {2, 4, 6} k = 3 Output : [1, 2], [1, 4], [1, 6] Explanation: The first 3 pairs are returned from the sequence [1, 2], [1, 4], [1, 6], [7, 2], [7, 4], [11, 2], [7, 6], [11, 4], [11, 6] Method 1 (Simple) Find all pairs and store their sums. Time complexity of this step is O(n1 * n2) where n1 and n2 are sizes of input arrays.Then sort pairs according to sum. Time complexity of this step is O(n1 * n2 * log (n1 * n2)) Find all pairs and store their sums. Time complexity of this step is O(n1 * n2) where n1 and n2 are sizes of input arrays. Then sort pairs according to sum. Time complexity of this step is O(n1 * n2 * log (n1 * n2)) Overall Time Complexity : O(n1 * n2 * log (n1 * n2))Method 2 (Efficient): We one by one find k smallest sum pairs, starting from least sum pair. The idea is to keep track of all elements of arr2[] which have been already considered for every element arr1[i1] so that in an iteration we only consider next element. For this purpose, we use an index array index2[] to track the indexes of next elements in the other array. It simply means that which element of second array to be added with the element of first array in each and every iteration. We increment value in index array for the element that forms next minimum value pair. C++ // C++ program to prints first k pairs with least sum from two// arrays.#include<bits/stdc++.h> using namespace std; // Function to find k pairs with least sum such// that one element of a pair is from arr1[] and// other element is from arr2[]void kSmallestPair(int arr1[], int n1, int arr2[], int n2, int k){ if (k > n1*n2) { cout << "k pairs don't exist"; return ; } // Stores current index in arr2[] for // every element of arr1[]. Initially // all values are considered 0. // Here current index is the index before // which all elements are considered as // part of output. int index2[n1]; memset(index2, 0, sizeof(index2)); while (k > 0) { // Initialize current pair sum as infinite int min_sum = INT_MAX; int min_index = 0; // To pick next pair, traverse for all elements // of arr1[], for every element, find corresponding // current element in arr2[] and pick minimum of // all formed pairs. for (int i1 = 0; i1 < n1; i1++) { // Check if current element of arr1[] plus // element of array2 to be used gives minimum // sum if (index2[i1] < n2 && arr1[i1] + arr2[index2[i1]] < min_sum) { // Update index that gives minimum min_index = i1; // update minimum sum min_sum = arr1[i1] + arr2[index2[i1]]; } } cout << "(" << arr1[min_index] << ", " << arr2[index2[min_index]] << ") "; index2[min_index]++; k--; }} // Driver codeint main(){ int arr1[] = {1, 3, 11}; int n1 = sizeof(arr1) / sizeof(arr1[0]); int arr2[] = {2, 4, 8}; int n2 = sizeof(arr2) / sizeof(arr2[0]); int k = 4; kSmallestPair( arr1, n1, arr2, n2, k); return 0;} (1, 2) (1, 4) (3, 2) (3, 4) Time Complexity : O(k*n1)Method 3 : Using Sorting, Min heap, Map Instead of brute forcing through all the possible sum combinations we should find a way to limit our search space to possible candidate sum combinations. Sort both arrays array A and array B.Create a min heap i.e priority_queue in C++ to store the sum combinations along with the indices of elements from both arrays A and B which make up the sum. Heap is ordered by the sum.Initialize the heap with the minimum possible sum combination i.e (A[0] + B[0]) and with the indices of elements from both arrays (0, 0). The tuple inside min heap will be (A[0] + B[0], 0, 0). Heap is ordered by first value i.e sum of both elements.Pop the heap to get the current smallest sum and along with the indices of the element that make up the sum. Let the tuple be (sum, i, j). Next insert (A[i + 1] + B[j], i + 1, j) and (A[i] + B[j + 1], i, j + 1) into the min heap but make sure that the pair of indices i.e (i + 1, j) and (i, j + 1) are not already present in the min heap.To check this we can use set in C++.Go back to 4 until K times. Sort both arrays array A and array B. Create a min heap i.e priority_queue in C++ to store the sum combinations along with the indices of elements from both arrays A and B which make up the sum. Heap is ordered by the sum. Initialize the heap with the minimum possible sum combination i.e (A[0] + B[0]) and with the indices of elements from both arrays (0, 0). The tuple inside min heap will be (A[0] + B[0], 0, 0). Heap is ordered by first value i.e sum of both elements. Pop the heap to get the current smallest sum and along with the indices of the element that make up the sum. Let the tuple be (sum, i, j). Next insert (A[i + 1] + B[j], i + 1, j) and (A[i] + B[j + 1], i, j + 1) into the min heap but make sure that the pair of indices i.e (i + 1, j) and (i, j + 1) are not already present in the min heap.To check this we can use set in C++.Go back to 4 until K times. Next insert (A[i + 1] + B[j], i + 1, j) and (A[i] + B[j + 1], i, j + 1) into the min heap but make sure that the pair of indices i.e (i + 1, j) and (i, j + 1) are not already present in the min heap.To check this we can use set in C++. Go back to 4 until K times. C++ // C++ program to Prints// first k pairs with// least sum from two arrays. #include <bits/stdc++.h>using namespace std; // Function to find k pairs// with least sum such// that one element of a pair// is from arr1[] and// other element is from arr2[]void kSmallestPair(vector<int> A, vector<int> B, int K){ sort(A.begin(), A.end()); sort(B.begin(), B.end()); int n = A.size(); // Min heap which contains tuple of the format // (sum, (i, j)) i and j are the indices // of the elements from array A // and array B which make up the sum. priority_queue<pair<int, pair<int, int> >, vector<pair<int, pair<int, int> > >, greater<pair<int, pair<int, int> > > > pq; // my_set is used to store the indices of // the pair(i, j) we use my_set to make sure // the indices doe not repeat inside min heap. set<pair<int, int> > my_set; // initialize the heap with the minimum sum // combination i.e. (A[0] + B[0]) // and also push indices (0,0) along // with sum. pq.push(make_pair(A[0] + B[0], make_pair(0, 0))); my_set.insert(make_pair(0, 0)); // iterate upto K int flag=1; for (int count = 0; count < K && flag; count++) { // tuple format (sum, i, j). pair<int, pair<int, int> > temp = pq.top(); pq.pop(); int i = temp.second.first; int j = temp.second.second; cout << "(" << A[i] << ", " << B[j] << ")" << endl; // Extracting pair with least sum such // that one element is from arr1 and // another is from arr2 // check if i+1 is in the range of our first array A flag=0; if (i + 1 < A.size()) { int sum = A[i + 1] + B[j]; // insert (A[i + 1] + B[j], (i + 1, j)) // into min heap. pair<int, int> temp1 = make_pair(i + 1, j); // insert only if the pair (i + 1, j) is // not already present inside the map i.e. // no repeating pair should be present inside // the heap. if (my_set.find(temp1) == my_set.end()) { pq.push(make_pair(sum, temp1)); my_set.insert(temp1); } flag=1; } // check if j+1 is in the range of our second array // B if (j + 1 < B.size()) { // insert (A[i] + B[j + 1], (i, j + 1)) // into min heap. int sum = A[i] + B[j + 1]; pair<int, int> temp1 = make_pair(i, j + 1); // insert only if the pair (i, j + 1) // is not present inside the heap. if (my_set.find(temp1) == my_set.end()) { pq.push(make_pair(sum, temp1)); my_set.insert(temp1); } flag=1; } }} // Driver Code.int main(){ vector<int> A = { 1 }; vector<int> B = { 2, 4, 5, 9 }; int K = 3; kSmallestPair(A, B, K); return 0;} // This code is contributed by Dhairya. (1, 2) (1, 4) (1, 5) Time Complexity : O(n*logn) assuming k<=nPlease refer complete article on Find k pairs with smallest sums in two arrays for more details! varshagumber28 Order-Statistics Arrays C++ C++ Programs Arrays CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Next Greater Element Window Sliding Technique Count pairs with given sum Program to find sum of elements in a given array Reversal algorithm for array rotation Vector in C++ STL Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) Inheritance in C++ std::sort() in C++ STL
[ { "code": null, "e": 24405, "s": 24377, "text": "\n25 Jan, 2022" }, { "code": null, "e": 24620, "s": 24405, "text": "Given two integer arrays arr1[] and arr2[] sorted in ascending order and an integer k. Find k pairs with smallest sums such that one element of a pair belongs to arr1[] and other element belongs to arr2[]Examples: " }, { "code": null, "e": 24881, "s": 24620, "text": "Input : arr1[] = {1, 7, 11}\n arr2[] = {2, 4, 6}\n k = 3\nOutput : [1, 2],\n [1, 4],\n [1, 6]\nExplanation: The first 3 pairs are returned \nfrom the sequence [1, 2], [1, 4], [1, 6], \n[7, 2], [7, 4], [11, 2], [7, 6], [11, 4], \n[11, 6]" }, { "code": null, "e": 24901, "s": 24881, "text": "Method 1 (Simple) " }, { "code": null, "e": 25116, "s": 24901, "text": "Find all pairs and store their sums. Time complexity of this step is O(n1 * n2) where n1 and n2 are sizes of input arrays.Then sort pairs according to sum. Time complexity of this step is O(n1 * n2 * log (n1 * n2))" }, { "code": null, "e": 25239, "s": 25116, "text": "Find all pairs and store their sums. Time complexity of this step is O(n1 * n2) where n1 and n2 are sizes of input arrays." }, { "code": null, "e": 25332, "s": 25239, "text": "Then sort pairs according to sum. Time complexity of this step is O(n1 * n2 * log (n1 * n2))" }, { "code": null, "e": 25965, "s": 25332, "text": "Overall Time Complexity : O(n1 * n2 * log (n1 * n2))Method 2 (Efficient): We one by one find k smallest sum pairs, starting from least sum pair. The idea is to keep track of all elements of arr2[] which have been already considered for every element arr1[i1] so that in an iteration we only consider next element. For this purpose, we use an index array index2[] to track the indexes of next elements in the other array. It simply means that which element of second array to be added with the element of first array in each and every iteration. We increment value in index array for the element that forms next minimum value pair. " }, { "code": null, "e": 25969, "s": 25965, "text": "C++" }, { "code": "// C++ program to prints first k pairs with least sum from two// arrays.#include<bits/stdc++.h> using namespace std; // Function to find k pairs with least sum such// that one element of a pair is from arr1[] and// other element is from arr2[]void kSmallestPair(int arr1[], int n1, int arr2[], int n2, int k){ if (k > n1*n2) { cout << \"k pairs don't exist\"; return ; } // Stores current index in arr2[] for // every element of arr1[]. Initially // all values are considered 0. // Here current index is the index before // which all elements are considered as // part of output. int index2[n1]; memset(index2, 0, sizeof(index2)); while (k > 0) { // Initialize current pair sum as infinite int min_sum = INT_MAX; int min_index = 0; // To pick next pair, traverse for all elements // of arr1[], for every element, find corresponding // current element in arr2[] and pick minimum of // all formed pairs. for (int i1 = 0; i1 < n1; i1++) { // Check if current element of arr1[] plus // element of array2 to be used gives minimum // sum if (index2[i1] < n2 && arr1[i1] + arr2[index2[i1]] < min_sum) { // Update index that gives minimum min_index = i1; // update minimum sum min_sum = arr1[i1] + arr2[index2[i1]]; } } cout << \"(\" << arr1[min_index] << \", \" << arr2[index2[min_index]] << \") \"; index2[min_index]++; k--; }} // Driver codeint main(){ int arr1[] = {1, 3, 11}; int n1 = sizeof(arr1) / sizeof(arr1[0]); int arr2[] = {2, 4, 8}; int n2 = sizeof(arr2) / sizeof(arr2[0]); int k = 4; kSmallestPair( arr1, n1, arr2, n2, k); return 0;}", "e": 27866, "s": 25969, "text": null }, { "code": null, "e": 27895, "s": 27866, "text": "(1, 2) (1, 4) (3, 2) (3, 4) " }, { "code": null, "e": 28116, "s": 27895, "text": "Time Complexity : O(k*n1)Method 3 : Using Sorting, Min heap, Map Instead of brute forcing through all the possible sum combinations we should find a way to limit our search space to possible candidate sum combinations. " }, { "code": null, "e": 28988, "s": 28116, "text": "Sort both arrays array A and array B.Create a min heap i.e priority_queue in C++ to store the sum combinations along with the indices of elements from both arrays A and B which make up the sum. Heap is ordered by the sum.Initialize the heap with the minimum possible sum combination i.e (A[0] + B[0]) and with the indices of elements from both arrays (0, 0). The tuple inside min heap will be (A[0] + B[0], 0, 0). Heap is ordered by first value i.e sum of both elements.Pop the heap to get the current smallest sum and along with the indices of the element that make up the sum. Let the tuple be (sum, i, j). Next insert (A[i + 1] + B[j], i + 1, j) and (A[i] + B[j + 1], i, j + 1) into the min heap but make sure that the pair of indices i.e (i + 1, j) and (i, j + 1) are not already present in the min heap.To check this we can use set in C++.Go back to 4 until K times." }, { "code": null, "e": 29026, "s": 28988, "text": "Sort both arrays array A and array B." }, { "code": null, "e": 29211, "s": 29026, "text": "Create a min heap i.e priority_queue in C++ to store the sum combinations along with the indices of elements from both arrays A and B which make up the sum. Heap is ordered by the sum." }, { "code": null, "e": 29461, "s": 29211, "text": "Initialize the heap with the minimum possible sum combination i.e (A[0] + B[0]) and with the indices of elements from both arrays (0, 0). The tuple inside min heap will be (A[0] + B[0], 0, 0). Heap is ordered by first value i.e sum of both elements." }, { "code": null, "e": 29863, "s": 29461, "text": "Pop the heap to get the current smallest sum and along with the indices of the element that make up the sum. Let the tuple be (sum, i, j). Next insert (A[i + 1] + B[j], i + 1, j) and (A[i] + B[j + 1], i, j + 1) into the min heap but make sure that the pair of indices i.e (i + 1, j) and (i, j + 1) are not already present in the min heap.To check this we can use set in C++.Go back to 4 until K times." }, { "code": null, "e": 30099, "s": 29863, "text": "Next insert (A[i + 1] + B[j], i + 1, j) and (A[i] + B[j + 1], i, j + 1) into the min heap but make sure that the pair of indices i.e (i + 1, j) and (i, j + 1) are not already present in the min heap.To check this we can use set in C++." }, { "code": null, "e": 30127, "s": 30099, "text": "Go back to 4 until K times." }, { "code": null, "e": 30131, "s": 30127, "text": "C++" }, { "code": "// C++ program to Prints// first k pairs with// least sum from two arrays. #include <bits/stdc++.h>using namespace std; // Function to find k pairs// with least sum such// that one element of a pair// is from arr1[] and// other element is from arr2[]void kSmallestPair(vector<int> A, vector<int> B, int K){ sort(A.begin(), A.end()); sort(B.begin(), B.end()); int n = A.size(); // Min heap which contains tuple of the format // (sum, (i, j)) i and j are the indices // of the elements from array A // and array B which make up the sum. priority_queue<pair<int, pair<int, int> >, vector<pair<int, pair<int, int> > >, greater<pair<int, pair<int, int> > > > pq; // my_set is used to store the indices of // the pair(i, j) we use my_set to make sure // the indices doe not repeat inside min heap. set<pair<int, int> > my_set; // initialize the heap with the minimum sum // combination i.e. (A[0] + B[0]) // and also push indices (0,0) along // with sum. pq.push(make_pair(A[0] + B[0], make_pair(0, 0))); my_set.insert(make_pair(0, 0)); // iterate upto K int flag=1; for (int count = 0; count < K && flag; count++) { // tuple format (sum, i, j). pair<int, pair<int, int> > temp = pq.top(); pq.pop(); int i = temp.second.first; int j = temp.second.second; cout << \"(\" << A[i] << \", \" << B[j] << \")\" << endl; // Extracting pair with least sum such // that one element is from arr1 and // another is from arr2 // check if i+1 is in the range of our first array A flag=0; if (i + 1 < A.size()) { int sum = A[i + 1] + B[j]; // insert (A[i + 1] + B[j], (i + 1, j)) // into min heap. pair<int, int> temp1 = make_pair(i + 1, j); // insert only if the pair (i + 1, j) is // not already present inside the map i.e. // no repeating pair should be present inside // the heap. if (my_set.find(temp1) == my_set.end()) { pq.push(make_pair(sum, temp1)); my_set.insert(temp1); } flag=1; } // check if j+1 is in the range of our second array // B if (j + 1 < B.size()) { // insert (A[i] + B[j + 1], (i, j + 1)) // into min heap. int sum = A[i] + B[j + 1]; pair<int, int> temp1 = make_pair(i, j + 1); // insert only if the pair (i, j + 1) // is not present inside the heap. if (my_set.find(temp1) == my_set.end()) { pq.push(make_pair(sum, temp1)); my_set.insert(temp1); } flag=1; } }} // Driver Code.int main(){ vector<int> A = { 1 }; vector<int> B = { 2, 4, 5, 9 }; int K = 3; kSmallestPair(A, B, K); return 0;} // This code is contributed by Dhairya.", "e": 33130, "s": 30131, "text": null }, { "code": null, "e": 33154, "s": 33133, "text": "(1, 2)\n(1, 4)\n(1, 5)" }, { "code": null, "e": 33295, "s": 33156, "text": "Time Complexity : O(n*logn) assuming k<=nPlease refer complete article on Find k pairs with smallest sums in two arrays for more details! " }, { "code": null, "e": 33310, "s": 33295, "text": "varshagumber28" }, { "code": null, "e": 33327, "s": 33310, "text": "Order-Statistics" }, { "code": null, "e": 33334, "s": 33327, "text": "Arrays" }, { "code": null, "e": 33338, "s": 33334, "text": "C++" }, { "code": null, "e": 33351, "s": 33338, "text": "C++ Programs" }, { "code": null, "e": 33358, "s": 33351, "text": "Arrays" }, { "code": null, "e": 33362, "s": 33358, "text": "CPP" }, { "code": null, "e": 33460, "s": 33362, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33469, "s": 33460, "text": "Comments" }, { "code": null, "e": 33482, "s": 33469, "text": "Old Comments" }, { "code": null, "e": 33503, "s": 33482, "text": "Next Greater Element" }, { "code": null, "e": 33528, "s": 33503, "text": "Window Sliding Technique" }, { "code": null, "e": 33555, "s": 33528, "text": "Count pairs with given sum" }, { "code": null, "e": 33604, "s": 33555, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 33642, "s": 33604, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 33660, "s": 33642, "text": "Vector in C++ STL" }, { "code": null, "e": 33706, "s": 33660, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 33749, "s": 33706, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 33768, "s": 33749, "text": "Inheritance in C++" } ]
How to display square root sign in base R plot?
To display square root sign in base R plot, we can follow the below steps − First of all, create a plot having square root values to display default visualisation. First of all, create a plot having square root values to display default visualisation. Then, create the plot with expression function to display square root sign in the plot. Then, create the plot with expression function to display square root sign in the plot. Using plot function to create a plot in base R with square root values as shown below − x<-1:10 y<-sqrt(x) plot(x,y) Display square root sign in the plot Create the plot with plot and expression function to display square root sign in the plot as shown below − x<-1:10 y<-sqrt(x) plot(x,y,ylab=expression(sqrt(x)))
[ { "code": null, "e": 1138, "s": 1062, "text": "To display square root sign in base R plot, we can follow the below steps −" }, { "code": null, "e": 1226, "s": 1138, "text": "First of all, create a plot having square root values to display default visualisation." }, { "code": null, "e": 1314, "s": 1226, "text": "First of all, create a plot having square root values to display default visualisation." }, { "code": null, "e": 1402, "s": 1314, "text": "Then, create the plot with expression function to display square root sign in the plot." }, { "code": null, "e": 1490, "s": 1402, "text": "Then, create the plot with expression function to display square root sign in the plot." }, { "code": null, "e": 1578, "s": 1490, "text": "Using plot function to create a plot in base R with square root values as shown below −" }, { "code": null, "e": 1607, "s": 1578, "text": "x<-1:10\ny<-sqrt(x)\nplot(x,y)" }, { "code": null, "e": 1644, "s": 1607, "text": "Display square root sign in the plot" }, { "code": null, "e": 1751, "s": 1644, "text": "Create the plot with plot and expression function to display square root sign in the plot as shown below −" }, { "code": null, "e": 1805, "s": 1751, "text": "x<-1:10\ny<-sqrt(x)\nplot(x,y,ylab=expression(sqrt(x)))" } ]
Zend Framework - Email Management
The Zend Framework provides a separate component called as zend-mail to send email messages. The zend-mail component also provides an option to read and write email messages with attachments both in text and html format. Sending an email in Zend is much easier and simple to configure. Let us go through the email concepts, basic settings, advanced settings such as SMTP transport, etc., in this chapter. The mail component can be installed using the following Composer command. composer require zendframework/zend-mail A basic email consists of one or more recipients, a subject, a body and a sender. Zend provides Zend\Mail\Message class to create a new email message. To send an email using the zend-mail, you must specify at least one recipient as well as a message body. The partial code to create a new mail message is as follows − use Zend\Mail; $mail = new Mail\Message(); $mail->setSubject('Zend email sample'); $mail->setBody('This is content of the mail message'); $mail->setFrom('sender@example.com', "sender-name"); $mail->addTo('recipient@test.com', "recipient-name"); Zend provides Zend\Mail\Sendmail class to send the mail message. Sendmail uses the php native mail function, mail to send the mail message and we can configure the transport layer using php configuration file. The partial coding using Sendmail is as follow − $transport = new Mail\Transport\Sendmail(); $transport->send($mail); The zend-mail provides many transport layer and each may require many additional parameters such as username, password, etc Some of the notable email management methods are as follows − isValid − Messages without a ‘From’ address is invalid. isValid − Messages without a ‘From’ address is invalid. isValid() : bool setEncoding − Set the message encoding. setEncoding − Set the message encoding. setEncoding(string $encoding) : void getEncoding − Get the message encoding. getEncoding − Get the message encoding. getEncoding() : string setHeaders − Compose headers. setHeaders − Compose headers. setHeaders(Zend\Mail\Headers $headers) : void getHeaders − Access headers collection. getHeaders − Access headers collection. getHeaders() : Zend\Mail\Headers setFrom − Set (overwrite) From addresses. It contains a key/value pairs where the key is the human readable name and the value is the email address. setFrom − Set (overwrite) From addresses. It contains a key/value pairs where the key is the human readable name and the value is the email address. setFrom( string|AddressInterface|array|AddressList|Traversable $emailOrAddressList, string|null $name ) : void addFrom − Add a ‘From’ address. addFrom − Add a ‘From’ address. addFrom( string|AddressInterface|array|AddressList|Traversable $emailOrAddressOrList, string|null $name ) : void getFrom − Retrieve list of ‘From’ senders. getFrom − Retrieve list of ‘From’ senders. getFrom() : AddressList setTo - Overwrite the address list in the To recipients. setTo( string|AddressInterface|array|AddressList|Traversable $emailOrAddressList, null|string $name ) : void setSubject − Set the message subject header value. setSubject − Set the message subject header value. setSubject(string $subject) :void setBody − Set the message body. setBody − Set the message body. setBody(null|string|Zend\Mime\Message|object $body) : void The zend-mail provides options to send an email using the SMTP server through the Zend\Mail\Transport\Smtpclass. It is like Sendmail except that it has a few additional options to configure the SMTP host, port, username, password, etc. The partial code is as follows − use Zend\Mail\Transport\Smtp as SmtpTransport; use Zend\Mail\Transport\SmtpOptions; $transport = new SmtpTransport(); $options = new SmtpOptions([ 'name' => 'localhost', 'host' =>'smtp.gmail.com', 'port' => 465, ]); $transport->setOptions($options); Here, name − Name of the SMTP host. name − Name of the SMTP host. host − Remote hostname or IP address. host − Remote hostname or IP address. port − Port on which the remote host is listening. port − Port on which the remote host is listening. Let us follow the following points to write a simple php console application to understand the mail concept. Create a folder “mailapp”. Create a folder “mailapp”. Install zend-mail using the composer tool. Install zend-mail using the composer tool. Create a php file Mail.php inside the “mailapp” folder. Create a php file Mail.php inside the “mailapp” folder. Create the message using the Zend\Mail\Message. Create the message using the Zend\Mail\Message. $message = new Message(); $message->addTo('user1@gmail.com'); $message->addFrom('user2@gmail.com'); $message->setSubject('Hello!'); $message->setBody("My first Zend-mail application!"); Create the SMTP transport layer and add the necessary configuration. Create the SMTP transport layer and add the necessary configuration. // Setup SMTP transport using LOGIN authentication $transport = new SmtpTransport(); $options = new SmtpOptions([ 'name' => 'localhost', 'host' => 'smtp.gmail.com', // or any SMTP server 'port' => 465, // port on which the SMTP server is listening 'connection_class' => 'login', 'connection_config' => [ username' => '<your username>', 'password' => '<your password>', 'ssl' => 'ssl'], ]); $transport->setOptions($options); Send the email using the send method. Send the email using the send method. $transport->send($message); The complete listing, Mail.php is as follows − <?php require __DIR__ . '/vendor/autoload.php'; use Zend\Mail\Message; use Zend\Mail\Transport\Smtp as SmtpTransport; use Zend\Mail\Transport\SmtpOptions; $message = new Message(); $message->addTo('user1@gmail.com'); $message->addFrom('user2@gmail.com'); $message->setSubject('Hello!'); $message->setBody("My first Zend-mail application!"); // Setup SMTP transport using LOGIN authentication $transport = new SmtpTransport(); $options = new SmtpOptions([ 'name' => 'localhost', 'host' => 'smtp.gmail.com', // or any SMTP server 'port' => 465, // port on which the SMTP server is listening 'connection_class' => 'login', 'connection_config' => [ 'username' => '<your username>', 'password' => '<your password>', 'ssl' => 'ssl'], ]); $transport->setOptions($options); $transport->send($message); Now, run the application in the command prompt php Mail.php. This will send the mail as configured in the application. Print Add Notes Bookmark this page
[ { "code": null, "e": 2598, "s": 2312, "text": "The Zend Framework provides a separate component called as zend-mail to send email messages. The zend-mail component also provides an option to read and write email messages with attachments both in text and html format. Sending an email in Zend is much easier and simple to configure." }, { "code": null, "e": 2717, "s": 2598, "text": "Let us go through the email concepts, basic settings, advanced settings such as SMTP transport, etc., in this chapter." }, { "code": null, "e": 2791, "s": 2717, "text": "The mail component can be installed using the following Composer command." }, { "code": null, "e": 2833, "s": 2791, "text": "composer require zendframework/zend-mail\n" }, { "code": null, "e": 3089, "s": 2833, "text": "A basic email consists of one or more recipients, a subject, a body and a sender. Zend provides Zend\\Mail\\Message class to create a new email message. To send an email using the zend-mail, you must specify at least one recipient as well as a message body." }, { "code": null, "e": 3151, "s": 3089, "text": "The partial code to create a new mail message is as follows −" }, { "code": null, "e": 3401, "s": 3151, "text": "use Zend\\Mail;\n$mail = new Mail\\Message(); \n$mail->setSubject('Zend email sample'); \n$mail->setBody('This is content of the mail message'); \n$mail->setFrom('sender@example.com', \"sender-name\"); \n$mail->addTo('recipient@test.com', \"recipient-name\"); " }, { "code": null, "e": 3611, "s": 3401, "text": "Zend provides Zend\\Mail\\Sendmail class to send the mail message. Sendmail uses the php native mail function, mail to send the mail message and we can configure the transport layer using php configuration file." }, { "code": null, "e": 3660, "s": 3611, "text": "The partial coding using Sendmail is as follow −" }, { "code": null, "e": 3730, "s": 3660, "text": "$transport = new Mail\\Transport\\Sendmail(); \n$transport->send($mail);" }, { "code": null, "e": 3854, "s": 3730, "text": "The zend-mail provides many transport layer and each may require many additional parameters such as username, password, etc" }, { "code": null, "e": 3916, "s": 3854, "text": "Some of the notable email management methods are as follows −" }, { "code": null, "e": 3972, "s": 3916, "text": "isValid − Messages without a ‘From’ address is invalid." }, { "code": null, "e": 4028, "s": 3972, "text": "isValid − Messages without a ‘From’ address is invalid." }, { "code": null, "e": 4046, "s": 4028, "text": "isValid() : bool\n" }, { "code": null, "e": 4086, "s": 4046, "text": "setEncoding − Set the message encoding." }, { "code": null, "e": 4126, "s": 4086, "text": "setEncoding − Set the message encoding." }, { "code": null, "e": 4164, "s": 4126, "text": "setEncoding(string $encoding) : void\n" }, { "code": null, "e": 4204, "s": 4164, "text": "getEncoding − Get the message encoding." }, { "code": null, "e": 4244, "s": 4204, "text": "getEncoding − Get the message encoding." }, { "code": null, "e": 4268, "s": 4244, "text": "getEncoding() : string\n" }, { "code": null, "e": 4298, "s": 4268, "text": "setHeaders − Compose headers." }, { "code": null, "e": 4328, "s": 4298, "text": "setHeaders − Compose headers." }, { "code": null, "e": 4375, "s": 4328, "text": "setHeaders(Zend\\Mail\\Headers $headers) : void\n" }, { "code": null, "e": 4415, "s": 4375, "text": "getHeaders − Access headers collection." }, { "code": null, "e": 4455, "s": 4415, "text": "getHeaders − Access headers collection." }, { "code": null, "e": 4489, "s": 4455, "text": "getHeaders() : Zend\\Mail\\Headers\n" }, { "code": null, "e": 4638, "s": 4489, "text": "setFrom − Set (overwrite) From addresses. It contains a key/value pairs where the key is the human readable name and the value is the email address." }, { "code": null, "e": 4787, "s": 4638, "text": "setFrom − Set (overwrite) From addresses. It contains a key/value pairs where the key is the human readable name and the value is the email address." }, { "code": null, "e": 4911, "s": 4787, "text": "setFrom( \n string|AddressInterface|array|AddressList|Traversable $emailOrAddressList, \n string|null $name \n) : void " }, { "code": null, "e": 4944, "s": 4911, "text": "addFrom − Add a ‘From’ address.\n" }, { "code": null, "e": 4976, "s": 4944, "text": "addFrom − Add a ‘From’ address." }, { "code": null, "e": 5102, "s": 4976, "text": "addFrom( \n string|AddressInterface|array|AddressList|Traversable $emailOrAddressOrList, \n string|null $name \n) : void " }, { "code": null, "e": 5145, "s": 5102, "text": "getFrom − Retrieve list of ‘From’ senders." }, { "code": null, "e": 5188, "s": 5145, "text": "getFrom − Retrieve list of ‘From’ senders." }, { "code": null, "e": 5393, "s": 5188, "text": "getFrom() : AddressList \nsetTo - Overwrite the address list in the To recipients. \nsetTo( \n string|AddressInterface|array|AddressList|Traversable $emailOrAddressList, \n null|string $name \n) : void " }, { "code": null, "e": 5444, "s": 5393, "text": "setSubject − Set the message subject header value." }, { "code": null, "e": 5495, "s": 5444, "text": "setSubject − Set the message subject header value." }, { "code": null, "e": 5531, "s": 5495, "text": "setSubject(string $subject) :void \n" }, { "code": null, "e": 5563, "s": 5531, "text": "setBody − Set the message body." }, { "code": null, "e": 5595, "s": 5563, "text": "setBody − Set the message body." }, { "code": null, "e": 5656, "s": 5595, "text": "setBody(null|string|Zend\\Mime\\Message|object $body) : void \n" }, { "code": null, "e": 5892, "s": 5656, "text": "The zend-mail provides options to send an email using the SMTP server through the Zend\\Mail\\Transport\\Smtpclass. It is like Sendmail except that it has a few additional options to configure the SMTP host, port, username, password, etc." }, { "code": null, "e": 5925, "s": 5892, "text": "The partial code is as follows −" }, { "code": null, "e": 6194, "s": 5925, "text": "use Zend\\Mail\\Transport\\Smtp as SmtpTransport; \nuse Zend\\Mail\\Transport\\SmtpOptions; \n$transport = new SmtpTransport(); \n$options = new SmtpOptions([ \n 'name' => 'localhost', \n 'host' =>'smtp.gmail.com', \n 'port' => 465, \n]); \n$transport->setOptions($options); " }, { "code": null, "e": 6200, "s": 6194, "text": "Here," }, { "code": null, "e": 6230, "s": 6200, "text": "name − Name of the SMTP host." }, { "code": null, "e": 6260, "s": 6230, "text": "name − Name of the SMTP host." }, { "code": null, "e": 6298, "s": 6260, "text": "host − Remote hostname or IP address." }, { "code": null, "e": 6336, "s": 6298, "text": "host − Remote hostname or IP address." }, { "code": null, "e": 6387, "s": 6336, "text": "port − Port on which the remote host is listening." }, { "code": null, "e": 6438, "s": 6387, "text": "port − Port on which the remote host is listening." }, { "code": null, "e": 6547, "s": 6438, "text": "Let us follow the following points to write a simple php console application to understand the mail concept." }, { "code": null, "e": 6574, "s": 6547, "text": "Create a folder “mailapp”." }, { "code": null, "e": 6601, "s": 6574, "text": "Create a folder “mailapp”." }, { "code": null, "e": 6644, "s": 6601, "text": "Install zend-mail using the composer tool." }, { "code": null, "e": 6687, "s": 6644, "text": "Install zend-mail using the composer tool." }, { "code": null, "e": 6743, "s": 6687, "text": "Create a php file Mail.php inside the “mailapp” folder." }, { "code": null, "e": 6799, "s": 6743, "text": "Create a php file Mail.php inside the “mailapp” folder." }, { "code": null, "e": 6847, "s": 6799, "text": "Create the message using the Zend\\Mail\\Message." }, { "code": null, "e": 6895, "s": 6847, "text": "Create the message using the Zend\\Mail\\Message." }, { "code": null, "e": 7087, "s": 6895, "text": "$message = new Message(); \n$message->addTo('user1@gmail.com'); \n$message->addFrom('user2@gmail.com'); \n$message->setSubject('Hello!'); \n$message->setBody(\"My first Zend-mail application!\"); \n" }, { "code": null, "e": 7156, "s": 7087, "text": "Create the SMTP transport layer and add the necessary configuration." }, { "code": null, "e": 7225, "s": 7156, "text": "Create the SMTP transport layer and add the necessary configuration." }, { "code": null, "e": 7688, "s": 7225, "text": "// Setup SMTP transport using LOGIN authentication \n$transport = new SmtpTransport(); \n$options = new SmtpOptions([ \n 'name' => 'localhost', \n 'host' => 'smtp.gmail.com', // or any SMTP server \n 'port' => 465, // port on which the SMTP server is listening \n 'connection_class' => 'login', \n 'connection_config' => [ \n username' => '<your username>', 'password' => '<your password>', \n 'ssl' => 'ssl'], \n]); \n$transport->setOptions($options); " }, { "code": null, "e": 7726, "s": 7688, "text": "Send the email using the send method." }, { "code": null, "e": 7764, "s": 7726, "text": "Send the email using the send method." }, { "code": null, "e": 7793, "s": 7764, "text": "$transport->send($message);\n" }, { "code": null, "e": 7840, "s": 7793, "text": "The complete listing, Mail.php is as follows −" }, { "code": null, "e": 8694, "s": 7840, "text": "<?php \nrequire __DIR__ . '/vendor/autoload.php'; \n\nuse Zend\\Mail\\Message; \nuse Zend\\Mail\\Transport\\Smtp as SmtpTransport; \nuse Zend\\Mail\\Transport\\SmtpOptions; \n \n$message = new Message(); \n$message->addTo('user1@gmail.com'); \n$message->addFrom('user2@gmail.com'); \n$message->setSubject('Hello!'); \n$message->setBody(\"My first Zend-mail application!\"); \n \n// Setup SMTP transport using LOGIN authentication \n$transport = new SmtpTransport(); \n$options = new SmtpOptions([ \n 'name' => 'localhost', \n 'host' => 'smtp.gmail.com', // or any SMTP server \n 'port' => 465, // port on which the SMTP server is listening \n 'connection_class' => 'login', \n 'connection_config' => [ \n 'username' => '<your username>', 'password' => '<your password>', \n 'ssl' => 'ssl'], \n]); \n$transport->setOptions($options); \n$transport->send($message);" }, { "code": null, "e": 8813, "s": 8694, "text": "Now, run the application in the command prompt php Mail.php. This will send the mail as configured in the application." }, { "code": null, "e": 8820, "s": 8813, "text": " Print" }, { "code": null, "e": 8831, "s": 8820, "text": " Add Notes" } ]
Creating a file using FileOutputStream - GeeksforGeeks
22 Dec, 2016 FileOutputStream class belongs to byte stream and stores the data in the form of individual bytes. It can be used to create text files. A file represents storage of data on a second storage media like a hard disk or CD. Whether or not a file is available or may be created depends upon the underlying platform. Some platforms, in particular, allow a file to be opened for writing by only one FileOutputStream (or other file-writing objects) at a time. In such situations, the constructors in this class will fail if the file involved is already open. FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter. Important methods: void close() : Closes this file output stream and releases any system resources associated with this stream. protected void finalize() : Cleans up the connection to the file, and ensures that the close method of this file output stream is called when there are no more references to this stream. void write(byte[] b) : Writes b.length bytes from the specified byte array to this file output stream. void write(byte[] b, int off, int len) : Writes len bytes from the specified byte array starting at offset off to this file output stream. void write(int b) : Writes the specified byte to this file output stream. Following steps are to be followed to create a text file that stores some characters (or text): Reading data: First of all, data should be read from the keyboard. For this purpose, associate the keyboard to some input stream class. The code for using DataInputSream class for reading data from the keyboard is as:DataInputStream dis =new DataInputStream(System.in);Here System.in represent the keyboard which is linked with DataInputStream objectSend data to OutputStream: Now , associate a file where the data is to be stored to some output stream. For this , take the help of FileOutputStream which can send data to the file. Attaching the file.txt to FileOutputStream can be done as:FileOutputStream fout=new FileOutputStream(“file.txt”);Reading data from DataInputStream: The next step is to read data from DataInputStream and write it into FileOutputStream . It means read data from dis object and write it into fout object, as shown here:ch=(char)dis.read(); fout.write(ch);Close the file: Finally, any file should be closed after performing input or output operations on it, else the data of the may be corrupted. Closing the file is done by closing the associated streams. For example, fout.close(): will close the FileOutputStream ,hence there is no way to write data into the file. Reading data: First of all, data should be read from the keyboard. For this purpose, associate the keyboard to some input stream class. The code for using DataInputSream class for reading data from the keyboard is as:DataInputStream dis =new DataInputStream(System.in);Here System.in represent the keyboard which is linked with DataInputStream object DataInputStream dis =new DataInputStream(System.in); Here System.in represent the keyboard which is linked with DataInputStream object Send data to OutputStream: Now , associate a file where the data is to be stored to some output stream. For this , take the help of FileOutputStream which can send data to the file. Attaching the file.txt to FileOutputStream can be done as:FileOutputStream fout=new FileOutputStream(“file.txt”); FileOutputStream fout=new FileOutputStream(“file.txt”); Reading data from DataInputStream: The next step is to read data from DataInputStream and write it into FileOutputStream . It means read data from dis object and write it into fout object, as shown here:ch=(char)dis.read(); fout.write(ch); ch=(char)dis.read(); fout.write(ch); Close the file: Finally, any file should be closed after performing input or output operations on it, else the data of the may be corrupted. Closing the file is done by closing the associated streams. For example, fout.close(): will close the FileOutputStream ,hence there is no way to write data into the file. Implementation: //Java program to demonstrate creating a text file using FileOutputStreamimport java.io.BufferedOutputStream;import java.io.DataInputStream;import java.io.FileOutputStream;import java.io.IOException;class Create_File{ public static void main(String[] args) throws IOException { //attach keyboard to DataInputStream DataInputStream dis=new DataInputStream(System.in); // attach file to FileOutputStream FileOutputStream fout=new FileOutputStream("file.txt"); //attach FileOutputStream to BufferedOutputStream BufferedOutputStream bout=new BufferedOutputStream(fout,1024); System.out.println("Enter text (@ at the end):"); char ch; //read characters from dis into ch. Then write them into bout. //repeat this as long as the read character is not @ while((ch=(char)dis.read())!='@') { bout.write(ch); } //close the file bout.close(); }} If the Program is executed again, the old data of file.txt will be lost and any recent data is only stored in the file. If we don’t want to lose the previous data of the file, and just append the new data to the end of already existing data, and this can be done by writing true along with file name. FileOutputStream fout=new FileOutputStream(“file.txt”,true); Improving Efficiency using BufferedOutputStream Normally, whenever we write data to a file using FileOutputStream as: fout.write(ch); Here, the FileOutputStream is invoked to write the characters into the file. Let us estimate the time it takes to read 100 characters from the keyboard and write all of them into a file. Let us assume data is read from the keyboard into memory using DataInputStream and it takes 1 sec to read 1 character into memory and this character is written into the file by FileOutputStream by spending another 1 sec. So for reading and writing a file will take 200 sec. This is wasting a lot of time. On the other hand, if Buffered classed are used, they provide a buffer which is first filled with characters from the buffer which can be at once written into the file. Buffered classes should be used in connection to other stream classes. First, the DataInputStream reads data from the keyboard by spending 1 sec for each character. This character is written into the buffer. Thus, to read 100 characters into a buffer, it will take 100 second time. Now FileOutputStream will write the entire buffer in a single step. So, reading and writing 100 characters took 101 sec only. In the same way, reading classes are used for improving the speed of reading operation. Attaching FileOutputStream to BufferedOutputStream as:BufferedOutputStream bout=new BufferedOutputStream(fout,1024);Here ,the buffer size is declared as 1024 bytes. If the buffer size is not specified , then a default size of 512 bytes is used BufferedOutputStream bout=new BufferedOutputStream(fout,1024); Here ,the buffer size is declared as 1024 bytes. If the buffer size is not specified , then a default size of 512 bytes is used Important methods of BufferedOutputStream Class: void flush() : Flushes this buffered output stream. void write(byte[] b, int off, int len) : Writes len bytes from the specified byte array starting at offset off to this buffered output stream. void write(int b) : Writes the specified byte to this buffered output stream. Output: C:\> javac Create_File.java C:\> java Create_File Enter text (@ at the end): This is a program to create a file @ C:/> type file.txt This is a program to create a file Related Articles: CharacterStream vs ByteStream File Class in Java File handling in Java using FileWriter and FileReader This article is contributed by Nishant Sharma. 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. Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Initialize an ArrayList in Java HashMap in Java with Examples Interfaces in Java ArrayList in Java How to iterate any Map in Java Multidimensional Arrays in Java Stack Class in Java Singleton Class in Java Set in Java Overriding in Java
[ { "code": null, "e": 24916, "s": 24888, "text": "\n22 Dec, 2016" }, { "code": null, "e": 25467, "s": 24916, "text": "FileOutputStream class belongs to byte stream and stores the data in the form of individual bytes. It can be used to create text files. A file represents storage of data on a second storage media like a hard disk or CD. Whether or not a file is available or may be created depends upon the underlying platform. Some platforms, in particular, allow a file to be opened for writing by only one FileOutputStream (or other file-writing objects) at a time. In such situations, the constructors in this class will fail if the file involved is already open." }, { "code": null, "e": 25608, "s": 25467, "text": "FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter." }, { "code": null, "e": 25627, "s": 25608, "text": "Important methods:" }, { "code": null, "e": 25736, "s": 25627, "text": "void close() : Closes this file output stream and releases any system resources associated with this stream." }, { "code": null, "e": 25923, "s": 25736, "text": "protected void finalize() : Cleans up the connection to the file, and ensures that the close method of this file output stream is called when there are no more references to this stream." }, { "code": null, "e": 26026, "s": 25923, "text": "void write(byte[] b) : Writes b.length bytes from the specified byte array to this file output stream." }, { "code": null, "e": 26165, "s": 26026, "text": "void write(byte[] b, int off, int len) : Writes len bytes from the specified byte array starting at offset off to this file output stream." }, { "code": null, "e": 26239, "s": 26165, "text": "void write(int b) : Writes the specified byte to this file output stream." }, { "code": null, "e": 26335, "s": 26239, "text": "Following steps are to be followed to create a text file that stores some characters (or text):" }, { "code": null, "e": 27531, "s": 26335, "text": "Reading data: First of all, data should be read from the keyboard. For this purpose, associate the keyboard to some input stream class. The code for using DataInputSream class for reading data from the keyboard is as:DataInputStream dis =new DataInputStream(System.in);Here System.in represent the keyboard which is linked with DataInputStream objectSend data to OutputStream: Now , associate a file where the data is to be stored to some output stream. For this , take the help of FileOutputStream which can send data to the file. Attaching the file.txt to FileOutputStream can be done as:FileOutputStream fout=new FileOutputStream(“file.txt”);Reading data from DataInputStream: The next step is to read data from DataInputStream and write it into FileOutputStream . It means read data from dis object and write it into fout object, as shown here:ch=(char)dis.read();\nfout.write(ch);Close the file: Finally, any file should be closed after performing input or output operations on it, else the data of the may be corrupted. Closing the file is done by closing the associated streams. For example, fout.close(): will close the FileOutputStream ,hence there is no way to write data into the file." }, { "code": null, "e": 27882, "s": 27531, "text": "Reading data: First of all, data should be read from the keyboard. For this purpose, associate the keyboard to some input stream class. The code for using DataInputSream class for reading data from the keyboard is as:DataInputStream dis =new DataInputStream(System.in);Here System.in represent the keyboard which is linked with DataInputStream object" }, { "code": null, "e": 27935, "s": 27882, "text": "DataInputStream dis =new DataInputStream(System.in);" }, { "code": null, "e": 28017, "s": 27935, "text": "Here System.in represent the keyboard which is linked with DataInputStream object" }, { "code": null, "e": 28313, "s": 28017, "text": "Send data to OutputStream: Now , associate a file where the data is to be stored to some output stream. For this , take the help of FileOutputStream which can send data to the file. Attaching the file.txt to FileOutputStream can be done as:FileOutputStream fout=new FileOutputStream(“file.txt”);" }, { "code": null, "e": 28369, "s": 28313, "text": "FileOutputStream fout=new FileOutputStream(“file.txt”);" }, { "code": null, "e": 28609, "s": 28369, "text": "Reading data from DataInputStream: The next step is to read data from DataInputStream and write it into FileOutputStream . It means read data from dis object and write it into fout object, as shown here:ch=(char)dis.read();\nfout.write(ch);" }, { "code": null, "e": 28646, "s": 28609, "text": "ch=(char)dis.read();\nfout.write(ch);" }, { "code": null, "e": 28958, "s": 28646, "text": "Close the file: Finally, any file should be closed after performing input or output operations on it, else the data of the may be corrupted. Closing the file is done by closing the associated streams. For example, fout.close(): will close the FileOutputStream ,hence there is no way to write data into the file." }, { "code": null, "e": 28974, "s": 28958, "text": "Implementation:" }, { "code": "//Java program to demonstrate creating a text file using FileOutputStreamimport java.io.BufferedOutputStream;import java.io.DataInputStream;import java.io.FileOutputStream;import java.io.IOException;class Create_File{ public static void main(String[] args) throws IOException { //attach keyboard to DataInputStream DataInputStream dis=new DataInputStream(System.in); // attach file to FileOutputStream FileOutputStream fout=new FileOutputStream(\"file.txt\"); //attach FileOutputStream to BufferedOutputStream BufferedOutputStream bout=new BufferedOutputStream(fout,1024); System.out.println(\"Enter text (@ at the end):\"); char ch; //read characters from dis into ch. Then write them into bout. //repeat this as long as the read character is not @ while((ch=(char)dis.read())!='@') { bout.write(ch); } //close the file bout.close(); }}", "e": 29940, "s": 28974, "text": null }, { "code": null, "e": 30241, "s": 29940, "text": "If the Program is executed again, the old data of file.txt will be lost and any recent data is only stored in the file. If we don’t want to lose the previous data of the file, and just append the new data to the end of already existing data, and this can be done by writing true along with file name." }, { "code": null, "e": 30303, "s": 30241, "text": "FileOutputStream fout=new FileOutputStream(“file.txt”,true);\n" }, { "code": null, "e": 30351, "s": 30303, "text": "Improving Efficiency using BufferedOutputStream" }, { "code": null, "e": 30421, "s": 30351, "text": "Normally, whenever we write data to a file using FileOutputStream as:" }, { "code": null, "e": 30437, "s": 30421, "text": "fout.write(ch);" }, { "code": null, "e": 30624, "s": 30437, "text": "Here, the FileOutputStream is invoked to write the characters into the file. Let us estimate the time it takes to read 100 characters from the keyboard and write all of them into a file." }, { "code": null, "e": 30845, "s": 30624, "text": "Let us assume data is read from the keyboard into memory using DataInputStream and it takes 1 sec to read 1 character into memory and this character is written into the file by FileOutputStream by spending another 1 sec." }, { "code": null, "e": 31169, "s": 30845, "text": "So for reading and writing a file will take 200 sec. This is wasting a lot of time. On the other hand, if Buffered classed are used, they provide a buffer which is first filled with characters from the buffer which can be at once written into the file. Buffered classes should be used in connection to other stream classes." }, { "code": null, "e": 31839, "s": 31169, "text": "First, the DataInputStream reads data from the keyboard by spending 1 sec for each character. This character is written into the buffer. Thus, to read 100 characters into a buffer, it will take 100 second time. Now FileOutputStream will write the entire buffer in a single step. So, reading and writing 100 characters took 101 sec only. In the same way, reading classes are used for improving the speed of reading operation. Attaching FileOutputStream to BufferedOutputStream as:BufferedOutputStream bout=new BufferedOutputStream(fout,1024);Here ,the buffer size is declared as 1024 bytes. If the buffer size is not specified , then a default size of 512 bytes is used" }, { "code": null, "e": 31902, "s": 31839, "text": "BufferedOutputStream bout=new BufferedOutputStream(fout,1024);" }, { "code": null, "e": 32030, "s": 31902, "text": "Here ,the buffer size is declared as 1024 bytes. If the buffer size is not specified , then a default size of 512 bytes is used" }, { "code": null, "e": 32079, "s": 32030, "text": "Important methods of BufferedOutputStream Class:" }, { "code": null, "e": 32131, "s": 32079, "text": "void flush() : Flushes this buffered output stream." }, { "code": null, "e": 32274, "s": 32131, "text": "void write(byte[] b, int off, int len) : Writes len bytes from the specified byte array starting at offset off to this buffered output stream." }, { "code": null, "e": 32352, "s": 32274, "text": "void write(int b) : Writes the specified byte to this buffered output stream." }, { "code": null, "e": 32360, "s": 32352, "text": "Output:" }, { "code": null, "e": 32530, "s": 32360, "text": "C:\\> javac Create_File.java\nC:\\> java Create_File\nEnter text (@ at the end):\nThis is a program to create a file\n@\n\nC:/> type file.txt\nThis is a program to create a file\n" }, { "code": null, "e": 32548, "s": 32530, "text": "Related Articles:" }, { "code": null, "e": 32578, "s": 32548, "text": "CharacterStream vs ByteStream" }, { "code": null, "e": 32597, "s": 32578, "text": "File Class in Java" }, { "code": null, "e": 32651, "s": 32597, "text": "File handling in Java using FileWriter and FileReader" }, { "code": null, "e": 32953, "s": 32651, "text": "This article is contributed by Nishant Sharma. 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": 33078, "s": 32953, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 33083, "s": 33078, "text": "Java" }, { "code": null, "e": 33088, "s": 33083, "text": "Java" }, { "code": null, "e": 33186, "s": 33088, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33218, "s": 33186, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 33248, "s": 33218, "text": "HashMap in Java with Examples" }, { "code": null, "e": 33267, "s": 33248, "text": "Interfaces in Java" }, { "code": null, "e": 33285, "s": 33267, "text": "ArrayList in Java" }, { "code": null, "e": 33316, "s": 33285, "text": "How to iterate any Map in Java" }, { "code": null, "e": 33348, "s": 33316, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 33368, "s": 33348, "text": "Stack Class in Java" }, { "code": null, "e": 33392, "s": 33368, "text": "Singleton Class in Java" }, { "code": null, "e": 33404, "s": 33392, "text": "Set in Java" } ]
Apple Silicon, run Scikit-Learn and TensorFlow on the new Macs M1 | by Fabrice Daniel | Towards Data Science
Update : explains how to fix issue on LSTM validation accuracy. — As everybody already knows the new Apple Silicon M1 Macs are incredibly powerful computers. By seeing the benchmarks and all the real-life test performed everywhere, as a machine learning engineer I’m really thinking that something great happened and a dream computer line for ML was born. A M1 based MacBook Air cannot beat training performances of a server with a high-end GPU. But even if I use Tesla K80 or V100 based instances for running big training jobs, 95% of my day-to-day work is based on small data size below 2 GB and reasonable training time not exceeding a few minutes. So, having such powerful ML lab in a 1.29 kg fanless laptop like the MacBook Air sounds like an engineer dream. 8-core CPU (4 high performances at 3.2 GHz, 4 high efficiency at 2.06 GHz) 8-core GPU (128 execution units, 24 576 threads, 2.6 TFlops) 16-core Neural Engine dedicated to linear algebra Unified Memory Architecture 4 266 MT/s (34 128 MB/s data transfer) As Apple stated, thanks to UMA “all of the technologies in the SoC can access the same data without copying it between multiple pools of memory”. In addition, M1 memory speed exceed by far most of the best available computers today. For instance, M1 memory transfer is 60% faster than the most recent iMac 27" released a few months ago equipped with a 2 666 MT/s RAM. And due to the Unified Memory Architecture, it eliminates memory transfers between CPU, GPU and Neural Engine even more increasing the performances gap with Intel architectures. For my day-to-day ML research and engineering I need Python 3, pandas, numpy, scikit-learn, matplotlib, tensorflow and jupyterlab as a bare minimum. Even if it reports surprisingly good performances, I don’t want to use Rosetta 2 for the moment. Instead, I’m only looking for native versions compiled for Apple Silicon even if they are not still using all its power (GPU, Neural Engine). Two weeks after the launch of Apple Silicon, Anaconda 2020.11 is not yet compatible. The installer asks for Rosetta. On the other hand installing Python 3 is quite easy. Simply open a terminal and call python3. This installs the XCode command line tools including Python 3.8.2 compiled for Apple Silicon. But this is quite useless for the moment as trying to install numpy fails with a compilation error. JupyterLab can be installed but fails to run any notebook, causing kernel issues. The solution is to use miniforge an open source conda distribution, from conda-forge , sponsored by numfocus and identical to miniconda but providing the packages compiled for various platform including Apple Silicon osx-arm64. I first installed pandas, numpy, scikit-learn, matplotlib and jupyterlab from miniforge conda. After a few testing on a dummy random forest classifier running from a Jupyter notebook, everything seems to work perfectly. At the moment gradient boosting packages like XGBoost, LightGBM and CatBoost cannot be installed. Trying to compile them from a pip installation under conda environment fails. Regarding TensorFlow an alpha version for Apple Silicon is available. This is a fork from TensorFlow by Apple that is planned to be merged in the master by Google as stated here. As it was compiled for Python 3.8 it cannot be installed under the miniforge conda environment. Instead, it needs to use the Python 3.8.2 release installed with XCode command line tools. It creates a dedicated virtual environment that can be used for experiments. When looking at the delivered packages, it includes numpy wheel, so we can guess this version is the one optimized for Apple Silicon as stated by Apple in the list of open-source project they helps the community to port. I have first tested MLP, CNN and LSTM models on MNIST. MLP and CNN works perfectly with a decreasing loss as expected, similar to the one observed on the current TensorFlow master release running on my Intel iMac. LSTM has an issue. While reporting a decreasing loss, the test set shows a very low accuracy while such extreme overfit does not appears when training the same network on 4 other configurations (CPU and GPU). I’ve reported the issue to Apple on GitHub. Update: a workaround exists by setting the evaluation batch size to a value greater or equal to the training batch size. For instance if the training batch size was 128, you must evaluate it with the same size. model.evaluate(X_test,y_test,verbose=2,batch_size=128) There are also some other bugs, like an exception raised when trying to disable the eager execution mode to avoid a huge slowdown when using the GPU. For now, only the CPU mode works quite well in most of the situations despite a strange underutilization. These issues are also reported to apple on GitHub. Regarding the miniforge release, it’s unclear today if numpy was optimized or just compiled for Apple Silicon. On the other hand, we can assume that numpy release delivered with TF 2.4 alpha takes benefit from M1 linear algebra computation capacity, at least partially. I will try to make it clearer with some tests in another article. Regarding TensorFlow, it’s too early for doing any reliable testing today as there is still too many issues, especially on GPU. Even on CPU we observe a strange underutilization with only 4 cores used at 50% or less each. I will soon publish an article on performances relative to ML on M1. I can disclose one more thing ... it’s already really fast. Thank you for reading.
[ { "code": null, "e": 235, "s": 171, "text": "Update : explains how to fix issue on LSTM validation accuracy." }, { "code": null, "e": 237, "s": 235, "text": "—" }, { "code": null, "e": 527, "s": 237, "text": "As everybody already knows the new Apple Silicon M1 Macs are incredibly powerful computers. By seeing the benchmarks and all the real-life test performed everywhere, as a machine learning engineer I’m really thinking that something great happened and a dream computer line for ML was born." }, { "code": null, "e": 823, "s": 527, "text": "A M1 based MacBook Air cannot beat training performances of a server with a high-end GPU. But even if I use Tesla K80 or V100 based instances for running big training jobs, 95% of my day-to-day work is based on small data size below 2 GB and reasonable training time not exceeding a few minutes." }, { "code": null, "e": 935, "s": 823, "text": "So, having such powerful ML lab in a 1.29 kg fanless laptop like the MacBook Air sounds like an engineer dream." }, { "code": null, "e": 1010, "s": 935, "text": "8-core CPU (4 high performances at 3.2 GHz, 4 high efficiency at 2.06 GHz)" }, { "code": null, "e": 1071, "s": 1010, "text": "8-core GPU (128 execution units, 24 576 threads, 2.6 TFlops)" }, { "code": null, "e": 1121, "s": 1071, "text": "16-core Neural Engine dedicated to linear algebra" }, { "code": null, "e": 1188, "s": 1121, "text": "Unified Memory Architecture 4 266 MT/s (34 128 MB/s data transfer)" }, { "code": null, "e": 1734, "s": 1188, "text": "As Apple stated, thanks to UMA “all of the technologies in the SoC can access the same data without copying it between multiple pools of memory”. In addition, M1 memory speed exceed by far most of the best available computers today. For instance, M1 memory transfer is 60% faster than the most recent iMac 27\" released a few months ago equipped with a 2 666 MT/s RAM. And due to the Unified Memory Architecture, it eliminates memory transfers between CPU, GPU and Neural Engine even more increasing the performances gap with Intel architectures." }, { "code": null, "e": 1883, "s": 1734, "text": "For my day-to-day ML research and engineering I need Python 3, pandas, numpy, scikit-learn, matplotlib, tensorflow and jupyterlab as a bare minimum." }, { "code": null, "e": 2122, "s": 1883, "text": "Even if it reports surprisingly good performances, I don’t want to use Rosetta 2 for the moment. Instead, I’m only looking for native versions compiled for Apple Silicon even if they are not still using all its power (GPU, Neural Engine)." }, { "code": null, "e": 2609, "s": 2122, "text": "Two weeks after the launch of Apple Silicon, Anaconda 2020.11 is not yet compatible. The installer asks for Rosetta. On the other hand installing Python 3 is quite easy. Simply open a terminal and call python3. This installs the XCode command line tools including Python 3.8.2 compiled for Apple Silicon. But this is quite useless for the moment as trying to install numpy fails with a compilation error. JupyterLab can be installed but fails to run any notebook, causing kernel issues." }, { "code": null, "e": 2837, "s": 2609, "text": "The solution is to use miniforge an open source conda distribution, from conda-forge , sponsored by numfocus and identical to miniconda but providing the packages compiled for various platform including Apple Silicon osx-arm64." }, { "code": null, "e": 3057, "s": 2837, "text": "I first installed pandas, numpy, scikit-learn, matplotlib and jupyterlab from miniforge conda. After a few testing on a dummy random forest classifier running from a Jupyter notebook, everything seems to work perfectly." }, { "code": null, "e": 3233, "s": 3057, "text": "At the moment gradient boosting packages like XGBoost, LightGBM and CatBoost cannot be installed. Trying to compile them from a pip installation under conda environment fails." }, { "code": null, "e": 3412, "s": 3233, "text": "Regarding TensorFlow an alpha version for Apple Silicon is available. This is a fork from TensorFlow by Apple that is planned to be merged in the master by Google as stated here." }, { "code": null, "e": 3897, "s": 3412, "text": "As it was compiled for Python 3.8 it cannot be installed under the miniforge conda environment. Instead, it needs to use the Python 3.8.2 release installed with XCode command line tools. It creates a dedicated virtual environment that can be used for experiments. When looking at the delivered packages, it includes numpy wheel, so we can guess this version is the one optimized for Apple Silicon as stated by Apple in the list of open-source project they helps the community to port." }, { "code": null, "e": 4364, "s": 3897, "text": "I have first tested MLP, CNN and LSTM models on MNIST. MLP and CNN works perfectly with a decreasing loss as expected, similar to the one observed on the current TensorFlow master release running on my Intel iMac. LSTM has an issue. While reporting a decreasing loss, the test set shows a very low accuracy while such extreme overfit does not appears when training the same network on 4 other configurations (CPU and GPU). I’ve reported the issue to Apple on GitHub." }, { "code": null, "e": 4575, "s": 4364, "text": "Update: a workaround exists by setting the evaluation batch size to a value greater or equal to the training batch size. For instance if the training batch size was 128, you must evaluate it with the same size." }, { "code": null, "e": 4630, "s": 4575, "text": "model.evaluate(X_test,y_test,verbose=2,batch_size=128)" }, { "code": null, "e": 4937, "s": 4630, "text": "There are also some other bugs, like an exception raised when trying to disable the eager execution mode to avoid a huge slowdown when using the GPU. For now, only the CPU mode works quite well in most of the situations despite a strange underutilization. These issues are also reported to apple on GitHub." }, { "code": null, "e": 5273, "s": 4937, "text": "Regarding the miniforge release, it’s unclear today if numpy was optimized or just compiled for Apple Silicon. On the other hand, we can assume that numpy release delivered with TF 2.4 alpha takes benefit from M1 linear algebra computation capacity, at least partially. I will try to make it clearer with some tests in another article." }, { "code": null, "e": 5495, "s": 5273, "text": "Regarding TensorFlow, it’s too early for doing any reliable testing today as there is still too many issues, especially on GPU. Even on CPU we observe a strange underutilization with only 4 cores used at 50% or less each." }, { "code": null, "e": 5564, "s": 5495, "text": "I will soon publish an article on performances relative to ML on M1." }, { "code": null, "e": 5624, "s": 5564, "text": "I can disclose one more thing ... it’s already really fast." } ]
Node.js process.kill() Method - GeeksforGeeks
17 Jan, 2022 The process.kill( pid[,signal] ) is an inbuilt method of node.js which sends a signal to the process, pid (which is the process id) and signal is in the string format that is the signal to send. Syntax : process.kill(pid[, signal]) Parameters: This method accepts two parameters as mentioned above and described below: pid: This parameter holds the process ID. signal: This parameter holds the string format.signal names : These are in string format .SIGTERMSIGINTSIGHUP signal names : These are in string format . SIGTERMSIGINTSIGHUP SIGTERM SIGINT SIGHUP Note : If no signal specified, then by default ‘SIGTERM’ will be the signal. ‘SIGTERM’ and ‘SIGINT‘ signals have default handlers on non-Windows platforms that reset the terminal mode before exiting with code 128 + signal number. If one of these signals has a listener installed, its default behavior on node.js will be removed. ‘SIGHUP’ is generated when the console window is closed. Return value : The process.kill() method will throw an error if the target pid is not found or doesn’t exist. This method returns boolean value 0 if pid exists and can be used as a test for the existence of the target process. For window users, this method will also throw an error if pid is used to kill a group of process. Below examples illustrate the use of process.kill() property in Node.js: Example 1: index.js // Node.js program to demonstrate the // process.kill(pid[, signal]) method // Printing process signal acknowledgedconst displayInfo = () => { console.log('Receiving SIGINT signal in nodeJS.');} // Initiating a processprocess.on('SIGINT', displayInfo); setTimeout(() => { console.log('Exiting.'); process.exit(0);}, 100); // kill the process with pid and signal = 'SIGINT' process.kill(process.pid, 'SIGINT'); Command to run : node index.js Output : Example 2 : index.js // Node.js program to demonstrate the // process.kill(pid[, signal]) method // Printing process signal acknowledgedconst displayInfo = () => { console.log('Acknowledged SIGHUP signal in nodeJS.');} // Initiating a processprocess.on('SIGHUP', displayInfo); setTimeout(() => { console.log('Exiting.'); process.exit(0);}, 100); // kill the process with pid and signal = 'SIGHUP' process.kill(process.pid, 'SIGHUP'); Command to run : node index.js Output : Reference : https://nodejs.org/api/process.html#process_process_kill_pid_signal adnanirshad158 Node.js-Methods NodeJS-Process Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to build a basic CRUD app with Node.js and ReactJS ? How to connect Node.js with React.js ? Mongoose Populate() Method Express.js req.params Property How to Convert CSV to JSON file having Comma Separated values in Node.js ? Top 10 Front End Developer Skills That You Need in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24531, "s": 24503, "text": "\n17 Jan, 2022" }, { "code": null, "e": 24726, "s": 24531, "text": "The process.kill( pid[,signal] ) is an inbuilt method of node.js which sends a signal to the process, pid (which is the process id) and signal is in the string format that is the signal to send." }, { "code": null, "e": 24735, "s": 24726, "text": "Syntax :" }, { "code": null, "e": 24763, "s": 24735, "text": "process.kill(pid[, signal])" }, { "code": null, "e": 24850, "s": 24763, "text": "Parameters: This method accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 24892, "s": 24850, "text": "pid: This parameter holds the process ID." }, { "code": null, "e": 25002, "s": 24892, "text": "signal: This parameter holds the string format.signal names : These are in string format .SIGTERMSIGINTSIGHUP" }, { "code": null, "e": 25046, "s": 25002, "text": "signal names : These are in string format ." }, { "code": null, "e": 25066, "s": 25046, "text": "SIGTERMSIGINTSIGHUP" }, { "code": null, "e": 25074, "s": 25066, "text": "SIGTERM" }, { "code": null, "e": 25081, "s": 25074, "text": "SIGINT" }, { "code": null, "e": 25088, "s": 25081, "text": "SIGHUP" }, { "code": null, "e": 25165, "s": 25088, "text": "Note : If no signal specified, then by default ‘SIGTERM’ will be the signal." }, { "code": null, "e": 25417, "s": 25165, "text": "‘SIGTERM’ and ‘SIGINT‘ signals have default handlers on non-Windows platforms that reset the terminal mode before exiting with code 128 + signal number. If one of these signals has a listener installed, its default behavior on node.js will be removed." }, { "code": null, "e": 25474, "s": 25417, "text": "‘SIGHUP’ is generated when the console window is closed." }, { "code": null, "e": 25800, "s": 25474, "text": "Return value : The process.kill() method will throw an error if the target pid is not found or doesn’t exist. This method returns boolean value 0 if pid exists and can be used as a test for the existence of the target process. For window users, this method will also throw an error if pid is used to kill a group of process. " }, { "code": null, "e": 25873, "s": 25800, "text": "Below examples illustrate the use of process.kill() property in Node.js:" }, { "code": null, "e": 25884, "s": 25873, "text": "Example 1:" }, { "code": null, "e": 25893, "s": 25884, "text": "index.js" }, { "code": "// Node.js program to demonstrate the // process.kill(pid[, signal]) method // Printing process signal acknowledgedconst displayInfo = () => { console.log('Receiving SIGINT signal in nodeJS.');} // Initiating a processprocess.on('SIGINT', displayInfo); setTimeout(() => { console.log('Exiting.'); process.exit(0);}, 100); // kill the process with pid and signal = 'SIGINT' process.kill(process.pid, 'SIGINT');", "e": 26317, "s": 25893, "text": null }, { "code": null, "e": 26334, "s": 26317, "text": "Command to run :" }, { "code": null, "e": 26348, "s": 26334, "text": "node index.js" }, { "code": null, "e": 26357, "s": 26348, "text": "Output :" }, { "code": null, "e": 26369, "s": 26357, "text": "Example 2 :" }, { "code": null, "e": 26378, "s": 26369, "text": "index.js" }, { "code": "// Node.js program to demonstrate the // process.kill(pid[, signal]) method // Printing process signal acknowledgedconst displayInfo = () => { console.log('Acknowledged SIGHUP signal in nodeJS.');} // Initiating a processprocess.on('SIGHUP', displayInfo); setTimeout(() => { console.log('Exiting.'); process.exit(0);}, 100); // kill the process with pid and signal = 'SIGHUP' process.kill(process.pid, 'SIGHUP');", "e": 26801, "s": 26378, "text": null }, { "code": null, "e": 26818, "s": 26801, "text": "Command to run :" }, { "code": null, "e": 26832, "s": 26818, "text": "node index.js" }, { "code": null, "e": 26841, "s": 26832, "text": "Output :" }, { "code": null, "e": 26921, "s": 26841, "text": "Reference : https://nodejs.org/api/process.html#process_process_kill_pid_signal" }, { "code": null, "e": 26936, "s": 26921, "text": "adnanirshad158" }, { "code": null, "e": 26952, "s": 26936, "text": "Node.js-Methods" }, { "code": null, "e": 26967, "s": 26952, "text": "NodeJS-Process" }, { "code": null, "e": 26974, "s": 26967, "text": "Picked" }, { "code": null, "e": 26982, "s": 26974, "text": "Node.js" }, { "code": null, "e": 26999, "s": 26982, "text": "Web Technologies" }, { "code": null, "e": 27097, "s": 26999, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27106, "s": 27097, "text": "Comments" }, { "code": null, "e": 27119, "s": 27106, "text": "Old Comments" }, { "code": null, "e": 27176, "s": 27119, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 27215, "s": 27176, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 27242, "s": 27215, "text": "Mongoose Populate() Method" }, { "code": null, "e": 27273, "s": 27242, "text": "Express.js req.params Property" }, { "code": null, "e": 27348, "s": 27273, "text": "How to Convert CSV to JSON file having Comma Separated values in Node.js ?" }, { "code": null, "e": 27404, "s": 27348, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 27466, "s": 27404, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27509, "s": 27466, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27559, "s": 27509, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How can we start MySQL event scheduler?
Actually, MySQL event scheduler is a process that runs in the background and constantly looks for the events to execute. But before we create or schedule an event we just have to start the scheduler. It can start with the help of the following statement − mysql> SET GLOBAL event_scheduler = ON; Query OK, 0 rows affected (0.07 sec) Now with the help of the following statement, we can check its status in MySQL process list − mysql> SHOW PROCESSLIST\G *************************** 1. row *************************** Id: 3 User: root Host: localhost:49500 db: query Command: Query Time: 0 State: starting Info: SHOW PROCESSLIST *************************** 2. row *************************** Id: 4 User: event_scheduler Host: localhost db: NULL Command: Daemon Time: 11 State: Waiting on empty queue Info: NULL 2 rows in set (0.06 sec) It can be turn off with the help of the following statement − mysql> SET GLOBAL event_scheduler = OFF; Query OK, 0 rows affected (0.07 sec)
[ { "code": null, "e": 1318, "s": 1062, "text": "Actually, MySQL event scheduler is a process that runs in the background and constantly looks for the events to execute. But before we create or schedule an event we just have to start the scheduler. It can start with the help of the following statement −" }, { "code": null, "e": 1395, "s": 1318, "text": "mysql> SET GLOBAL event_scheduler = ON;\nQuery OK, 0 rows affected (0.07 sec)" }, { "code": null, "e": 1489, "s": 1395, "text": "Now with the help of the following statement, we can check its status in MySQL process list −" }, { "code": null, "e": 1944, "s": 1489, "text": "mysql> SHOW PROCESSLIST\\G\n*************************** 1. row ***************************\n Id: 3\n User: root\n Host: localhost:49500\n db: query\nCommand: Query\n Time: 0\n State: starting\n Info: SHOW PROCESSLIST\n*************************** 2. row ***************************\n Id: 4\n User: event_scheduler\n Host: localhost\n db: NULL\nCommand: Daemon\n Time: 11\n State: Waiting on empty queue\n Info: NULL\n2 rows in set (0.06 sec)" }, { "code": null, "e": 2006, "s": 1944, "text": "It can be turn off with the help of the following statement −" }, { "code": null, "e": 2084, "s": 2006, "text": "mysql> SET GLOBAL event_scheduler = OFF;\nQuery OK, 0 rows affected (0.07 sec)" } ]
Splines in Python for Feature Selection and Data Smoothing | by Robbie Prior | Towards Data Science
So this week I ended up doing some work with Splines in Python and was shocked regarding the state of information and lack of support articles for new-comers to Splines with Python. There is plenty of information on the math already. The goal of this article is to break down the application of that theory for B-Splines and Smoothing Splines. Please consider giving me a follow to support future articles if this is helpful. What is a Spline? How are Splines Used? Walkthrough 1: B-Splines from scratch for the most flexible but mathematically hands-on approach Walkthrough 2: splrep from SciPy for easy Smoothing B-Spines Summarizing Splines for Feature Extraction Conclusion A Spline is essentially a piecewise regression line. Trying to fit one regression line over a very dynamic set of data can let to a lot of compromise. You can tailor your line to fit one area well, but then can often suffer from overfitting in other areas as a consequence. Instead, we break up the observation into different “knots” and fit a different regression line on each segment divvied up by these knots or division points. Generally when we are looking at the input for a spline, we are using a 1D list or array. This could be we took the heart rate for one patient and recorded it every second for 30 seconds. This creates 1 observation with 30 features, or the heart rate recorded at each of those 30 seconds. We will then fit a Spline to this one observation detailing our knots (t) and order (k), which will return a line of best fit that has its own coefficients we can leverage as is or to make predictions with as well. Fit/train the spline on the observationExtract the heart rate by feeding in the exact times we would like to predict the heart rate for (in this example, a list/array of range 0:30)Save this output as the new data for each of our 30 features Fit/train the spline on the observation Extract the heart rate by feeding in the exact times we would like to predict the heart rate for (in this example, a list/array of range 0:30) Save this output as the new data for each of our 30 features Fit/train the spline on the observationExtract the coefficients for our spline (Beta values across each knot) and save these as our new feature data (number of coefficients depends on the complexity of your spline, but you could reduce your features from 30 to 8 just as an example)Repeat steps 1 & 2 for multiple observations (multiple patients we have tracked the heart for over 30 seconds)Run a new model such as Regression or Random Forest on this new data frame of n number of patients as rows and m number of extracted coefficients as the columns Fit/train the spline on the observation Extract the coefficients for our spline (Beta values across each knot) and save these as our new feature data (number of coefficients depends on the complexity of your spline, but you could reduce your features from 30 to 8 just as an example) Repeat steps 1 & 2 for multiple observations (multiple patients we have tracked the heart for over 30 seconds) Run a new model such as Regression or Random Forest on this new data frame of n number of patients as rows and m number of extracted coefficients as the columns That’s enough mumbo jumbo, so let’s see it in action... First, this is our function to evenly distribute the locations of our knots (and account for buffer knots depending on the degree chosen) as we go to set the basis for our splines. def knot_points(nKnots, x, degree):#create the knot locations knots = np.linspace(x[0], x[-1], nKnots) lo = min(x[0], knots[0]) #we have to add these min and values to conform by adding preceding and proceeding values hi = max(x[-1], knots[-1]) augmented_knots = np.append(np.append([lo]*degree, knots), [hi]*degree) return augmented_knotsloo = LeaveOneOut() The data we are using is a series of radio signals. Each observation is a distinct radio signal with each feature being the amplitude of the signal at a given point in time. x1 = pd.read_csv("data.csv", header=None)y = np.array(x1.values[0,:])x = np.array(range(0,len(x1[0])) Y and x should both have a shape of (51,), equal to the number of features/columns. Array x represents the number of features which will be useful to specify the output for our splines and graphing later on. Array y represents one observation with its respective amplitude measurements. So let’s get started! nknots = 8degree = 3k=degreeDOF = nknots + degree +1augmented_t = knot_points(nknots, x, degree) We set a couple of variables we will use (DOF = Degrees of Freedom). Below we start to fit our Spline manually. bs2 = BSpline(augmented_t, np.eye(DOF), degree, extrapolate=False) #setting up the basisB = bs2(x)[:,:-2] #Creating the basis for x & getting rid of extra column of zeroes from padding for order# Least square estimationx_proj_matrix = B@np.linalg.inv(B.T@B)@B.Tcoeff = np.linalg.lstsq(B, y.T,rcond=-1)[0].Tyhat = B@coeffn = x.shape[0]K = np.trace(x_proj_matrix)sigma2 = (1/(n-K))*(y-yhat).T@(y-yhat) #SSE/(n-p)width = np.diag(sigma2*x_proj_matrix)**0.5y_neg_ci = yhat-4*widthy_pos_ci = yhat+4*width We fit the basis to our x and y to calculate the coefficients, which we can then use to give a prediction. We can also use the X Projection Matrix to directly calculate the covariances and give us our confidence intervals that we see in the image below. So we see some of the math used to create these splines. While calculating this by hand does not seem to be the most fun, you can begin to easily extract other powerful information such as covariances to create these confidence intervals around our trend line. Let’s look at Example 2 now: Walking through an example using Smoothing Splines. These are a little more complicated as they contain a smoothing hyperparameter that balances variance and bias. We can use cross validation with leave one out to find MSE and choose the optimal smoothing parameter here. The benefit is that this function will automatically setup the knot array for us and return it too. lambs = np.array([0.001,0.005, 0.1,0.25,0.5])for i in lambs:error = [] for trg, tst in loo.split(x): spl = splrep(x[trg], y[trg],s=i) pred = splev(x[tst],spl)[0] true = y[tst][0] error.append((pred - true)**2) mse = mean(error) Our best lambda (smoothing parameter) turned out to be 0.005. spl = splrep(x, y, s=0.005)y_hat = splev(x, spl) Something that is also useful is calling a fitted splrep model as below, which gives us a nice clean output of the self-generated knots array, coefficients, and the power/order of the function. spl Now, if we were going to apply all of this above for smoothing our data we could loop through each observation/row, fit a spline on the resultant x and y arrays for that iteration in the loop, and then predict the new features. Now that ends the examples for smoothing. I will briefly summarize feature extraction here and go more in depth in my next article. Essentially, instead of making a prediction of the new feature values, we will just output the Betas/Coefficients produced by the spline. For example with the B-Splines above we can get following output: bs = make_lsq_spline(x, y, augmented_t, k=degree)bs.c Now, we can loop through our data frame, training a spline on each row and returning instead of the 51 features, just the 9 features made up of the Betas from our spline above. This can help us combat high dimensionality and overfitting on smaller data sets while still maintaining high explained variance. Overall, this Spline Feature Selection approach can often beat out even FPCA/PCA for a better model performance score with even fewer required features. Thanks for reading and please give me a follow if you liked the article!
[ { "code": null, "e": 391, "s": 47, "text": "So this week I ended up doing some work with Splines in Python and was shocked regarding the state of information and lack of support articles for new-comers to Splines with Python. There is plenty of information on the math already. The goal of this article is to break down the application of that theory for B-Splines and Smoothing Splines." }, { "code": null, "e": 473, "s": 391, "text": "Please consider giving me a follow to support future articles if this is helpful." }, { "code": null, "e": 491, "s": 473, "text": "What is a Spline?" }, { "code": null, "e": 513, "s": 491, "text": "How are Splines Used?" }, { "code": null, "e": 610, "s": 513, "text": "Walkthrough 1: B-Splines from scratch for the most flexible but mathematically hands-on approach" }, { "code": null, "e": 671, "s": 610, "text": "Walkthrough 2: splrep from SciPy for easy Smoothing B-Spines" }, { "code": null, "e": 714, "s": 671, "text": "Summarizing Splines for Feature Extraction" }, { "code": null, "e": 725, "s": 714, "text": "Conclusion" }, { "code": null, "e": 1157, "s": 725, "text": "A Spline is essentially a piecewise regression line. Trying to fit one regression line over a very dynamic set of data can let to a lot of compromise. You can tailor your line to fit one area well, but then can often suffer from overfitting in other areas as a consequence. Instead, we break up the observation into different “knots” and fit a different regression line on each segment divvied up by these knots or division points." }, { "code": null, "e": 1661, "s": 1157, "text": "Generally when we are looking at the input for a spline, we are using a 1D list or array. This could be we took the heart rate for one patient and recorded it every second for 30 seconds. This creates 1 observation with 30 features, or the heart rate recorded at each of those 30 seconds. We will then fit a Spline to this one observation detailing our knots (t) and order (k), which will return a line of best fit that has its own coefficients we can leverage as is or to make predictions with as well." }, { "code": null, "e": 1903, "s": 1661, "text": "Fit/train the spline on the observationExtract the heart rate by feeding in the exact times we would like to predict the heart rate for (in this example, a list/array of range 0:30)Save this output as the new data for each of our 30 features" }, { "code": null, "e": 1943, "s": 1903, "text": "Fit/train the spline on the observation" }, { "code": null, "e": 2086, "s": 1943, "text": "Extract the heart rate by feeding in the exact times we would like to predict the heart rate for (in this example, a list/array of range 0:30)" }, { "code": null, "e": 2147, "s": 2086, "text": "Save this output as the new data for each of our 30 features" }, { "code": null, "e": 2700, "s": 2147, "text": "Fit/train the spline on the observationExtract the coefficients for our spline (Beta values across each knot) and save these as our new feature data (number of coefficients depends on the complexity of your spline, but you could reduce your features from 30 to 8 just as an example)Repeat steps 1 & 2 for multiple observations (multiple patients we have tracked the heart for over 30 seconds)Run a new model such as Regression or Random Forest on this new data frame of n number of patients as rows and m number of extracted coefficients as the columns" }, { "code": null, "e": 2740, "s": 2700, "text": "Fit/train the spline on the observation" }, { "code": null, "e": 2984, "s": 2740, "text": "Extract the coefficients for our spline (Beta values across each knot) and save these as our new feature data (number of coefficients depends on the complexity of your spline, but you could reduce your features from 30 to 8 just as an example)" }, { "code": null, "e": 3095, "s": 2984, "text": "Repeat steps 1 & 2 for multiple observations (multiple patients we have tracked the heart for over 30 seconds)" }, { "code": null, "e": 3256, "s": 3095, "text": "Run a new model such as Regression or Random Forest on this new data frame of n number of patients as rows and m number of extracted coefficients as the columns" }, { "code": null, "e": 3312, "s": 3256, "text": "That’s enough mumbo jumbo, so let’s see it in action..." }, { "code": null, "e": 3493, "s": 3312, "text": "First, this is our function to evenly distribute the locations of our knots (and account for buffer knots depending on the degree chosen) as we go to set the basis for our splines." }, { "code": null, "e": 3874, "s": 3493, "text": "def knot_points(nKnots, x, degree):#create the knot locations knots = np.linspace(x[0], x[-1], nKnots) lo = min(x[0], knots[0]) #we have to add these min and values to conform by adding preceding and proceeding values hi = max(x[-1], knots[-1]) augmented_knots = np.append(np.append([lo]*degree, knots), [hi]*degree) return augmented_knotsloo = LeaveOneOut()" }, { "code": null, "e": 4048, "s": 3874, "text": "The data we are using is a series of radio signals. Each observation is a distinct radio signal with each feature being the amplitude of the signal at a given point in time." }, { "code": null, "e": 4150, "s": 4048, "text": "x1 = pd.read_csv(\"data.csv\", header=None)y = np.array(x1.values[0,:])x = np.array(range(0,len(x1[0]))" }, { "code": null, "e": 4437, "s": 4150, "text": "Y and x should both have a shape of (51,), equal to the number of features/columns. Array x represents the number of features which will be useful to specify the output for our splines and graphing later on. Array y represents one observation with its respective amplitude measurements." }, { "code": null, "e": 4459, "s": 4437, "text": "So let’s get started!" }, { "code": null, "e": 4556, "s": 4459, "text": "nknots = 8degree = 3k=degreeDOF = nknots + degree +1augmented_t = knot_points(nknots, x, degree)" }, { "code": null, "e": 4668, "s": 4556, "text": "We set a couple of variables we will use (DOF = Degrees of Freedom). Below we start to fit our Spline manually." }, { "code": null, "e": 5167, "s": 4668, "text": "bs2 = BSpline(augmented_t, np.eye(DOF), degree, extrapolate=False) #setting up the basisB = bs2(x)[:,:-2] #Creating the basis for x & getting rid of extra column of zeroes from padding for order# Least square estimationx_proj_matrix = B@np.linalg.inv(B.T@B)@B.Tcoeff = np.linalg.lstsq(B, y.T,rcond=-1)[0].Tyhat = B@coeffn = x.shape[0]K = np.trace(x_proj_matrix)sigma2 = (1/(n-K))*(y-yhat).T@(y-yhat) #SSE/(n-p)width = np.diag(sigma2*x_proj_matrix)**0.5y_neg_ci = yhat-4*widthy_pos_ci = yhat+4*width" }, { "code": null, "e": 5421, "s": 5167, "text": "We fit the basis to our x and y to calculate the coefficients, which we can then use to give a prediction. We can also use the X Projection Matrix to directly calculate the covariances and give us our confidence intervals that we see in the image below." }, { "code": null, "e": 5682, "s": 5421, "text": "So we see some of the math used to create these splines. While calculating this by hand does not seem to be the most fun, you can begin to easily extract other powerful information such as covariances to create these confidence intervals around our trend line." }, { "code": null, "e": 6083, "s": 5682, "text": "Let’s look at Example 2 now: Walking through an example using Smoothing Splines. These are a little more complicated as they contain a smoothing hyperparameter that balances variance and bias. We can use cross validation with leave one out to find MSE and choose the optimal smoothing parameter here. The benefit is that this function will automatically setup the knot array for us and return it too." }, { "code": null, "e": 6345, "s": 6083, "text": "lambs = np.array([0.001,0.005, 0.1,0.25,0.5])for i in lambs:error = [] for trg, tst in loo.split(x): spl = splrep(x[trg], y[trg],s=i) pred = splev(x[tst],spl)[0] true = y[tst][0] error.append((pred - true)**2) mse = mean(error)" }, { "code": null, "e": 6407, "s": 6345, "text": "Our best lambda (smoothing parameter) turned out to be 0.005." }, { "code": null, "e": 6456, "s": 6407, "text": "spl = splrep(x, y, s=0.005)y_hat = splev(x, spl)" }, { "code": null, "e": 6650, "s": 6456, "text": "Something that is also useful is calling a fitted splrep model as below, which gives us a nice clean output of the self-generated knots array, coefficients, and the power/order of the function." }, { "code": null, "e": 6654, "s": 6650, "text": "spl" }, { "code": null, "e": 6882, "s": 6654, "text": "Now, if we were going to apply all of this above for smoothing our data we could loop through each observation/row, fit a spline on the resultant x and y arrays for that iteration in the loop, and then predict the new features." }, { "code": null, "e": 7218, "s": 6882, "text": "Now that ends the examples for smoothing. I will briefly summarize feature extraction here and go more in depth in my next article. Essentially, instead of making a prediction of the new feature values, we will just output the Betas/Coefficients produced by the spline. For example with the B-Splines above we can get following output:" }, { "code": null, "e": 7272, "s": 7218, "text": "bs = make_lsq_spline(x, y, augmented_t, k=degree)bs.c" }, { "code": null, "e": 7732, "s": 7272, "text": "Now, we can loop through our data frame, training a spline on each row and returning instead of the 51 features, just the 9 features made up of the Betas from our spline above. This can help us combat high dimensionality and overfitting on smaller data sets while still maintaining high explained variance. Overall, this Spline Feature Selection approach can often beat out even FPCA/PCA for a better model performance score with even fewer required features." } ]
Solidity - Environment Setup
This chapter explains how we can setup Solidity compiler on CentOS machine. If you do not have a Linux machine then you can use our Online Compiler for small contracts and for quickly learning Solidity. This is the fastest way to install Solidity compiler on your CentoS Machine. We have following steps to install Solidity Compiler − First make sure you have node.js available on your CentOS machine. If it is not available then install it using the following commands − # First install epel-release $sudo yum install epel-release # Now install nodejs $sudo yum install nodejs # Next install npm (Nodejs Package Manager ) $sudo yum install npm # Finally verify installation $npm --version If everything has been installed then you will see an output something like this − 3.10.10 Once you have Node.js package manager installed then you can proceed to install Solidity compiler as below − $sudonpm install -g solc The above command will install solcjs program and will make it available globally through out the system. Now you can test your Solidity compiler by issuing following command − $solcjs-version If everything goes fine, then this will print something as follows − 0.5.2+commit.1df8f40c.Emscripten.clang Now you are ready to use solcjs which has fewer features than the standard Solidity compiler but it will give you a good starting point. You can pull a Docker image and start using it to start with Solidity programming. Following are the simple steps. Following is the command to pull a Solidity Docker Image. $docker pull ethereum/solc:stable Once a docker image is downloaded we can verify it using the following command. $docker run ethereum/solc:stable-version This will print something as follows − $ docker run ethereum/solc:stable -version solc, the solidity compiler commandlineinterfaceVersion: 0.5.2+commit.1df8f40c.Linux.g++ If you are willing to install full fledged compiler on your Linux machine, then please check official website Installing the Solidity Compiler. 38 Lectures 4.5 hours Abhilash Nelson 62 Lectures 8.5 hours Frahaan Hussain 31 Lectures 3.5 hours Swapnil Kole Print Add Notes Bookmark this page
[ { "code": null, "e": 2758, "s": 2555, "text": "This chapter explains how we can setup Solidity compiler on CentOS machine. If you do not have a Linux machine then you can use our Online Compiler for small contracts and for quickly learning Solidity." }, { "code": null, "e": 2890, "s": 2758, "text": "This is the fastest way to install Solidity compiler on your CentoS Machine. We have following steps to install Solidity Compiler −" }, { "code": null, "e": 3027, "s": 2890, "text": "First make sure you have node.js available on your CentOS machine. If it is not available then install it using the following commands −" }, { "code": null, "e": 3249, "s": 3027, "text": "# First install epel-release\n$sudo yum install epel-release\n\n# Now install nodejs\n$sudo yum install nodejs\n\n# Next install npm (Nodejs Package Manager )\n$sudo yum install npm\n\n# Finally verify installation\n$npm --version\n" }, { "code": null, "e": 3332, "s": 3249, "text": "If everything has been installed then you will see an output something like this −" }, { "code": null, "e": 3341, "s": 3332, "text": "3.10.10\n" }, { "code": null, "e": 3450, "s": 3341, "text": "Once you have Node.js package manager installed then you can proceed to install Solidity compiler as below −" }, { "code": null, "e": 3476, "s": 3450, "text": "$sudonpm install -g solc\n" }, { "code": null, "e": 3653, "s": 3476, "text": "The above command will install solcjs program and will make it available globally through out the system. Now you can test your Solidity compiler by issuing following command −" }, { "code": null, "e": 3670, "s": 3653, "text": "$solcjs-version\n" }, { "code": null, "e": 3739, "s": 3670, "text": "If everything goes fine, then this will print something as follows −" }, { "code": null, "e": 3779, "s": 3739, "text": "0.5.2+commit.1df8f40c.Emscripten.clang\n" }, { "code": null, "e": 3916, "s": 3779, "text": "Now you are ready to use solcjs which has fewer features than the standard Solidity compiler but it will give you a good starting point." }, { "code": null, "e": 4089, "s": 3916, "text": "You can pull a Docker image and start using it to start with Solidity programming. Following are the simple steps. Following is the command to pull a Solidity Docker Image." }, { "code": null, "e": 4124, "s": 4089, "text": "$docker pull ethereum/solc:stable\n" }, { "code": null, "e": 4204, "s": 4124, "text": "Once a docker image is downloaded we can verify it using the following command." }, { "code": null, "e": 4246, "s": 4204, "text": "$docker run ethereum/solc:stable-version\n" }, { "code": null, "e": 4285, "s": 4246, "text": "This will print something as follows −" }, { "code": null, "e": 4419, "s": 4285, "text": "$ docker run ethereum/solc:stable -version\n\nsolc, the solidity compiler commandlineinterfaceVersion: 0.5.2+commit.1df8f40c.Linux.g++\n" }, { "code": null, "e": 4563, "s": 4419, "text": "If you are willing to install full fledged compiler on your Linux machine, then please check official website Installing the Solidity Compiler." }, { "code": null, "e": 4598, "s": 4563, "text": "\n 38 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4615, "s": 4598, "text": " Abhilash Nelson" }, { "code": null, "e": 4650, "s": 4615, "text": "\n 62 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4667, "s": 4650, "text": " Frahaan Hussain" }, { "code": null, "e": 4702, "s": 4667, "text": "\n 31 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4716, "s": 4702, "text": " Swapnil Kole" }, { "code": null, "e": 4723, "s": 4716, "text": " Print" }, { "code": null, "e": 4734, "s": 4723, "text": " Add Notes" } ]
JavaScript Proxy() Object
The JavaScript proxy() object wraps an object or function and is used for custom actions for fundamental operations like accessing property , invoking function etc. Following is the code for proxy() object in JavaScript − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .sample { font-size: 18px; font-weight: 500; color: red; } </style> </head> <body> <h1>JavaScript Proxy() Object</h1> <div class="sample"></div> <button class="Btn">CLICK HERE</button> <h3> Click on the above button to access object values using proxy object </h3> <script> let sampleEle = document.querySelector('.sample'); const test = { Name: 'Rohan Sharma', birthYear: 1990, }; const handler = { get: function(target, objectKey) { if (objectKey === 'FirstName') { return target.Name.split(' ')[0]; } if (objectKey === 'CurrentAge') { let date = new Date(); return date.getFullYear() - target.birthYear; } else { return Reflect.get(target,objectKey); } } }; const proxy1 = new Proxy(test, handler); document.querySelector('.Btn').addEventListener('click',()=>{ sampleEle.innerHTML += 'proxy1.Firstname = ' + proxy1.FirstName + '<br>'; sampleEle.innerHTML += 'proxy1.CurrentAge = ' + proxy1.CurrentAge + '<br>'; }) </script> </body> </html> On clicking the ‘CLICK HERE’ button −
[ { "code": null, "e": 1227, "s": 1062, "text": "The JavaScript proxy() object wraps an object or function and is used for custom actions for fundamental operations like accessing property , invoking function etc." }, { "code": null, "e": 1284, "s": 1227, "text": "Following is the code for proxy() object in JavaScript −" }, { "code": null, "e": 1295, "s": 1284, "text": " Live Demo" }, { "code": null, "e": 2668, "s": 1295, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .sample {\n font-size: 18px;\n font-weight: 500;\n color: red;\n }\n</style>\n</head>\n<body>\n<h1>JavaScript Proxy() Object</h1>\n<div class=\"sample\"></div>\n<button class=\"Btn\">CLICK HERE</button>\n<h3>\nClick on the above button to access object values using proxy object\n</h3>\n<script>\n let sampleEle = document.querySelector('.sample');\n const test = {\n Name: 'Rohan Sharma',\n birthYear: 1990,\n };\n const handler = {\n get: function(target, objectKey) {\n if (objectKey === 'FirstName') {\n return target.Name.split(' ')[0];\n }\n if (objectKey === 'CurrentAge') {\n let date = new Date();\n return date.getFullYear() - target.birthYear;\n } else {\n return Reflect.get(target,objectKey);\n }\n }\n };\n const proxy1 = new Proxy(test, handler);\n document.querySelector('.Btn').addEventListener('click',()=>{\n sampleEle.innerHTML += 'proxy1.Firstname = ' + proxy1.FirstName + '<br>';\n sampleEle.innerHTML += 'proxy1.CurrentAge = ' + proxy1.CurrentAge + '<br>';\n })\n</script>\n</body>\n</html>" }, { "code": null, "e": 2706, "s": 2668, "text": "On clicking the ‘CLICK HERE’ button −" } ]
C | String | Question 5 - GeeksforGeeks
05 Feb, 2013 What does the following fragment of C-program print? char c[] = "GATE2011"; char *p =c; printf("%s", p + p[3] - p[1]) ; (A) GATE2011(B) E2011(C) 2011(D) 011Answer: (C)Explanation: See comments for explanation. char c[] = "GATE2011"; // p now has the base address string "GATE2011" char *p = c; // p[3] is 'E' and p[1] is 'A'. // p[3] - p[1] = ASCII value of 'E' - ASCII value of 'A' = 4 // So the expression p + p[3] - p[1] becomes p + 4 which is // base address of string "2011" printf("%s", p + p[3] - p[1]); // prints 2011 C-String C-String-Question C Language C Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in C / C++ rand() and srand() in C/C++ fork() in C Core Dump (Segmentation fault) in C/C++ Left Shift and Right Shift Operators in C/C++ Compiling a C program:- Behind the Scenes Operator Precedence and Associativity in C C | Pointer Basics | Question 15 C | Structure & Union | Question 4 C | File Handling | Question 1
[ { "code": null, "e": 24051, "s": 24023, "text": "\n05 Feb, 2013" }, { "code": null, "e": 24104, "s": 24051, "text": "What does the following fragment of C-program print?" }, { "code": "char c[] = \"GATE2011\"; char *p =c; printf(\"%s\", p + p[3] - p[1]) ;", "e": 24171, "s": 24104, "text": null }, { "code": null, "e": 24261, "s": 24171, "text": "(A) GATE2011(B) E2011(C) 2011(D) 011Answer: (C)Explanation: See comments for explanation." }, { "code": null, "e": 24593, "s": 24261, "text": "\nchar c[] = \"GATE2011\"; \n \n // p now has the base address string \"GATE2011\" \nchar *p = c; \n \n// p[3] is 'E' and p[1] is 'A'. \n// p[3] - p[1] = ASCII value of 'E' - ASCII value of 'A' = 4 \n// So the expression p + p[3] - p[1] becomes p + 4 which is \n// base address of string \"2011\" \nprintf(\"%s\", p + p[3] - p[1]); // prints 2011" }, { "code": null, "e": 24602, "s": 24593, "text": "C-String" }, { "code": null, "e": 24620, "s": 24602, "text": "C-String-Question" }, { "code": null, "e": 24631, "s": 24620, "text": "C Language" }, { "code": null, "e": 24638, "s": 24631, "text": "C Quiz" }, { "code": null, "e": 24736, "s": 24638, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24771, "s": 24736, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 24799, "s": 24771, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 24811, "s": 24799, "text": "fork() in C" }, { "code": null, "e": 24851, "s": 24811, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 24897, "s": 24851, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 24939, "s": 24897, "text": "Compiling a C program:- Behind the Scenes" }, { "code": null, "e": 24982, "s": 24939, "text": "Operator Precedence and Associativity in C" }, { "code": null, "e": 25015, "s": 24982, "text": "C | Pointer Basics | Question 15" }, { "code": null, "e": 25050, "s": 25015, "text": "C | Structure & Union | Question 4" } ]
Minimize operations to make given binary string as all 1s by repeatedly converting K consecutive characters to 1 - GeeksforGeeks
20 Dec, 2021 Given a binary string str of N characters an integer K, the task is to find the minimum moves required to convert all characters of the string to 1’s where at each move, K consecutive characters can be converted to 1. Example: Input: str=”0010′′, K=3Output: 2Explanation:Move 1: Select the substring from 0 to 2 and replace it with all 1.Move 2: Select the substring from 1 to 3 and replace it with all 1. Input: str=”0000010′′, K=1Output: 6 Approach: This problem can be solved using a greedy approach. To solve this problem, follow the below steps: Create a variable cnt, to store the minimum number of moves required. Initialize it with 0.Traverse the string using a variable i and str[i] = ‘0’, then update i to i + K and increase cnt by 1, because no matter what these characters are, a move is always required to convert the character str[i] to ‘1’.After the loop ends, return cnt which will be the required answer. Create a variable cnt, to store the minimum number of moves required. Initialize it with 0. Traverse the string using a variable i and str[i] = ‘0’, then update i to i + K and increase cnt by 1, because no matter what these characters are, a move is always required to convert the character str[i] to ‘1’. After the loop ends, return cnt which will be the required answer. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ code for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum// operations required to convert// the binary string str to all 1sint minMoves(string str, int K){ int N = str.size(); // Variable to store number // of minimum moves required int cnt = 0; int i = 0; // Loop to traverse str while (i < N) { // If element is '0' if (str[i] == '0') { i += K; cnt += 1; } // If element is '1' else { i++; } } return cnt;} // Driver Codeint main(){ string str = "0010"; int K = 3; cout << minMoves(str, K);} // Java code for the above approachclass GFG { // Function to find the minimum // operations required to convert // the binary String str to all 1s static int minMoves(String str, int K) { int N = str.length(); // Variable to store number // of minimum moves required int cnt = 0; int i = 0; // Loop to traverse str while (i < N) { // If element is '0' if (str.charAt(i) == '0') { i += K; cnt += 1; } // If element is '1' else { i++; } } return cnt; } // Driver Code public static void main(String args[]) { String str = "0010"; int K = 3; System.out.println(minMoves(str, K)); }} // This code is contributed by Saurabh Jaiswal # Python code for the above approach # Function to find the minimum# operations required to convert# the binary string str to all 1sdef minMoves(str, K): N = len(str) # Variable to store number # of minimum moves required cnt = 0 i = 0 # Loop to traverse str while (i < N): # If element is '0' if (str[i] == '0'): i += K cnt += 1 # If element is '1' else: i += 1 return cnt # Driver Codestr = "0010"K = 3print(minMoves(str, K)) # This code is contributed by Saurabh Jaiswal // C# code for the above approachusing System; class GFG{ // Function to find the minimum// operations required to convert// the binary string str to all 1sstatic int minMoves(string str, int K){ int N = str.Length; // Variable to store number // of minimum moves required int cnt = 0; int i = 0; // Loop to traverse str while (i < N) { // If element is '0' if (str[i] == '0') { i += K; cnt += 1; } // If element is '1' else { i++; } } return cnt;} // Driver Codepublic static void Main(){ string str = "0010"; int K = 3; Console.Write(minMoves(str, K));}} // This code is contributed by Samim Hossain Mondal. <script> // JavaScript code for the above approach // Function to find the minimum // operations required to convert // the binary string str to all 1s function minMoves(str, K) { let N = str.length; // Variable to store number // of minimum moves required let cnt = 0; let i = 0; // Loop to traverse str while (i < N) { // If element is '0' if (str[i] == '0') { i += K; cnt += 1; } // If element is '1' else { i++; } } return cnt; } // Driver Code let str = "0010"; let K = 3; document.write(minMoves(str, K)); // This code is contributed by Potta Lokesh </script> 2 Time Complexity: O(N)Auxiliary Space: O(1) lokeshpotta20 samim2000 _saurabh_jaiswal binary-string Greedy Strings Strings Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Optimal Page Replacement Algorithm Program for Best Fit algorithm in Memory Management Program for First Fit algorithm in Memory Management Bin Packing Problem (Minimize number of used Bins) Max Flow Problem Introduction Write a program to reverse an array or string Reverse a string in Java C++ Data Types Longest Common Subsequence | DP-4 Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 26537, "s": 26509, "text": "\n20 Dec, 2021" }, { "code": null, "e": 26755, "s": 26537, "text": "Given a binary string str of N characters an integer K, the task is to find the minimum moves required to convert all characters of the string to 1’s where at each move, K consecutive characters can be converted to 1." }, { "code": null, "e": 26764, "s": 26755, "text": "Example:" }, { "code": null, "e": 26943, "s": 26764, "text": "Input: str=”0010′′, K=3Output: 2Explanation:Move 1: Select the substring from 0 to 2 and replace it with all 1.Move 2: Select the substring from 1 to 3 and replace it with all 1." }, { "code": null, "e": 26979, "s": 26943, "text": "Input: str=”0000010′′, K=1Output: 6" }, { "code": null, "e": 27088, "s": 26979, "text": "Approach: This problem can be solved using a greedy approach. To solve this problem, follow the below steps:" }, { "code": null, "e": 27459, "s": 27088, "text": "Create a variable cnt, to store the minimum number of moves required. Initialize it with 0.Traverse the string using a variable i and str[i] = ‘0’, then update i to i + K and increase cnt by 1, because no matter what these characters are, a move is always required to convert the character str[i] to ‘1’.After the loop ends, return cnt which will be the required answer." }, { "code": null, "e": 27551, "s": 27459, "text": "Create a variable cnt, to store the minimum number of moves required. Initialize it with 0." }, { "code": null, "e": 27765, "s": 27551, "text": "Traverse the string using a variable i and str[i] = ‘0’, then update i to i + K and increase cnt by 1, because no matter what these characters are, a move is always required to convert the character str[i] to ‘1’." }, { "code": null, "e": 27832, "s": 27765, "text": "After the loop ends, return cnt which will be the required answer." }, { "code": null, "e": 27883, "s": 27832, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27887, "s": 27883, "text": "C++" }, { "code": null, "e": 27892, "s": 27887, "text": "Java" }, { "code": null, "e": 27900, "s": 27892, "text": "Python3" }, { "code": null, "e": 27903, "s": 27900, "text": "C#" }, { "code": null, "e": 27914, "s": 27903, "text": "Javascript" }, { "code": "// C++ code for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum// operations required to convert// the binary string str to all 1sint minMoves(string str, int K){ int N = str.size(); // Variable to store number // of minimum moves required int cnt = 0; int i = 0; // Loop to traverse str while (i < N) { // If element is '0' if (str[i] == '0') { i += K; cnt += 1; } // If element is '1' else { i++; } } return cnt;} // Driver Codeint main(){ string str = \"0010\"; int K = 3; cout << minMoves(str, K);}", "e": 28579, "s": 27914, "text": null }, { "code": "// Java code for the above approachclass GFG { // Function to find the minimum // operations required to convert // the binary String str to all 1s static int minMoves(String str, int K) { int N = str.length(); // Variable to store number // of minimum moves required int cnt = 0; int i = 0; // Loop to traverse str while (i < N) { // If element is '0' if (str.charAt(i) == '0') { i += K; cnt += 1; } // If element is '1' else { i++; } } return cnt; } // Driver Code public static void main(String args[]) { String str = \"0010\"; int K = 3; System.out.println(minMoves(str, K)); }} // This code is contributed by Saurabh Jaiswal", "e": 29434, "s": 28579, "text": null }, { "code": "# Python code for the above approach # Function to find the minimum# operations required to convert# the binary string str to all 1sdef minMoves(str, K): N = len(str) # Variable to store number # of minimum moves required cnt = 0 i = 0 # Loop to traverse str while (i < N): # If element is '0' if (str[i] == '0'): i += K cnt += 1 # If element is '1' else: i += 1 return cnt # Driver Codestr = \"0010\"K = 3print(minMoves(str, K)) # This code is contributed by Saurabh Jaiswal", "e": 29998, "s": 29434, "text": null }, { "code": "// C# code for the above approachusing System; class GFG{ // Function to find the minimum// operations required to convert// the binary string str to all 1sstatic int minMoves(string str, int K){ int N = str.Length; // Variable to store number // of minimum moves required int cnt = 0; int i = 0; // Loop to traverse str while (i < N) { // If element is '0' if (str[i] == '0') { i += K; cnt += 1; } // If element is '1' else { i++; } } return cnt;} // Driver Codepublic static void Main(){ string str = \"0010\"; int K = 3; Console.Write(minMoves(str, K));}} // This code is contributed by Samim Hossain Mondal.", "e": 30727, "s": 29998, "text": null }, { "code": "<script> // JavaScript code for the above approach // Function to find the minimum // operations required to convert // the binary string str to all 1s function minMoves(str, K) { let N = str.length; // Variable to store number // of minimum moves required let cnt = 0; let i = 0; // Loop to traverse str while (i < N) { // If element is '0' if (str[i] == '0') { i += K; cnt += 1; } // If element is '1' else { i++; } } return cnt; } // Driver Code let str = \"0010\"; let K = 3; document.write(minMoves(str, K)); // This code is contributed by Potta Lokesh </script>", "e": 31594, "s": 30727, "text": null }, { "code": null, "e": 31599, "s": 31597, "text": "2" }, { "code": null, "e": 31644, "s": 31601, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 31660, "s": 31646, "text": "lokeshpotta20" }, { "code": null, "e": 31670, "s": 31660, "text": "samim2000" }, { "code": null, "e": 31687, "s": 31670, "text": "_saurabh_jaiswal" }, { "code": null, "e": 31701, "s": 31687, "text": "binary-string" }, { "code": null, "e": 31708, "s": 31701, "text": "Greedy" }, { "code": null, "e": 31716, "s": 31708, "text": "Strings" }, { "code": null, "e": 31724, "s": 31716, "text": "Strings" }, { "code": null, "e": 31731, "s": 31724, "text": "Greedy" }, { "code": null, "e": 31829, "s": 31731, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31864, "s": 31829, "text": "Optimal Page Replacement Algorithm" }, { "code": null, "e": 31916, "s": 31864, "text": "Program for Best Fit algorithm in Memory Management" }, { "code": null, "e": 31969, "s": 31916, "text": "Program for First Fit algorithm in Memory Management" }, { "code": null, "e": 32020, "s": 31969, "text": "Bin Packing Problem (Minimize number of used Bins)" }, { "code": null, "e": 32050, "s": 32020, "text": "Max Flow Problem Introduction" }, { "code": null, "e": 32096, "s": 32050, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 32121, "s": 32096, "text": "Reverse a string in Java" }, { "code": null, "e": 32136, "s": 32121, "text": "C++ Data Types" }, { "code": null, "e": 32170, "s": 32136, "text": "Longest Common Subsequence | DP-4" } ]
Maximum sum subarray of even length - GeeksforGeeks
22 Mar, 2022 Given an array arr[] of N elements, the task is to find the maximum sum of any subarray of length X such that X > 0 and X % 2 = 0.Examples: Input: arr[] = {1, 2, 3} Output: 5 {2, 3} is the required subarray.Input: arr[] = {8, 9, -8, 9, 10} Output: 20 {9, -8, 9, 10} is the required subarray. Even though {8, 9, -8, 9, 10} has the maximum sum but it is not of even length. Approach: This problem is a variation of maximum subarray sum problem and can be solved using dynamic programming approach. Create an array dp[] where dp[i] will store the maximum sum of an even length subarray whose first element is arr[i]. Now the recurrence relation will be: dp[i] = max((arr[i] + arr[i + 1]), (arr[i] + arr[i + 1] + dp[i + 2])) This is because the maximum sum even length subarray starting with the element arr[i] can either be the sum of arr[i] and arr[i + 1] or it can be arr[i] + arr[i + 1] added with the maximum sum of even length subarray starting with arr[i + 2] i.e. dp[i + 2]. Take the maximum of these two. In the end, the maximum value from the dp[] array will be the required answer.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; // Function to return the maximum// subarray sum of even lengthint maxEvenLenSum(int arr[], int n){ // There has to be at // least 2 elements if (n < 2) return 0; // dp[i] will store the maximum // subarray sum of even length // starting at arr[i] int dp[n] = { 0 }; // Valid subarray cannot start from // the last element as its // length has to be even dp[n - 1] = 0; dp[n - 2] = arr[n - 2] + arr[n - 1]; for (int i = n - 3; i >= 0; i--) { // arr[i] and arr[i + 1] can be added // to get an even length subarray // starting at arr[i] dp[i] = arr[i] + arr[i + 1]; // If the sum of the valid subarray starting // from arr[i + 2] is greater than 0 then it // can be added with arr[i] and arr[i + 1] // to maximize the sum of the subarray // starting from arr[i] if (dp[i + 2] > 0) dp[i] += dp[i + 2]; } // Get the sum of the even length // subarray with maximum sum int maxSum = *max_element(dp, dp + n); return maxSum;} // Driver codeint main(){ int arr[] = { 8, 9, -8, 9, 10 }; int n = sizeof(arr) / sizeof(int); cout << maxEvenLenSum(arr, n); return 0;} // Java implementation of the approachimport java.util.Arrays; class GFG{ // Function to return the maximum// subarray sum of even lengthstatic int maxEvenLenSum(int arr[], int n){ // There has to be at // least 2 elements if (n < 2) return 0; // dp[i] will store the maximum // subarray sum of even length // starting at arr[i] int []dp = new int[n]; // Valid subarray cannot start from // the last element as its // length has to be even dp[n - 1] = 0; dp[n - 2] = arr[n - 2] + arr[n - 1]; for (int i = n - 3; i >= 0; i--) { // arr[i] and arr[i + 1] can be added // to get an even length subarray // starting at arr[i] dp[i] = arr[i] + arr[i + 1]; // If the sum of the valid subarray starting // from arr[i + 2] is greater than 0 then it // can be added with arr[i] and arr[i + 1] // to maximize the sum of the subarray // starting from arr[i] if (dp[i + 2] > 0) dp[i] += dp[i + 2]; } // Get the sum of the even length // subarray with maximum sum int maxSum = Arrays.stream(dp).max().getAsInt(); return maxSum;} // Driver codepublic static void main(String[] args){ int arr[] = { 8, 9, -8, 9, 10 }; int n = arr.length; System.out.println(maxEvenLenSum(arr, n));}} // This code is contributed by 29AjayKumar # Python3 implementation of the approach # Function to return the maximum# subarray sum of even lengthdef maxEvenLenSum(arr, n): # There has to be at # least 2 elements if (n < 2): return 0 # dp[i] will store the maximum # subarray sum of even length # starting at arr[i] dp = [0 for i in range(n)] # Valid subarray cannot start from # the last element as its # length has to be even dp[n - 1] = 0 dp[n - 2] = arr[n - 2] + arr[n - 1] for i in range(n - 3, -1, -1): # arr[i] and arr[i + 1] can be added # to get an even length subarray # starting at arr[i] dp[i] = arr[i] + arr[i + 1] # If the sum of the valid subarray # starting from arr[i + 2] is # greater than 0 then it can be added # with arr[i] and arr[i + 1] # to maximize the sum of the # subarray starting from arr[i] if (dp[i + 2] > 0): dp[i] += dp[i + 2] # Get the sum of the even length # subarray with maximum sum maxSum = max(dp) return maxSum # Driver codearr = [8, 9, -8, 9, 10]n = len(arr) print(maxEvenLenSum(arr, n)) # This code is contributed by Mohit Kumar // C# implementation of the approachusing System; class GFG{ static int MaxSum(int []arr) { // assigning first element to the array int large = arr[0]; // loop to compare value of large // with other elements for (int i = 1; i < arr.Length; i++) { // if large is smaller than other element // assign that element to the large if (large < arr[i]) large = arr[i]; } return large; } // Function to return the maximum // subarray sum of even length static int maxEvenLenSum(int []arr, int n) { // There has to be at // least 2 elements if (n < 2) return 0; // dp[i] will store the maximum // subarray sum of even length // starting at arr[i] int []dp = new int[n]; // Valid subarray cannot start from // the last element as its // length has to be even dp[n - 1] = 0; dp[n - 2] = arr[n - 2] + arr[n - 1]; for (int i = n - 3; i >= 0; i--) { // arr[i] and arr[i + 1] can be added // to get an even length subarray // starting at arr[i] dp[i] = arr[i] + arr[i + 1]; // If the sum of the valid subarray starting // from arr[i + 2] is greater than 0 then it // can be added with arr[i] and arr[i + 1] // to maximize the sum of the subarray // starting from arr[i] if (dp[i + 2] > 0) dp[i] += dp[i + 2]; } // Get the sum of the even length // subarray with maximum sum int maxSum = MaxSum(dp); return maxSum; } // Driver code public static void Main() { int []arr = { 8, 9, -8, 9, 10 }; int n = arr.Length; Console.WriteLine(maxEvenLenSum(arr, n)); }} // This code is contributed by kanugargng <script>// Javascript implementation of the approach // Function to return the maximum// subarray sum of even lengthfunction maxEvenLenSum(arr, n) { // There has to be at // least 2 elements if (n < 2) return 0; // dp[i] will store the maximum // subarray sum of even length // starting at arr[i] let dp = new Array(n).fill(0); // Valid subarray cannot start from // the last element as its // length has to be even dp[n - 1] = 0; dp[n - 2] = arr[n - 2] + arr[n - 1]; for (let i = n - 3; i >= 0; i--) { // arr[i] and arr[i + 1] can be added // to get an even length subarray // starting at arr[i] dp[i] = arr[i] + arr[i + 1]; // If the sum of the valid subarray starting // from arr[i + 2] is greater than 0 then it // can be added with arr[i] and arr[i + 1] // to maximize the sum of the subarray // starting from arr[i] if (dp[i + 2] > 0) dp[i] += dp[i + 2]; } // Get the sum of the even length // subarray with maximum sum let maxSum = dp.sort((a, b) => b - a)[0]; return maxSum;} // Driver codelet arr = [8, 9, -8, 9, 10];let n = arr.length; document.write(maxEvenLenSum(arr, n)); // This code is contributed by _saurabh_jaiswal.</script> 20 Time complexity: O(n) Space complexity: O(n) mohit kumar 29 29AjayKumar kanugargng _saurabh_jaiswal sweetyty subarray subarray-sum Algorithms Arrays Competitive Programming Dynamic Programming Arrays Dynamic Programming Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar How to Start Learning DSA? Difference between Algorithm, Pseudocode and Program K means Clustering - Introduction Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Arrays in Java Arrays in C/C++ Maximum and minimum of an array using minimum number of comparisons Write a program to reverse an array or string Program for array rotation
[ { "code": null, "e": 25943, "s": 25915, "text": "\n22 Mar, 2022" }, { "code": null, "e": 26085, "s": 25943, "text": "Given an array arr[] of N elements, the task is to find the maximum sum of any subarray of length X such that X > 0 and X % 2 = 0.Examples: " }, { "code": null, "e": 26319, "s": 26085, "text": "Input: arr[] = {1, 2, 3} Output: 5 {2, 3} is the required subarray.Input: arr[] = {8, 9, -8, 9, 10} Output: 20 {9, -8, 9, 10} is the required subarray. Even though {8, 9, -8, 9, 10} has the maximum sum but it is not of even length. " }, { "code": null, "e": 26602, "s": 26321, "text": "Approach: This problem is a variation of maximum subarray sum problem and can be solved using dynamic programming approach. Create an array dp[] where dp[i] will store the maximum sum of an even length subarray whose first element is arr[i]. Now the recurrence relation will be: " }, { "code": null, "e": 26672, "s": 26602, "text": "dp[i] = max((arr[i] + arr[i + 1]), (arr[i] + arr[i + 1] + dp[i + 2]))" }, { "code": null, "e": 27093, "s": 26672, "text": " This is because the maximum sum even length subarray starting with the element arr[i] can either be the sum of arr[i] and arr[i + 1] or it can be arr[i] + arr[i + 1] added with the maximum sum of even length subarray starting with arr[i + 2] i.e. dp[i + 2]. Take the maximum of these two. In the end, the maximum value from the dp[] array will be the required answer.Below is the implementation of the above approach: " }, { "code": null, "e": 27097, "s": 27093, "text": "C++" }, { "code": null, "e": 27102, "s": 27097, "text": "Java" }, { "code": null, "e": 27110, "s": 27102, "text": "Python3" }, { "code": null, "e": 27113, "s": 27110, "text": "C#" }, { "code": null, "e": 27124, "s": 27113, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum// subarray sum of even lengthint maxEvenLenSum(int arr[], int n){ // There has to be at // least 2 elements if (n < 2) return 0; // dp[i] will store the maximum // subarray sum of even length // starting at arr[i] int dp[n] = { 0 }; // Valid subarray cannot start from // the last element as its // length has to be even dp[n - 1] = 0; dp[n - 2] = arr[n - 2] + arr[n - 1]; for (int i = n - 3; i >= 0; i--) { // arr[i] and arr[i + 1] can be added // to get an even length subarray // starting at arr[i] dp[i] = arr[i] + arr[i + 1]; // If the sum of the valid subarray starting // from arr[i + 2] is greater than 0 then it // can be added with arr[i] and arr[i + 1] // to maximize the sum of the subarray // starting from arr[i] if (dp[i + 2] > 0) dp[i] += dp[i + 2]; } // Get the sum of the even length // subarray with maximum sum int maxSum = *max_element(dp, dp + n); return maxSum;} // Driver codeint main(){ int arr[] = { 8, 9, -8, 9, 10 }; int n = sizeof(arr) / sizeof(int); cout << maxEvenLenSum(arr, n); return 0;}", "e": 28426, "s": 27124, "text": null }, { "code": "// Java implementation of the approachimport java.util.Arrays; class GFG{ // Function to return the maximum// subarray sum of even lengthstatic int maxEvenLenSum(int arr[], int n){ // There has to be at // least 2 elements if (n < 2) return 0; // dp[i] will store the maximum // subarray sum of even length // starting at arr[i] int []dp = new int[n]; // Valid subarray cannot start from // the last element as its // length has to be even dp[n - 1] = 0; dp[n - 2] = arr[n - 2] + arr[n - 1]; for (int i = n - 3; i >= 0; i--) { // arr[i] and arr[i + 1] can be added // to get an even length subarray // starting at arr[i] dp[i] = arr[i] + arr[i + 1]; // If the sum of the valid subarray starting // from arr[i + 2] is greater than 0 then it // can be added with arr[i] and arr[i + 1] // to maximize the sum of the subarray // starting from arr[i] if (dp[i + 2] > 0) dp[i] += dp[i + 2]; } // Get the sum of the even length // subarray with maximum sum int maxSum = Arrays.stream(dp).max().getAsInt(); return maxSum;} // Driver codepublic static void main(String[] args){ int arr[] = { 8, 9, -8, 9, 10 }; int n = arr.length; System.out.println(maxEvenLenSum(arr, n));}} // This code is contributed by 29AjayKumar", "e": 29798, "s": 28426, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the maximum# subarray sum of even lengthdef maxEvenLenSum(arr, n): # There has to be at # least 2 elements if (n < 2): return 0 # dp[i] will store the maximum # subarray sum of even length # starting at arr[i] dp = [0 for i in range(n)] # Valid subarray cannot start from # the last element as its # length has to be even dp[n - 1] = 0 dp[n - 2] = arr[n - 2] + arr[n - 1] for i in range(n - 3, -1, -1): # arr[i] and arr[i + 1] can be added # to get an even length subarray # starting at arr[i] dp[i] = arr[i] + arr[i + 1] # If the sum of the valid subarray # starting from arr[i + 2] is # greater than 0 then it can be added # with arr[i] and arr[i + 1] # to maximize the sum of the # subarray starting from arr[i] if (dp[i + 2] > 0): dp[i] += dp[i + 2] # Get the sum of the even length # subarray with maximum sum maxSum = max(dp) return maxSum # Driver codearr = [8, 9, -8, 9, 10]n = len(arr) print(maxEvenLenSum(arr, n)) # This code is contributed by Mohit Kumar", "e": 30979, "s": 29798, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ static int MaxSum(int []arr) { // assigning first element to the array int large = arr[0]; // loop to compare value of large // with other elements for (int i = 1; i < arr.Length; i++) { // if large is smaller than other element // assign that element to the large if (large < arr[i]) large = arr[i]; } return large; } // Function to return the maximum // subarray sum of even length static int maxEvenLenSum(int []arr, int n) { // There has to be at // least 2 elements if (n < 2) return 0; // dp[i] will store the maximum // subarray sum of even length // starting at arr[i] int []dp = new int[n]; // Valid subarray cannot start from // the last element as its // length has to be even dp[n - 1] = 0; dp[n - 2] = arr[n - 2] + arr[n - 1]; for (int i = n - 3; i >= 0; i--) { // arr[i] and arr[i + 1] can be added // to get an even length subarray // starting at arr[i] dp[i] = arr[i] + arr[i + 1]; // If the sum of the valid subarray starting // from arr[i + 2] is greater than 0 then it // can be added with arr[i] and arr[i + 1] // to maximize the sum of the subarray // starting from arr[i] if (dp[i + 2] > 0) dp[i] += dp[i + 2]; } // Get the sum of the even length // subarray with maximum sum int maxSum = MaxSum(dp); return maxSum; } // Driver code public static void Main() { int []arr = { 8, 9, -8, 9, 10 }; int n = arr.Length; Console.WriteLine(maxEvenLenSum(arr, n)); }} // This code is contributed by kanugargng", "e": 32962, "s": 30979, "text": null }, { "code": "<script>// Javascript implementation of the approach // Function to return the maximum// subarray sum of even lengthfunction maxEvenLenSum(arr, n) { // There has to be at // least 2 elements if (n < 2) return 0; // dp[i] will store the maximum // subarray sum of even length // starting at arr[i] let dp = new Array(n).fill(0); // Valid subarray cannot start from // the last element as its // length has to be even dp[n - 1] = 0; dp[n - 2] = arr[n - 2] + arr[n - 1]; for (let i = n - 3; i >= 0; i--) { // arr[i] and arr[i + 1] can be added // to get an even length subarray // starting at arr[i] dp[i] = arr[i] + arr[i + 1]; // If the sum of the valid subarray starting // from arr[i + 2] is greater than 0 then it // can be added with arr[i] and arr[i + 1] // to maximize the sum of the subarray // starting from arr[i] if (dp[i + 2] > 0) dp[i] += dp[i + 2]; } // Get the sum of the even length // subarray with maximum sum let maxSum = dp.sort((a, b) => b - a)[0]; return maxSum;} // Driver codelet arr = [8, 9, -8, 9, 10];let n = arr.length; document.write(maxEvenLenSum(arr, n)); // This code is contributed by _saurabh_jaiswal.</script>", "e": 34254, "s": 32962, "text": null }, { "code": null, "e": 34257, "s": 34254, "text": "20" }, { "code": null, "e": 34305, "s": 34259, "text": "Time complexity: O(n) Space complexity: O(n) " }, { "code": null, "e": 34320, "s": 34305, "text": "mohit kumar 29" }, { "code": null, "e": 34332, "s": 34320, "text": "29AjayKumar" }, { "code": null, "e": 34343, "s": 34332, "text": "kanugargng" }, { "code": null, "e": 34360, "s": 34343, "text": "_saurabh_jaiswal" }, { "code": null, "e": 34369, "s": 34360, "text": "sweetyty" }, { "code": null, "e": 34378, "s": 34369, "text": "subarray" }, { "code": null, "e": 34391, "s": 34378, "text": "subarray-sum" }, { "code": null, "e": 34402, "s": 34391, "text": "Algorithms" }, { "code": null, "e": 34409, "s": 34402, "text": "Arrays" }, { "code": null, "e": 34433, "s": 34409, "text": "Competitive Programming" }, { "code": null, "e": 34453, "s": 34433, "text": "Dynamic Programming" }, { "code": null, "e": 34460, "s": 34453, "text": "Arrays" }, { "code": null, "e": 34480, "s": 34460, "text": "Dynamic Programming" }, { "code": null, "e": 34491, "s": 34480, "text": "Algorithms" }, { "code": null, "e": 34589, "s": 34491, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34614, "s": 34589, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 34641, "s": 34614, "text": "How to Start Learning DSA?" }, { "code": null, "e": 34694, "s": 34641, "text": "Difference between Algorithm, Pseudocode and Program" }, { "code": null, "e": 34728, "s": 34694, "text": "K means Clustering - Introduction" }, { "code": null, "e": 34795, "s": 34728, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 34810, "s": 34795, "text": "Arrays in Java" }, { "code": null, "e": 34826, "s": 34810, "text": "Arrays in C/C++" }, { "code": null, "e": 34894, "s": 34826, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 34940, "s": 34894, "text": "Write a program to reverse an array or string" } ]
Find if an undirected graph contains an independent set of a given size - GeeksforGeeks
07 Apr, 2022 Given an undirected graph, check if it contains an independent set of size k. Print ‘Yes’ if there exists an independent set of size k. Print ‘No’ otherwise. Independent Set: An independent set in a graph is a set of vertices that are not directly connected to each other. Example 1: Input : K = 4, graph = [[1, 1, 0, 0, 0], [1, 1, 1, 1, 1], [0, 1, 1, 0, 0], [0, 1, 0, 1, 0], [0, 1, 0, 0, 1]] Output : Yes The above graph contains an independent set of size 4 (vertices 1, 2, 3, 4 are not directly connected to each other). Hence, the output is ‘Yes’. Example 2: Input : K = 4, graph = [[1, 1, 0, 0, 0], [1, 1, 1, 1, 1], [0, 1, 1, 0, 0], [0, 1, 0, 1, 1], [0, 1, 0, 1, 1]] Output : No The above graph doesn’t contain an independent set of size 4. Hence, the output is ‘No’. Approach: Initialize a variable sol with boolean False value. Find all the possible sets of vertices of size K from the given graph. If an independent set of size k is found, change the value of sol to True and return. Else continue checking for other possible sets. In the end, if sol is True, print ‘Yes’ else print ‘No’. Below is the implementation of the above approach: C++14 Java Python3 C# Javascript // C++ code to check if a given graph// contains an independent set of size k#include <bits/stdc++.h>using namespace std; // Function prototypebool check(int[][5], vector<int> &, int); // Function to construct a set of given size kbool func(int graph[][5], vector<int> &arr, int k, int index, bool sol[]){ // Check if the selected set is independent or not. // Change the value of sol to True and return // if it is independent if (k == 0) { if (check(graph, arr, arr.size())) { sol[0] = true; return true; } } else { // Set of size k can be formed even if we don't // include the vertex at current index. if (index >= k) { vector<int> newvec(arr.begin(), arr.end()); newvec.push_back(index); return (func(graph, newvec, k - 1, index - 1, sol) or func(graph, arr, k, index - 1, sol)); } // Set of size k cannot be formed if we don't // include the vertex at current index. else { arr.push_back(index); return func(graph, arr, k - 1, index - 1, sol); } }} // Function to check if the given set is// independent or not// arr --> set of size k (contains the// index of included vertex)bool check(int graph[][5], vector<int> &arr, int n){ // Check if each vertex is connected to any other // vertex in the set or not for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (graph[arr[i]][arr[j]] == 1) return false; return true;} // Driver Codeint main(){ int graph[][5] = {{1, 1, 0, 0, 0}, {1, 1, 1, 1, 1}, {0, 1, 1, 0, 0}, {0, 1, 0, 1, 0}, {0, 1, 0, 0, 1}}; int k = 4; vector<int> arr; // Empty set bool sol[] = {false}; int n = sizeof(graph) / sizeof(graph[0]); func(graph, arr, k, n - 1, sol); if (sol[0]) cout << "Yes" << endl; else cout << "No" << endl; return 0;} // This code is contributed by// sanjeev2552 // Java code to check if a// given graph contains an// independent set of size kimport java.util.*;class GFG{ static Vector<Integer> arr = new Vector<>(); // Function to cona set of// given size kstatic boolean func(int graph[][], int k, int index, boolean sol[]){ // Check if the selected set is // independent or not. Change the // value of sol to True and return // if it is independent if (k == 0) { if (check(graph, arr.size())) { sol[0] = true; return true; } } else { // Set of size k can be // formed even if we don't // include the vertex at // current index. if (index >= k) { Vector<Integer> newvec = new Vector<>(); newvec.add(index); return (func(graph, k - 1, index - 1, sol) || func(graph, k, index - 1, sol)); } // Set of size k cannot be // formed if we don't include // the vertex at current index. else { arr.add(index); return func(graph, k - 1, index - 1, sol); } } return true;} // Function to check if the// given set is independent// or not arr -. set of size// k (contains the index of// included vertex)static boolean check(int graph[][], int n){ // Check if each vertex is // connected to any other // vertex in the set or not for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (graph[arr.get(i)][arr.get(j)] == 1) return false; return true;} // Driver Codepublic static void main(String[] args){ int graph[][] = {{1, 1, 0, 0, 0}, {1, 1, 1, 1, 1}, {0, 1, 1, 0, 0}, {0, 1, 0, 1, 0}, {0, 1, 0, 0, 1}}; int k = 4; boolean []sol = new boolean[1]; int n = graph.length; func(graph, k, n - 1, sol); if (sol[0]) System.out.print("Yes" + "\n"); else System.out.print("No" + "\n");}} // This code is contributed by Amit Katiyar # Python3 code to check if a given graph# contains an independent set of size k # Function to construct a set of given size kdef func(graph, arr, k, index, sol): # Check if the selected set is independent or not. # Change the value of sol to True and return # if it is independent if k == 0: if check(graph, arr) == True: sol[0] = True return else: # Set of size k can be formed even if we don't # include the vertex at current index. if index >= k: return (func(graph, arr[:] + [index], k-1, index-1, sol) or func(graph, arr[:], k, index-1, sol)) # Set of size k cannot be formed if we don't # include the vertex at current index. else: return func(graph, arr[:] + [index], k-1, index-1, sol) # Function to check if the given set is# independent or not# arr --> set of size k (contains the# index of included vertex)def check(graph, arr): # Check if each vertex is connected to any other # vertex in the set or not for i in range(len(arr)): for j in range(i + 1, len(arr)): if graph[arr[i]][arr[j]] == 1: return False return True # Driver Code graph = [[1, 1, 0, 0, 0], [1, 1, 1, 1, 1], [0, 1, 1, 0, 0], [0, 1, 0, 1, 0], [0, 1, 0, 0, 1]] k = 4arr = [] # Empty setsol = [False] func(graph, arr[:], k, len(graph)-1, sol) if sol[0] == True: print("Yes")else: print("No") // C# code to check if a// given graph contains an// independent set of size kusing System;using System.Collections.Generic; class GFG{ static List<int> arr = new List<int>(); // Function to cona set of// given size kstatic bool func(int [,]graph, int k, int index, bool []sol){ // Check if the selected set is // independent or not. Change the // value of sol to True and return // if it is independent if (k == 0) { if (check(graph, arr.Count)) { sol[0] = true; return true; } } else { // Set of size k can be // formed even if we don't // include the vertex at // current index. if (index >= k) { List<int> newvec = new List<int>(); newvec.Add(index); return (func(graph, k - 1, index - 1, sol) || func(graph, k, index - 1, sol)); } // Set of size k cannot be // formed if we don't include // the vertex at current index. else { arr.Add(index); return func(graph, k - 1, index - 1, sol); } } return true;} // Function to check if the// given set is independent// or not arr -. set of size// k (contains the index of// included vertex)static bool check(int [,]graph, int n){ // Check if each vertex is // connected to any other // vertex in the set or not for(int i = 0; i < n; i++) for(int j = i + 1; j < n; j++) if (graph[arr[i],arr[j]] == 1) return false; return true;} // Driver Codepublic static void Main(String[] args){ int [,]graph = { { 1, 1, 0, 0, 0 }, { 1, 1, 1, 1, 1 }, { 0, 1, 1, 0, 0 }, { 0, 1, 0, 1, 0 }, { 0, 1, 0, 0, 1 } }; int k = 4; bool []sol = new bool[1]; int n = graph.GetLength(0); func(graph, k, n - 1, sol); if (sol[0]) Console.Write("Yes" + "\n"); else Console.Write("No" + "\n");}} // This code is contributed by Amit Katiyar <script> // JavaScript implementation of the above approach // Function to construct a set of given size kfunction func(graph, arr,k, index, sol){ // Check if the selected set is independent or not. // Change the value of sol to True and return // if it is independent if (k == 0) { if (check(graph, arr, arr.length)) { sol[0] = true; return true; } } else { // Set of size k can be formed even if we don't // include the vertex at current index. if (index >= k) { let newvec = new Array(); for(let x of arr){ newvec.push(x); } newvec.push(index); return (func(graph, newvec, k - 1,index - 1, sol) || func(graph, arr, k, index - 1, sol)); } // Set of size k cannot be formed if we don't // include the vertex at current index. else { arr.push(index); return func(graph, arr, k - 1,index - 1, sol); } }} // Function to check if the given set is// independent or not// arr --> set of size k (contains the// index of included vertex)function check(graph,arr,n){ // Check if each vertex is connected to any other // vertex in the set or not for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) if (graph[arr[i]][arr[j]] == 1) return false; return true;} // Driver Codelet graph = [[1, 1, 0, 0, 0], [1, 1, 1, 1, 1], [0, 1, 1, 0, 0], [0, 1, 0, 1, 0], [0, 1, 0, 0, 1]];let k = 4;let arr = []; // Empty setlet sol = [false];let n = graph.length;func(graph, arr, k, n - 1, sol); if (sol[0]) document.write("Yes");else document.write("No"); // This code is written by Shinjanpatra </script> Yes Time Complexity: where V is the number of vertices in the graph and k is the given size of set. Auxiliary Space: O(V) sanjeev2552 amit143katiyar pankajsharmagfg shinjanpatra Picked Technical Scripter 2018 Algorithms Graph Technical Scripter Graph Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar How to write a Pseudo Code? Understanding Time Complexity with Simple Examples Introduction to Algorithms Breadth First Search or BFS for a Graph Depth First Search or DFS for a Graph Graph and its representations Topological Sorting Bellman–Ford Algorithm | DP-23
[ { "code": null, "e": 26597, "s": 26569, "text": "\n07 Apr, 2022" }, { "code": null, "e": 26755, "s": 26597, "text": "Given an undirected graph, check if it contains an independent set of size k. Print ‘Yes’ if there exists an independent set of size k. Print ‘No’ otherwise." }, { "code": null, "e": 26870, "s": 26755, "text": "Independent Set: An independent set in a graph is a set of vertices that are not directly connected to each other." }, { "code": null, "e": 26882, "s": 26870, "text": "Example 1: " }, { "code": null, "e": 27081, "s": 26882, "text": "Input : K = 4,\n graph = [[1, 1, 0, 0, 0],\n [1, 1, 1, 1, 1],\n [0, 1, 1, 0, 0],\n [0, 1, 0, 1, 0],\n [0, 1, 0, 0, 1]]\nOutput : Yes " }, { "code": null, "e": 27227, "s": 27081, "text": "The above graph contains an independent set of size 4 (vertices 1, 2, 3, 4 are not directly connected to each other). Hence, the output is ‘Yes’." }, { "code": null, "e": 27239, "s": 27227, "text": "Example 2: " }, { "code": null, "e": 27436, "s": 27239, "text": "Input : K = 4,\n graph = [[1, 1, 0, 0, 0],\n [1, 1, 1, 1, 1],\n [0, 1, 1, 0, 0],\n [0, 1, 0, 1, 1],\n [0, 1, 0, 1, 1]]\nOutput : No" }, { "code": null, "e": 27526, "s": 27436, "text": "The above graph doesn’t contain an independent set of size 4. Hence, the output is ‘No’. " }, { "code": null, "e": 27538, "s": 27526, "text": "Approach: " }, { "code": null, "e": 27590, "s": 27538, "text": "Initialize a variable sol with boolean False value." }, { "code": null, "e": 27661, "s": 27590, "text": "Find all the possible sets of vertices of size K from the given graph." }, { "code": null, "e": 27747, "s": 27661, "text": "If an independent set of size k is found, change the value of sol to True and return." }, { "code": null, "e": 27795, "s": 27747, "text": "Else continue checking for other possible sets." }, { "code": null, "e": 27852, "s": 27795, "text": "In the end, if sol is True, print ‘Yes’ else print ‘No’." }, { "code": null, "e": 27904, "s": 27852, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27910, "s": 27904, "text": "C++14" }, { "code": null, "e": 27915, "s": 27910, "text": "Java" }, { "code": null, "e": 27923, "s": 27915, "text": "Python3" }, { "code": null, "e": 27926, "s": 27923, "text": "C#" }, { "code": null, "e": 27937, "s": 27926, "text": "Javascript" }, { "code": "// C++ code to check if a given graph// contains an independent set of size k#include <bits/stdc++.h>using namespace std; // Function prototypebool check(int[][5], vector<int> &, int); // Function to construct a set of given size kbool func(int graph[][5], vector<int> &arr, int k, int index, bool sol[]){ // Check if the selected set is independent or not. // Change the value of sol to True and return // if it is independent if (k == 0) { if (check(graph, arr, arr.size())) { sol[0] = true; return true; } } else { // Set of size k can be formed even if we don't // include the vertex at current index. if (index >= k) { vector<int> newvec(arr.begin(), arr.end()); newvec.push_back(index); return (func(graph, newvec, k - 1, index - 1, sol) or func(graph, arr, k, index - 1, sol)); } // Set of size k cannot be formed if we don't // include the vertex at current index. else { arr.push_back(index); return func(graph, arr, k - 1, index - 1, sol); } }} // Function to check if the given set is// independent or not// arr --> set of size k (contains the// index of included vertex)bool check(int graph[][5], vector<int> &arr, int n){ // Check if each vertex is connected to any other // vertex in the set or not for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (graph[arr[i]][arr[j]] == 1) return false; return true;} // Driver Codeint main(){ int graph[][5] = {{1, 1, 0, 0, 0}, {1, 1, 1, 1, 1}, {0, 1, 1, 0, 0}, {0, 1, 0, 1, 0}, {0, 1, 0, 0, 1}}; int k = 4; vector<int> arr; // Empty set bool sol[] = {false}; int n = sizeof(graph) / sizeof(graph[0]); func(graph, arr, k, n - 1, sol); if (sol[0]) cout << \"Yes\" << endl; else cout << \"No\" << endl; return 0;} // This code is contributed by// sanjeev2552", "e": 30118, "s": 27937, "text": null }, { "code": "// Java code to check if a// given graph contains an// independent set of size kimport java.util.*;class GFG{ static Vector<Integer> arr = new Vector<>(); // Function to cona set of// given size kstatic boolean func(int graph[][], int k, int index, boolean sol[]){ // Check if the selected set is // independent or not. Change the // value of sol to True and return // if it is independent if (k == 0) { if (check(graph, arr.size())) { sol[0] = true; return true; } } else { // Set of size k can be // formed even if we don't // include the vertex at // current index. if (index >= k) { Vector<Integer> newvec = new Vector<>(); newvec.add(index); return (func(graph, k - 1, index - 1, sol) || func(graph, k, index - 1, sol)); } // Set of size k cannot be // formed if we don't include // the vertex at current index. else { arr.add(index); return func(graph, k - 1, index - 1, sol); } } return true;} // Function to check if the// given set is independent// or not arr -. set of size// k (contains the index of// included vertex)static boolean check(int graph[][], int n){ // Check if each vertex is // connected to any other // vertex in the set or not for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (graph[arr.get(i)][arr.get(j)] == 1) return false; return true;} // Driver Codepublic static void main(String[] args){ int graph[][] = {{1, 1, 0, 0, 0}, {1, 1, 1, 1, 1}, {0, 1, 1, 0, 0}, {0, 1, 0, 1, 0}, {0, 1, 0, 0, 1}}; int k = 4; boolean []sol = new boolean[1]; int n = graph.length; func(graph, k, n - 1, sol); if (sol[0]) System.out.print(\"Yes\" + \"\\n\"); else System.out.print(\"No\" + \"\\n\");}} // This code is contributed by Amit Katiyar", "e": 32134, "s": 30118, "text": null }, { "code": "# Python3 code to check if a given graph# contains an independent set of size k # Function to construct a set of given size kdef func(graph, arr, k, index, sol): # Check if the selected set is independent or not. # Change the value of sol to True and return # if it is independent if k == 0: if check(graph, arr) == True: sol[0] = True return else: # Set of size k can be formed even if we don't # include the vertex at current index. if index >= k: return (func(graph, arr[:] + [index], k-1, index-1, sol) or func(graph, arr[:], k, index-1, sol)) # Set of size k cannot be formed if we don't # include the vertex at current index. else: return func(graph, arr[:] + [index], k-1, index-1, sol) # Function to check if the given set is# independent or not# arr --> set of size k (contains the# index of included vertex)def check(graph, arr): # Check if each vertex is connected to any other # vertex in the set or not for i in range(len(arr)): for j in range(i + 1, len(arr)): if graph[arr[i]][arr[j]] == 1: return False return True # Driver Code graph = [[1, 1, 0, 0, 0], [1, 1, 1, 1, 1], [0, 1, 1, 0, 0], [0, 1, 0, 1, 0], [0, 1, 0, 0, 1]] k = 4arr = [] # Empty setsol = [False] func(graph, arr[:], k, len(graph)-1, sol) if sol[0] == True: print(\"Yes\")else: print(\"No\")", "e": 33685, "s": 32134, "text": null }, { "code": "// C# code to check if a// given graph contains an// independent set of size kusing System;using System.Collections.Generic; class GFG{ static List<int> arr = new List<int>(); // Function to cona set of// given size kstatic bool func(int [,]graph, int k, int index, bool []sol){ // Check if the selected set is // independent or not. Change the // value of sol to True and return // if it is independent if (k == 0) { if (check(graph, arr.Count)) { sol[0] = true; return true; } } else { // Set of size k can be // formed even if we don't // include the vertex at // current index. if (index >= k) { List<int> newvec = new List<int>(); newvec.Add(index); return (func(graph, k - 1, index - 1, sol) || func(graph, k, index - 1, sol)); } // Set of size k cannot be // formed if we don't include // the vertex at current index. else { arr.Add(index); return func(graph, k - 1, index - 1, sol); } } return true;} // Function to check if the// given set is independent// or not arr -. set of size// k (contains the index of// included vertex)static bool check(int [,]graph, int n){ // Check if each vertex is // connected to any other // vertex in the set or not for(int i = 0; i < n; i++) for(int j = i + 1; j < n; j++) if (graph[arr[i],arr[j]] == 1) return false; return true;} // Driver Codepublic static void Main(String[] args){ int [,]graph = { { 1, 1, 0, 0, 0 }, { 1, 1, 1, 1, 1 }, { 0, 1, 1, 0, 0 }, { 0, 1, 0, 1, 0 }, { 0, 1, 0, 0, 1 } }; int k = 4; bool []sol = new bool[1]; int n = graph.GetLength(0); func(graph, k, n - 1, sol); if (sol[0]) Console.Write(\"Yes\" + \"\\n\"); else Console.Write(\"No\" + \"\\n\");}} // This code is contributed by Amit Katiyar", "e": 35695, "s": 33685, "text": null }, { "code": "<script> // JavaScript implementation of the above approach // Function to construct a set of given size kfunction func(graph, arr,k, index, sol){ // Check if the selected set is independent or not. // Change the value of sol to True and return // if it is independent if (k == 0) { if (check(graph, arr, arr.length)) { sol[0] = true; return true; } } else { // Set of size k can be formed even if we don't // include the vertex at current index. if (index >= k) { let newvec = new Array(); for(let x of arr){ newvec.push(x); } newvec.push(index); return (func(graph, newvec, k - 1,index - 1, sol) || func(graph, arr, k, index - 1, sol)); } // Set of size k cannot be formed if we don't // include the vertex at current index. else { arr.push(index); return func(graph, arr, k - 1,index - 1, sol); } }} // Function to check if the given set is// independent or not// arr --> set of size k (contains the// index of included vertex)function check(graph,arr,n){ // Check if each vertex is connected to any other // vertex in the set or not for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) if (graph[arr[i]][arr[j]] == 1) return false; return true;} // Driver Codelet graph = [[1, 1, 0, 0, 0], [1, 1, 1, 1, 1], [0, 1, 1, 0, 0], [0, 1, 0, 1, 0], [0, 1, 0, 0, 1]];let k = 4;let arr = []; // Empty setlet sol = [false];let n = graph.length;func(graph, arr, k, n - 1, sol); if (sol[0]) document.write(\"Yes\");else document.write(\"No\"); // This code is written by Shinjanpatra </script>", "e": 37545, "s": 35695, "text": null }, { "code": null, "e": 37549, "s": 37545, "text": "Yes" }, { "code": null, "e": 37671, "s": 37551, "text": "Time Complexity: where V is the number of vertices in the graph and k is the given size of set. Auxiliary Space: O(V) " }, { "code": null, "e": 37683, "s": 37671, "text": "sanjeev2552" }, { "code": null, "e": 37698, "s": 37683, "text": "amit143katiyar" }, { "code": null, "e": 37714, "s": 37698, "text": "pankajsharmagfg" }, { "code": null, "e": 37727, "s": 37714, "text": "shinjanpatra" }, { "code": null, "e": 37734, "s": 37727, "text": "Picked" }, { "code": null, "e": 37758, "s": 37734, "text": "Technical Scripter 2018" }, { "code": null, "e": 37769, "s": 37758, "text": "Algorithms" }, { "code": null, "e": 37775, "s": 37769, "text": "Graph" }, { "code": null, "e": 37794, "s": 37775, "text": "Technical Scripter" }, { "code": null, "e": 37800, "s": 37794, "text": "Graph" }, { "code": null, "e": 37811, "s": 37800, "text": "Algorithms" }, { "code": null, "e": 37909, "s": 37811, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37958, "s": 37909, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 37983, "s": 37958, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 38011, "s": 37983, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 38062, "s": 38011, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 38089, "s": 38062, "text": "Introduction to Algorithms" }, { "code": null, "e": 38129, "s": 38089, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 38167, "s": 38129, "text": "Depth First Search or DFS for a Graph" }, { "code": null, "e": 38197, "s": 38167, "text": "Graph and its representations" }, { "code": null, "e": 38217, "s": 38197, "text": "Topological Sorting" } ]
Understanding ReDoS Attack - GeeksforGeeks
12 Jan, 2022 ReDoS stands for Regular Expression Denial of Service. The ReDoS is an algorithmic complexity attack that produces a denial of service by providing a regular expression that takes a very long time to evaluate. The attack exploits the fact that most regular expression implementations have exponential time worst case complexity, so for larger input strings(the ‘evil regex’) the time taken by a regex engine to find a match increases exponentially. The aim of the attacker is to provide such regex(s) so that it takes indefinite amount of computation time which in turn will either slow down the application or completely bring it down. So this attack basically takes advantage of the fact that the regex engine will try out every possible permutation and combination of characters to find a match. Regular expressions can be found all over the web and a ReDoS attack can be used to target various components of the web. Sample Expression of ReDOS attacks Regex: ^((ab)*)+$ (this regex searches for ab and its repetition) Input: ababab In this case the regex engine will find a match in the first try since ababab matches the regex pattern. Now we can complicate things very easily by throwing in abababa as the input. This extra a in the end will cause all kinds of trouble since it does not match the pattern and it will make the regex engine run all kinds of permutation looking for a possible match. (ababab) - NOT A MATCH (abab)(ab) - NOT A MATCH (ab)(abab) - NOT A MATCH (ab)(ab)(ab) - NOT A MATCH ()(ababab) - NOT A MATCH ()(abab)(ab) - NOT A MATCH ()(ab)(abab) - NOT A MATCH ()(ab)(ab)(ab) - NOT A MATCH You can try it out yourself in this online regex editor. Now imagine if that input was longer something like abababababababababababababababababababababababababab...... what kind of havoc it will create. Evil Regex They are the regular expressions that make an application vulnerable to ReDoS attacks, they occur whenever these factors occur: the regular expression applies repetition (“+”, “*”) to a complex subexpression for the repeated subexpression, there exists a match which is also a suffix of another valid match. Examples of malicious regexes include the following: (a+)+ ([a-zA-Z]+)* (a|aa)+ (a|a?)+ (.*a){x} for x > 10 Web application attack via Evil Regex: Open a JavaScript and find the Evil Regex Craft a malicious input for the found Regex and submit a valid value via intercepting proxy Change the request to contain a malicious input and you are ready with a ReDos attack ReDoS via Regex Injection The following example checks if the username is part of the password entered by the user. String userName = textBox1.Text; String password = textBox2.Text; Regex testPassword = new Regex(userName); Match match = testPassword.Match(password); if (match.Success) { MessageBox.Show("Do not include name in password."); } else { MessageBox.Show("Good password."); } If an attacker enters ^(([a-z])+.)+[A-Z]([a-z])+$ as a username and aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa! as a password, the program will hang. Prevention: Use atomic grouping in your regex. An atomic group is a group that, when the regex engine exits from it, automatically throws away all backtracking positions remembered by any tokens inside the groupIf a regular expression takes too long, kill it at once, and inform the user that the regular expression was taking too long.Preformat/validate your regular expressions or let people search for text directly, rather than input a regular expression directly. Use atomic grouping in your regex. An atomic group is a group that, when the regex engine exits from it, automatically throws away all backtracking positions remembered by any tokens inside the group If a regular expression takes too long, kill it at once, and inform the user that the regular expression was taking too long. Preformat/validate your regular expressions or let people search for text directly, rather than input a regular expression directly. References: https://www.linkedin.com/pulse/redos-attacks-python-application-architectures-akshat-mahajan http://stackoverflow.com/questions/12841970/how-can-i-recognize-an-evil-regex https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS Image Source: https://www.owasp.org/index.php/Main_Page This article is contributed by Palash Nigam . 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. sumitgumber28 secure-coding Advanced Computer Subject GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Reinforcement learning Decision Tree System Design Tutorial Decision Tree Introduction with example Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... DSA Sheet by Love Babbar Socket Programming in C/C++ GET and POST requests using Python Must Do Coding Questions for Product Based Companies
[ { "code": null, "e": 25653, "s": 25625, "text": "\n12 Jan, 2022" }, { "code": null, "e": 26104, "s": 25653, "text": "ReDoS stands for Regular Expression Denial of Service. The ReDoS is an algorithmic complexity attack that produces a denial of service by providing a regular expression that takes a very long time to evaluate. The attack exploits the fact that most regular expression implementations have exponential time worst case complexity, so for larger input strings(the ‘evil regex’) the time taken by a regex engine to find a match increases exponentially. " }, { "code": null, "e": 26455, "s": 26104, "text": "The aim of the attacker is to provide such regex(s) so that it takes indefinite amount of computation time which in turn will either slow down the application or completely bring it down. So this attack basically takes advantage of the fact that the regex engine will try out every possible permutation and combination of characters to find a match. " }, { "code": null, "e": 26578, "s": 26455, "text": "Regular expressions can be found all over the web and a ReDoS attack can be used to target various components of the web. " }, { "code": null, "e": 26615, "s": 26580, "text": "Sample Expression of ReDOS attacks" }, { "code": null, "e": 27065, "s": 26615, "text": "Regex: ^((ab)*)+$ (this regex searches for ab and its repetition) Input: ababab In this case the regex engine will find a match in the first try since ababab matches the regex pattern. Now we can complicate things very easily by throwing in abababa as the input. This extra a in the end will cause all kinds of trouble since it does not match the pattern and it will make the regex engine run all kinds of permutation looking for a possible match. " }, { "code": null, "e": 27273, "s": 27065, "text": "(ababab) - NOT A MATCH\n(abab)(ab) - NOT A MATCH\n(ab)(abab) - NOT A MATCH\n(ab)(ab)(ab) - NOT A MATCH\n()(ababab) - NOT A MATCH\n()(abab)(ab) - NOT A MATCH\n()(ab)(abab) - NOT A MATCH\n()(ab)(ab)(ab) - NOT A MATCH" }, { "code": null, "e": 27384, "s": 27273, "text": "You can try it out yourself in this online regex editor. Now imagine if that input was longer something like " }, { "code": null, "e": 27443, "s": 27384, "text": "abababababababababababababababababababababababababab......" }, { "code": null, "e": 27480, "s": 27443, "text": "what kind of havoc it will create. " }, { "code": null, "e": 27491, "s": 27480, "text": "Evil Regex" }, { "code": null, "e": 27621, "s": 27491, "text": "They are the regular expressions that make an application vulnerable to ReDoS attacks, they occur whenever these factors occur: " }, { "code": null, "e": 27701, "s": 27621, "text": "the regular expression applies repetition (“+”, “*”) to a complex subexpression" }, { "code": null, "e": 27801, "s": 27701, "text": "for the repeated subexpression, there exists a match which is also a suffix of another valid match." }, { "code": null, "e": 27856, "s": 27801, "text": "Examples of malicious regexes include the following: " }, { "code": null, "e": 27862, "s": 27856, "text": "(a+)+" }, { "code": null, "e": 27875, "s": 27862, "text": "([a-zA-Z]+)*" }, { "code": null, "e": 27883, "s": 27875, "text": "(a|aa)+" }, { "code": null, "e": 27891, "s": 27883, "text": "(a|a?)+" }, { "code": null, "e": 27911, "s": 27891, "text": "(.*a){x} for x > 10" }, { "code": null, "e": 27952, "s": 27911, "text": "Web application attack via Evil Regex: " }, { "code": null, "e": 27994, "s": 27952, "text": "Open a JavaScript and find the Evil Regex" }, { "code": null, "e": 28086, "s": 27994, "text": "Craft a malicious input for the found Regex and submit a valid value via intercepting proxy" }, { "code": null, "e": 28172, "s": 28086, "text": "Change the request to contain a malicious input and you are ready with a ReDos attack" }, { "code": null, "e": 28200, "s": 28174, "text": "ReDoS via Regex Injection" }, { "code": null, "e": 28292, "s": 28200, "text": "The following example checks if the username is part of the password entered by the user. " }, { "code": null, "e": 28564, "s": 28292, "text": "String userName = textBox1.Text;\nString password = textBox2.Text;\nRegex testPassword = new Regex(userName);\nMatch match = testPassword.Match(password);\nif (match.Success)\n{\nMessageBox.Show(\"Do not include name in password.\");\n}\nelse\n{\nMessageBox.Show(\"Good password.\");\n}" }, { "code": null, "e": 28706, "s": 28564, "text": "If an attacker enters ^(([a-z])+.)+[A-Z]([a-z])+$ as a username and aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa! as a password, the program will hang. " }, { "code": null, "e": 28720, "s": 28706, "text": "Prevention: " }, { "code": null, "e": 29177, "s": 28720, "text": "Use atomic grouping in your regex. An atomic group is a group that, when the regex engine exits from it, automatically throws away all backtracking positions remembered by any tokens inside the groupIf a regular expression takes too long, kill it at once, and inform the user that the regular expression was taking too long.Preformat/validate your regular expressions or let people search for text directly, rather than input a regular expression directly." }, { "code": null, "e": 29377, "s": 29177, "text": "Use atomic grouping in your regex. An atomic group is a group that, when the regex engine exits from it, automatically throws away all backtracking positions remembered by any tokens inside the group" }, { "code": null, "e": 29503, "s": 29377, "text": "If a regular expression takes too long, kill it at once, and inform the user that the regular expression was taking too long." }, { "code": null, "e": 29636, "s": 29503, "text": "Preformat/validate your regular expressions or let people search for text directly, rather than input a regular expression directly." }, { "code": null, "e": 29650, "s": 29636, "text": "References: " }, { "code": null, "e": 29743, "s": 29650, "text": "https://www.linkedin.com/pulse/redos-attacks-python-application-architectures-akshat-mahajan" }, { "code": null, "e": 29821, "s": 29743, "text": "http://stackoverflow.com/questions/12841970/how-can-i-recognize-an-evil-regex" }, { "code": null, "e": 29898, "s": 29821, "text": "https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS" }, { "code": null, "e": 29954, "s": 29898, "text": "Image Source: https://www.owasp.org/index.php/Main_Page" }, { "code": null, "e": 30252, "s": 29954, "text": "This article is contributed by Palash Nigam . 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": 30378, "s": 30252, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 30392, "s": 30378, "text": "sumitgumber28" }, { "code": null, "e": 30406, "s": 30392, "text": "secure-coding" }, { "code": null, "e": 30432, "s": 30406, "text": "Advanced Computer Subject" }, { "code": null, "e": 30438, "s": 30432, "text": "GBlog" }, { "code": null, "e": 30536, "s": 30438, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30559, "s": 30536, "text": "ML | Linear Regression" }, { "code": null, "e": 30582, "s": 30559, "text": "Reinforcement learning" }, { "code": null, "e": 30596, "s": 30582, "text": "Decision Tree" }, { "code": null, "e": 30619, "s": 30596, "text": "System Design Tutorial" }, { "code": null, "e": 30659, "s": 30619, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 30733, "s": 30659, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 30758, "s": 30733, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 30786, "s": 30758, "text": "Socket Programming in C/C++" }, { "code": null, "e": 30821, "s": 30786, "text": "GET and POST requests using Python" } ]
Program to calculate area and volume of a Tetrahedron - GeeksforGeeks
01 May, 2021 A Tetrahedron is simply a pyramid with a triangular base. It is a solid object with four triangular faces, three on the sides or lateral faces, one on the bottom or the base and four vertices or corners. If the faces are all congruent equilateral triangles, then the tetrahedron is called regular. The area of Tetrahedron can be found by using the formula : Area = sqrt(3)*(side*side) Examples : Input : side = 3 Output : 15.5885 Input : side = 20 Output : 692.82 C++ Java Python3 C# PHP Javascript // C++ Program to Calculate// area of tetrahedron#include<iostream>#include<math.h>using namespace std; //Utility Functiondouble area_of_tetrahedron(int side){ return (sqrt(3)*(side*side));} //Driver Codeint main(){ int side=3; cout<< "Area of Tetrahedron =" << area_of_tetrahedron(side);} // This code is contributed by anant321. // Java Program to Calculate// area of tetrahedronimport java.util.*;import java.lang.*; class GFG { // Utility Function public static double area_of_tetrahedron(int side) { return (Math.sqrt(3) * (side * side)); } // Driver code public static void main(String[] args) { int side = 3; System.out.println("Area of Tetrahedron =" + area_of_tetrahedron(side)); }}// This code is contributed// by Prasad Kshirsagar # Python3 Program to# Calculate area of# tetrahedronimport math def area_of_tetrahedron(side): return (math.sqrt(3) * (side * side)); # Driver Codeside = 3;print("Area of Tetrahedron = ", round(area_of_tetrahedron(side), 4)); # This code is contributed by mits // C# Program to Calculate// area of tetrahedronusing System; class GFG{// Utility Functionpublic static double area_of_tetrahedron(int side){ return (Math.Sqrt(3) * (side * side)); } // Driver codestatic public void Main (){ int side = 3; Console.WriteLine("Area of Tetrahedron = " + area_of_tetrahedron(side));}} // This code is contributed// by akt_mit <?php// PHP Program to Calculate// area of tetrahedron function area_of_tetrahedron($side){ return (sqrt(3) * ($side * $side));} // Driver Code $side = 3; echo "Area of Tetrahedron = ", area_of_tetrahedron($side); // This code is contributed by aj_36.?> <script>// javascript Program to Calculate// area of tetrahedron // Utility Functionfunction area_of_tetrahedron( side){ return (Math.sqrt(3) * (side * side));} // Driver Codelet side = 3;document.write("Area of Tetrahedron ="+ area_of_tetrahedron(side).toFixed(4)); // This code contributed by aashish1995 </script Output : Area of Tetrahedron =15.5885 The volume of the tetrahedron can be found by using the following formula : Volume = a3/(6√2) Examples : Input : side = 3 Output : 3.18 Input : side = 20 Output : 942.81 C++ Java Python3 C# PHP Javascript // C++ code to find the volume of a tetrahedron#include <bits/stdc++.h>using namespace std; // Function to calculate volumedouble vol_tetra(int side){ double volume = (pow(side, 3) / (6 * sqrt(2))); return volume;} // Driver codeint main(){ int side = 3; double vol = vol_tetra(side); vol = (double)round(vol * 100) / 100; cout << vol; return 0;} // This code is contributed by suresh07 // Java code to find the volume of a tetrahedronimport java.io.*; class Tetrahedron { // Function to calculate volume static double vol_tetra(int side) { double volume = (Math.pow(side, 3) / (6 * Math.sqrt(2))); return volume; } // Driver Code public static void main(String[] args) { int side = 3; double vol = vol_tetra(side); vol = (double)Math.round(vol * 100) / 100; System.out.println(vol); }} # Python code to find the volume of a tetrahedronimport mathdef vol_tetra(side): volume = (side ** 3 / (6 * math.sqrt(2))) return round(volume, 2) # Driver Codeside = 3vol = vol_tetra(side)print(vol) // C# code to find the volume of a tetrahedronusing System; class Tetrahedron { // Function to calculate volume static double vol_tetra(int side) { double volume = (Math.Pow(side, 3) / (6 * Math.Sqrt(2))); return volume; } // Driver Code public static void Main() { int side = 3; double vol = vol_tetra(side); vol = (double)Math.Round(vol * 100) / 100; Console.WriteLine(vol); }} // This code is contributed// by vt_m. <?php// PHP program to find the// volume of a tetrahedron // Function to calculate volumefunction vol_tetra($side){ $volume = (pow($side, 3) / (6 * sqrt(2))); return $volume;} // Driver Code$side = 3;$vol = vol_tetra($side);echo $vol; // This code is contributed by ajit?> <script>// javascript code to find the volume of a tetrahedron function vol_tetra(side){ let volume = (Math.pow(side, 3) / (6 * Math.sqrt(2))); return volume;} // Driver Codelet side = 3;let vol = vol_tetra(side);vol = Math.round(vol * 100) / 100;document.write(vol); // This code is contributed by gauravrajput1 </script> Output : 3.18 jit_t Prasad_Kshirsagar Mithun Kumar aashish1995 GauravRajput1 suresh07 area-volume-programs Geometric Mathematical School Programming Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Optimum location of point to minimize total distance Given n line segments, find if any two segments intersect Convex Hull using Divide and Conquer Algorithm Polygon Clipping | Sutherland–Hodgman Algorithm Program for Point of Intersection of Two Lines Program for Fibonacci numbers Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) C++ Data Types Coin Change | DP-7
[ { "code": null, "e": 26734, "s": 26706, "text": "\n01 May, 2021" }, { "code": null, "e": 27033, "s": 26734, "text": "A Tetrahedron is simply a pyramid with a triangular base. It is a solid object with four triangular faces, three on the sides or lateral faces, one on the bottom or the base and four vertices or corners. If the faces are all congruent equilateral triangles, then the tetrahedron is called regular. " }, { "code": null, "e": 27094, "s": 27033, "text": "The area of Tetrahedron can be found by using the formula : " }, { "code": null, "e": 27121, "s": 27094, "text": "Area = sqrt(3)*(side*side)" }, { "code": null, "e": 27134, "s": 27121, "text": "Examples : " }, { "code": null, "e": 27203, "s": 27134, "text": "Input : side = 3\nOutput : 15.5885\n\nInput : side = 20\nOutput : 692.82" }, { "code": null, "e": 27207, "s": 27203, "text": "C++" }, { "code": null, "e": 27212, "s": 27207, "text": "Java" }, { "code": null, "e": 27220, "s": 27212, "text": "Python3" }, { "code": null, "e": 27223, "s": 27220, "text": "C#" }, { "code": null, "e": 27227, "s": 27223, "text": "PHP" }, { "code": null, "e": 27238, "s": 27227, "text": "Javascript" }, { "code": "// C++ Program to Calculate// area of tetrahedron#include<iostream>#include<math.h>using namespace std; //Utility Functiondouble area_of_tetrahedron(int side){ return (sqrt(3)*(side*side));} //Driver Codeint main(){ int side=3; cout<< \"Area of Tetrahedron =\" << area_of_tetrahedron(side);} // This code is contributed by anant321.", "e": 27586, "s": 27238, "text": null }, { "code": "// Java Program to Calculate// area of tetrahedronimport java.util.*;import java.lang.*; class GFG { // Utility Function public static double area_of_tetrahedron(int side) { return (Math.sqrt(3) * (side * side)); } // Driver code public static void main(String[] args) { int side = 3; System.out.println(\"Area of Tetrahedron =\" + area_of_tetrahedron(side)); }}// This code is contributed// by Prasad Kshirsagar", "e": 28065, "s": 27586, "text": null }, { "code": "# Python3 Program to# Calculate area of# tetrahedronimport math def area_of_tetrahedron(side): return (math.sqrt(3) * (side * side)); # Driver Codeside = 3;print(\"Area of Tetrahedron = \", round(area_of_tetrahedron(side), 4)); # This code is contributed by mits", "e": 28345, "s": 28065, "text": null }, { "code": "// C# Program to Calculate// area of tetrahedronusing System; class GFG{// Utility Functionpublic static double area_of_tetrahedron(int side){ return (Math.Sqrt(3) * (side * side)); } // Driver codestatic public void Main (){ int side = 3; Console.WriteLine(\"Area of Tetrahedron = \" + area_of_tetrahedron(side));}} // This code is contributed// by akt_mit", "e": 28740, "s": 28345, "text": null }, { "code": "<?php// PHP Program to Calculate// area of tetrahedron function area_of_tetrahedron($side){ return (sqrt(3) * ($side * $side));} // Driver Code $side = 3; echo \"Area of Tetrahedron = \", area_of_tetrahedron($side); // This code is contributed by aj_36.?>", "e": 29016, "s": 28740, "text": null }, { "code": "<script>// javascript Program to Calculate// area of tetrahedron // Utility Functionfunction area_of_tetrahedron( side){ return (Math.sqrt(3) * (side * side));} // Driver Codelet side = 3;document.write(\"Area of Tetrahedron =\"+ area_of_tetrahedron(side).toFixed(4)); // This code contributed by aashish1995 </script", "e": 29337, "s": 29016, "text": null }, { "code": null, "e": 29347, "s": 29337, "text": "Output : " }, { "code": null, "e": 29376, "s": 29347, "text": "Area of Tetrahedron =15.5885" }, { "code": null, "e": 29453, "s": 29376, "text": "The volume of the tetrahedron can be found by using the following formula : " }, { "code": null, "e": 29471, "s": 29453, "text": "Volume = a3/(6√2)" }, { "code": null, "e": 29483, "s": 29471, "text": "Examples : " }, { "code": null, "e": 29550, "s": 29483, "text": "Input : side = 3\nOutput : 3.18\n\n\nInput : side = 20\nOutput : 942.81" }, { "code": null, "e": 29554, "s": 29550, "text": "C++" }, { "code": null, "e": 29559, "s": 29554, "text": "Java" }, { "code": null, "e": 29567, "s": 29559, "text": "Python3" }, { "code": null, "e": 29570, "s": 29567, "text": "C#" }, { "code": null, "e": 29574, "s": 29570, "text": "PHP" }, { "code": null, "e": 29585, "s": 29574, "text": "Javascript" }, { "code": "// C++ code to find the volume of a tetrahedron#include <bits/stdc++.h>using namespace std; // Function to calculate volumedouble vol_tetra(int side){ double volume = (pow(side, 3) / (6 * sqrt(2))); return volume;} // Driver codeint main(){ int side = 3; double vol = vol_tetra(side); vol = (double)round(vol * 100) / 100; cout << vol; return 0;} // This code is contributed by suresh07", "e": 30013, "s": 29585, "text": null }, { "code": "// Java code to find the volume of a tetrahedronimport java.io.*; class Tetrahedron { // Function to calculate volume static double vol_tetra(int side) { double volume = (Math.pow(side, 3) / (6 * Math.sqrt(2))); return volume; } // Driver Code public static void main(String[] args) { int side = 3; double vol = vol_tetra(side); vol = (double)Math.round(vol * 100) / 100; System.out.println(vol); }}", "e": 30480, "s": 30013, "text": null }, { "code": "# Python code to find the volume of a tetrahedronimport mathdef vol_tetra(side): volume = (side ** 3 / (6 * math.sqrt(2))) return round(volume, 2) # Driver Codeside = 3vol = vol_tetra(side)print(vol)", "e": 30686, "s": 30480, "text": null }, { "code": "// C# code to find the volume of a tetrahedronusing System; class Tetrahedron { // Function to calculate volume static double vol_tetra(int side) { double volume = (Math.Pow(side, 3) / (6 * Math.Sqrt(2))); return volume; } // Driver Code public static void Main() { int side = 3; double vol = vol_tetra(side); vol = (double)Math.Round(vol * 100) / 100; Console.WriteLine(vol); }} // This code is contributed// by vt_m.", "e": 31172, "s": 30686, "text": null }, { "code": "<?php// PHP program to find the// volume of a tetrahedron // Function to calculate volumefunction vol_tetra($side){ $volume = (pow($side, 3) / (6 * sqrt(2))); return $volume;} // Driver Code$side = 3;$vol = vol_tetra($side);echo $vol; // This code is contributed by ajit?>", "e": 31472, "s": 31172, "text": null }, { "code": "<script>// javascript code to find the volume of a tetrahedron function vol_tetra(side){ let volume = (Math.pow(side, 3) / (6 * Math.sqrt(2))); return volume;} // Driver Codelet side = 3;let vol = vol_tetra(side);vol = Math.round(vol * 100) / 100;document.write(vol); // This code is contributed by gauravrajput1 </script>", "e": 31801, "s": 31472, "text": null }, { "code": null, "e": 31811, "s": 31801, "text": "Output : " }, { "code": null, "e": 31816, "s": 31811, "text": "3.18" }, { "code": null, "e": 31824, "s": 31818, "text": "jit_t" }, { "code": null, "e": 31842, "s": 31824, "text": "Prasad_Kshirsagar" }, { "code": null, "e": 31855, "s": 31842, "text": "Mithun Kumar" }, { "code": null, "e": 31867, "s": 31855, "text": "aashish1995" }, { "code": null, "e": 31881, "s": 31867, "text": "GauravRajput1" }, { "code": null, "e": 31890, "s": 31881, "text": "suresh07" }, { "code": null, "e": 31911, "s": 31890, "text": "area-volume-programs" }, { "code": null, "e": 31921, "s": 31911, "text": "Geometric" }, { "code": null, "e": 31934, "s": 31921, "text": "Mathematical" }, { "code": null, "e": 31953, "s": 31934, "text": "School Programming" }, { "code": null, "e": 31966, "s": 31953, "text": "Mathematical" }, { "code": null, "e": 31976, "s": 31966, "text": "Geometric" }, { "code": null, "e": 32074, "s": 31976, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32127, "s": 32074, "text": "Optimum location of point to minimize total distance" }, { "code": null, "e": 32185, "s": 32127, "text": "Given n line segments, find if any two segments intersect" }, { "code": null, "e": 32232, "s": 32185, "text": "Convex Hull using Divide and Conquer Algorithm" }, { "code": null, "e": 32280, "s": 32232, "text": "Polygon Clipping | Sutherland–Hodgman Algorithm" }, { "code": null, "e": 32327, "s": 32280, "text": "Program for Point of Intersection of Two Lines" }, { "code": null, "e": 32357, "s": 32327, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 32417, "s": 32357, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 32460, "s": 32417, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 32475, "s": 32460, "text": "C++ Data Types" } ]
numpy.absolute() in Python - GeeksforGeeks
29 Nov, 2018 numpy.absolute(arr, out = None, ufunc ‘absolute’) : This mathematical function helps user to calculate absolute value of each element. For complex input, a + ib, the absolute value is . Parameters : arr : [array_like] Input array or object whose elements, we need to test. Return : An array with absolute value of each array. Code #1 : Working # Python program explaining# absolute () function import numpy as np arr1 = [1, -3, 15, -466]print ("Absolute Value of arr1 : \n", np.absolute(arr1)) arr2 = [23 , -56]print ("\nAbsolute Value of arr2 : \n", np.absolute(arr2)) Output : Absolute Value of arr1 : [ 1 3 15 466] Absolute Value of arr2 : [23 56] Code #2 : Working with complex numbers # Python program explaining# absolute () function import numpy as np a = 4 + 3jprint("Absolute(4 + 3j) : ", np.absolute(a)) b = 16 + 13jprint("\nAbsolute value(16 + 13j) : ", np.absolute(b)) Output : Absolute(4 + 3j) : 5.0 Absolute value(16 + 13j) : 20.6155281281 Code #3: Graphical Representation of numpy.absolute() # Python program explaining# absolute () function import numpy as npimport matplotlib.pyplot as plt a = np.linspace(start = -5, stop = 5, num = 6, endpoint = True) print("Graphical Representation : \n", np.absolute(a)) plt.title("blue : with absolute\nred : without absolute")plt.plot(a, np.absolute(a)) plt.plot(a, a, color = 'red')plt.show() Output : Graphical Representation : [ 5. 3. 1. 1. 3. 5.] References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.absolute.html. Python numpy-Mathematical Function Python-numpy 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 How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25295, "s": 25267, "text": "\n29 Nov, 2018" }, { "code": null, "e": 25481, "s": 25295, "text": "numpy.absolute(arr, out = None, ufunc ‘absolute’) : This mathematical function helps user to calculate absolute value of each element. For complex input, a + ib, the absolute value is ." }, { "code": null, "e": 25494, "s": 25481, "text": "Parameters :" }, { "code": null, "e": 25570, "s": 25494, "text": "arr : [array_like] Input array or object whose elements, we need to test.\n" }, { "code": null, "e": 25579, "s": 25570, "text": "Return :" }, { "code": null, "e": 25626, "s": 25579, "text": "An array with absolute value of each array. \n" }, { "code": null, "e": 25645, "s": 25626, "text": " Code #1 : Working" }, { "code": "# Python program explaining# absolute () function import numpy as np arr1 = [1, -3, 15, -466]print (\"Absolute Value of arr1 : \\n\", np.absolute(arr1)) arr2 = [23 , -56]print (\"\\nAbsolute Value of arr2 : \\n\", np.absolute(arr2))", "e": 25916, "s": 25645, "text": null }, { "code": null, "e": 25925, "s": 25916, "text": "Output :" }, { "code": null, "e": 26007, "s": 25925, "text": "Absolute Value of arr1 : \n [ 1 3 15 466]\n\nAbsolute Value of arr2 : \n [23 56]\n" }, { "code": null, "e": 26047, "s": 26007, "text": " Code #2 : Working with complex numbers" }, { "code": "# Python program explaining# absolute () function import numpy as np a = 4 + 3jprint(\"Absolute(4 + 3j) : \", np.absolute(a)) b = 16 + 13jprint(\"\\nAbsolute value(16 + 13j) : \", np.absolute(b))", "e": 26276, "s": 26047, "text": null }, { "code": null, "e": 26285, "s": 26276, "text": "Output :" }, { "code": null, "e": 26352, "s": 26285, "text": "Absolute(4 + 3j) : 5.0\n\nAbsolute value(16 + 13j) : 20.6155281281" }, { "code": null, "e": 26407, "s": 26352, "text": " Code #3: Graphical Representation of numpy.absolute()" }, { "code": "# Python program explaining# absolute () function import numpy as npimport matplotlib.pyplot as plt a = np.linspace(start = -5, stop = 5, num = 6, endpoint = True) print(\"Graphical Representation : \\n\", np.absolute(a)) plt.title(\"blue : with absolute\\nred : without absolute\")plt.plot(a, np.absolute(a)) plt.plot(a, a, color = 'red')plt.show()", "e": 26810, "s": 26407, "text": null }, { "code": null, "e": 26819, "s": 26810, "text": "Output :" }, { "code": null, "e": 26875, "s": 26819, "text": "Graphical Representation : \n [ 5. 3. 1. 1. 3. 5.]\n" }, { "code": null, "e": 26968, "s": 26875, "text": "References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.absolute.html." }, { "code": null, "e": 27003, "s": 26968, "text": "Python numpy-Mathematical Function" }, { "code": null, "e": 27016, "s": 27003, "text": "Python-numpy" }, { "code": null, "e": 27023, "s": 27016, "text": "Python" }, { "code": null, "e": 27121, "s": 27023, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27139, "s": 27121, "text": "Python Dictionary" }, { "code": null, "e": 27174, "s": 27139, "text": "Read a file line by line in Python" }, { "code": null, "e": 27206, "s": 27174, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27228, "s": 27206, "text": "Enumerate() in Python" }, { "code": null, "e": 27270, "s": 27228, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27300, "s": 27270, "text": "Iterate over a list in Python" }, { "code": null, "e": 27326, "s": 27300, "text": "Python String | replace()" }, { "code": null, "e": 27355, "s": 27326, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27399, "s": 27355, "text": "Reading and Writing to text files in Python" } ]
Eulerian path and circuit for undirected graph - GeeksforGeeks
18 Jan, 2022 Eulerian Path is a path in graph that visits every edge exactly once. Eulerian Circuit is an Eulerian Path which starts and ends on the same vertex. How to find whether a given graph is Eulerian or not? The problem is same as following question. “Is it possible to draw a given graph without lifting pencil from the paper and without tracing any of the edges more than once”.A graph is called Eulerian if it has an Eulerian Cycle and called Semi-Eulerian if it has an Eulerian Path. The problem seems similar to Hamiltonian Path which is NP complete problem for a general graph. Fortunately, we can find whether a given graph has a Eulerian Path or not in polynomial time. In fact, we can find it in O(V+E) time. Following are some interesting properties of undirected graphs with an Eulerian path and cycle. We can use these properties to find whether a graph is Eulerian or not.Eulerian Cycle An undirected graph has Eulerian cycle if following two conditions are true. ....a) All vertices with non-zero degree are connected. We don’t care about vertices with zero degree because they don’t belong to Eulerian Cycle or Path (we only consider all edges). ....b) All vertices have even degree.Eulerian Path An undirected graph has Eulerian Path if following two conditions are true. ....a) Same as condition (a) for Eulerian Cycle ....b) If zero or two vertices have odd degree and all other vertices have even degree. Note that only one vertex with odd degree is not possible in an undirected graph (sum of all degrees is always even in an undirected graph)Note that a graph with no edges is considered Eulerian because there are no edges to traverse.How does this work? In Eulerian path, each time we visit a vertex v, we walk through two unvisited edges with one end point as v. Therefore, all middle vertices in Eulerian Path must have even degree. For Eulerian Cycle, any vertex can be middle vertex, therefore all vertices must have even degree. C++ Java Python3 C# Javascript // A C++ program to check if a given graph is Eulerian or not#include<iostream>#include <list>using namespace std; // A class that represents an undirected graphclass Graph{ int V; // No. of vertices list<int> *adj; // A dynamic array of adjacency listspublic: // Constructor and destructor Graph(int V) {this->V = V; adj = new list<int>[V]; } ~Graph() { delete [] adj; } // To avoid memory leak // function to add an edge to graph void addEdge(int v, int w); // Method to check if this graph is Eulerian or not int isEulerian(); // Method to check if all non-zero degree vertices are connected bool isConnected(); // Function to do DFS starting from v. Used in isConnected(); void DFSUtil(int v, bool visited[]);}; void Graph::addEdge(int v, int w){ adj[v].push_back(w); adj[w].push_back(v); // Note: the graph is undirected} void Graph::DFSUtil(int v, bool visited[]){ // Mark the current node as visited and print it visited[v] = true; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i, visited);} // Method to check if all non-zero degree vertices are connected.// It mainly does DFS traversal starting frombool Graph::isConnected(){ // Mark all the vertices as not visited bool visited[V]; int i; for (i = 0; i < V; i++) visited[i] = false; // Find a vertex with non-zero degree for (i = 0; i < V; i++) if (adj[i].size() != 0) break; // If there are no edges in the graph, return true if (i == V) return true; // Start DFS traversal from a vertex with non-zero degree DFSUtil(i, visited); // Check if all non-zero degree vertices are visited for (i = 0; i < V; i++) if (visited[i] == false && adj[i].size() > 0) return false; return true;} /* The function returns one of the following values 0 --> If graph is not Eulerian 1 --> If graph has an Euler path (Semi-Eulerian) 2 --> If graph has an Euler Circuit (Eulerian) */int Graph::isEulerian(){ // Check if all non-zero degree vertices are connected if (isConnected() == false) return 0; // Count vertices with odd degree int odd = 0; for (int i = 0; i < V; i++) if (adj[i].size() & 1) odd++; // If count is more than 2, then graph is not Eulerian if (odd > 2) return 0; // If odd count is 2, then semi-eulerian. // If odd count is 0, then eulerian // Note that odd count can never be 1 for undirected graph return (odd)? 1 : 2;} // Function to run test casesvoid test(Graph &g){ int res = g.isEulerian(); if (res == 0) cout << "graph is not Eulerian\n"; else if (res == 1) cout << "graph has a Euler path\n"; else cout << "graph has a Euler cycle\n";} // Driver program to test above functionint main(){ // Let us create and test graphs shown in above figures Graph g1(5); g1.addEdge(1, 0); g1.addEdge(0, 2); g1.addEdge(2, 1); g1.addEdge(0, 3); g1.addEdge(3, 4); test(g1); Graph g2(5); g2.addEdge(1, 0); g2.addEdge(0, 2); g2.addEdge(2, 1); g2.addEdge(0, 3); g2.addEdge(3, 4); g2.addEdge(4, 0); test(g2); Graph g3(5); g3.addEdge(1, 0); g3.addEdge(0, 2); g3.addEdge(2, 1); g3.addEdge(0, 3); g3.addEdge(3, 4); g3.addEdge(1, 3); test(g3); // Let us create a graph with 3 vertices // connected in the form of cycle Graph g4(3); g4.addEdge(0, 1); g4.addEdge(1, 2); g4.addEdge(2, 0); test(g4); // Let us create a graph with all vertices // with zero degree Graph g5(3); test(g5); return 0;} // A Java program to check if a given graph is Eulerian or notimport java.io.*;import java.util.*;import java.util.LinkedList; // This class represents an undirected graph using adjacency list// representationclass Graph{ private int V; // No. of vertices // Array of lists for Adjacency List Representation private LinkedList<Integer> adj[]; // Constructor Graph(int v) { V = v; adj = new LinkedList[v]; for (int i=0; i<v; ++i) adj[i] = new LinkedList(); } //Function to add an edge into the graph void addEdge(int v, int w) { adj[v].add(w);// Add w to v's list. adj[w].add(v); //The graph is undirected } // A function used by DFS void DFSUtil(int v,boolean visited[]) { // Mark the current node as visited visited[v] = true; // Recur for all the vertices adjacent to this vertex Iterator<Integer> i = adj[v].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) DFSUtil(n, visited); } } // Method to check if all non-zero degree vertices are // connected. It mainly does DFS traversal starting from boolean isConnected() { // Mark all the vertices as not visited boolean visited[] = new boolean[V]; int i; for (i = 0; i < V; i++) visited[i] = false; // Find a vertex with non-zero degree for (i = 0; i < V; i++) if (adj[i].size() != 0) break; // If there are no edges in the graph, return true if (i == V) return true; // Start DFS traversal from a vertex with non-zero degree DFSUtil(i, visited); // Check if all non-zero degree vertices are visited for (i = 0; i < V; i++) if (visited[i] == false && adj[i].size() > 0) return false; return true; } /* The function returns one of the following values 0 --> If graph is not Eulerian 1 --> If graph has an Euler path (Semi-Eulerian) 2 --> If graph has an Euler Circuit (Eulerian) */ int isEulerian() { // Check if all non-zero degree vertices are connected if (isConnected() == false) return 0; // Count vertices with odd degree int odd = 0; for (int i = 0; i < V; i++) if (adj[i].size()%2!=0) odd++; // If count is more than 2, then graph is not Eulerian if (odd > 2) return 0; // If odd count is 2, then semi-eulerian. // If odd count is 0, then eulerian // Note that odd count can never be 1 for undirected graph return (odd==2)? 1 : 2; } // Function to run test cases void test() { int res = isEulerian(); if (res == 0) System.out.println("graph is not Eulerian"); else if (res == 1) System.out.println("graph has a Euler path"); else System.out.println("graph has a Euler cycle"); } // Driver method public static void main(String args[]) { // Let us create and test graphs shown in above figures Graph g1 = new Graph(5); g1.addEdge(1, 0); g1.addEdge(0, 2); g1.addEdge(2, 1); g1.addEdge(0, 3); g1.addEdge(3, 4); g1.test(); Graph g2 = new Graph(5); g2.addEdge(1, 0); g2.addEdge(0, 2); g2.addEdge(2, 1); g2.addEdge(0, 3); g2.addEdge(3, 4); g2.addEdge(4, 0); g2.test(); Graph g3 = new Graph(5); g3.addEdge(1, 0); g3.addEdge(0, 2); g3.addEdge(2, 1); g3.addEdge(0, 3); g3.addEdge(3, 4); g3.addEdge(1, 3); g3.test(); // Let us create a graph with 3 vertices // connected in the form of cycle Graph g4 = new Graph(3); g4.addEdge(0, 1); g4.addEdge(1, 2); g4.addEdge(2, 0); g4.test(); // Let us create a graph with all vertices // with zero degree Graph g5 = new Graph(3); g5.test(); }}// This code is contributed by Aakash Hasija # Python program to check if a given graph is Eulerian or not#Complexity : O(V+E) from collections import defaultdict # This class represents a undirected graph using adjacency list representation class 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) self.graph[v].append(u) # A function used by isConnected def DFSUtil(self, v, visited): # Mark the current node as visited visited[v] = True # Recur for all the vertices adjacent to this vertex for i in self.graph[v]: if visited[i] == False: self.DFSUtil(i, visited) '''Method to check if all non-zero degree vertices are connected. It mainly does DFS traversal starting from node with non-zero degree''' def isConnected(self): # Mark all the vertices as not visited visited = [False]*(self.V) # Find a vertex with non-zero degree for i in range(self.V): if len(self.graph[i]) > 1: break # If there are no edges in the graph, return true if i == self.V-1: return True # Start DFS traversal from a vertex with non-zero degree self.DFSUtil(i, visited) # Check if all non-zero degree vertices are visited for i in range(self.V): if visited[i] == False and len(self.graph[i]) > 0: return False return True '''The function returns one of the following values 0 --> If graph is not Eulerian 1 --> If graph has an Euler path (Semi-Eulerian) 2 --> If graph has an Euler Circuit (Eulerian) ''' def isEulerian(self): # Check if all non-zero degree vertices are connected if self.isConnected() == False: return 0 else: # Count vertices with odd degree odd = 0 for i in range(self.V): if len(self.graph[i]) % 2 != 0: odd += 1 '''If odd count is 2, then semi-eulerian. If odd count is 0, then eulerian If count is more than 2, then graph is not Eulerian Note that odd count can never be 1 for undirected graph''' if odd == 0: return 2 elif odd == 2: return 1 elif odd > 2: return 0 # Function to run test cases def test(self): res = self.isEulerian() if res == 0: print("graph is not Eulerian") elif res == 1: print("graph has a Euler path") else: print("graph has a Euler cycle") # Let us create and test graphs shown in above figuresg1 = Graph(5)g1.addEdge(1, 0)g1.addEdge(0, 2)g1.addEdge(2, 1)g1.addEdge(0, 3)g1.addEdge(3, 4)g1.test() g2 = Graph(5)g2.addEdge(1, 0)g2.addEdge(0, 2)g2.addEdge(2, 1)g2.addEdge(0, 3)g2.addEdge(3, 4)g2.addEdge(4, 0)g2.test() g3 = Graph(5)g3.addEdge(1, 0)g3.addEdge(0, 2)g3.addEdge(2, 1)g3.addEdge(0, 3)g3.addEdge(3, 4)g3.addEdge(1, 3)g3.test() # Let us create a graph with 3 vertices# connected in the form of cycleg4 = Graph(3)g4.addEdge(0, 1)g4.addEdge(1, 2)g4.addEdge(2, 0)g4.test() # Let us create a graph with all vertices# with zero degreeg5 = Graph(3)g5.test() # This code is contributed by Neelam Yadav // A C# program to check if a given graph is Eulerian or notusing System;using System.Collections.Generic; // This class represents an undirected graph using adjacency list// representationpublic class Graph{ private int V; // No. of vertices // Array of lists for Adjacency List Representation private List<int> []adj; // Constructor Graph(int v) { V = v; adj = new List<int>[v]; for (int i=0; i<v; ++i) adj[i] = new List<int>(); } //Function to add an edge into the graph void addEdge(int v, int w) { adj[v].Add(w);// Add w to v's list. adj[w].Add(v); //The graph is undirected } // A function used by DFS void DFSUtil(int v,bool []visited) { // Mark the current node as visited visited[v] = true; // Recur for all the vertices adjacent to this vertex foreach(int i in adj[v]){ int n = i; if (!visited[n]) DFSUtil(n, visited); } } // Method to check if all non-zero degree vertices are // connected. It mainly does DFS traversal starting from bool isConnected() { // Mark all the vertices as not visited bool []visited = new bool[V]; int i; for (i = 0; i < V; i++) visited[i] = false; // Find a vertex with non-zero degree for (i = 0; i < V; i++) if (adj[i].Count != 0) break; // If there are no edges in the graph, return true if (i == V) return true; // Start DFS traversal from a vertex with non-zero degree DFSUtil(i, visited); // Check if all non-zero degree vertices are visited for (i = 0; i < V; i++) if (visited[i] == false && adj[i].Count > 0) return false; return true; } /* The function returns one of the following values 0 --> If graph is not Eulerian 1 --> If graph has an Euler path (Semi-Eulerian) 2 --> If graph has an Euler Circuit (Eulerian) */ int isEulerian() { // Check if all non-zero degree vertices are connected if (isConnected() == false) return 0; // Count vertices with odd degree int odd = 0; for (int i = 0; i < V; i++) if (adj[i].Count%2!=0) odd++; // If count is more than 2, then graph is not Eulerian if (odd > 2) return 0; // If odd count is 2, then semi-eulerian. // If odd count is 0, then eulerian // Note that odd count can never be 1 for undirected graph return (odd==2)? 1 : 2; } // Function to run test cases void test() { int res = isEulerian(); if (res == 0) Console.WriteLine("graph is not Eulerian"); else if (res == 1) Console.WriteLine("graph has a Euler path"); else Console.WriteLine("graph has a Euler cycle"); } // Driver method public static void Main(String []args) { // Let us create and test graphs shown in above figures Graph g1 = new Graph(5); g1.addEdge(1, 0); g1.addEdge(0, 2); g1.addEdge(2, 1); g1.addEdge(0, 3); g1.addEdge(3, 4); g1.test(); Graph g2 = new Graph(5); g2.addEdge(1, 0); g2.addEdge(0, 2); g2.addEdge(2, 1); g2.addEdge(0, 3); g2.addEdge(3, 4); g2.addEdge(4, 0); g2.test(); Graph g3 = new Graph(5); g3.addEdge(1, 0); g3.addEdge(0, 2); g3.addEdge(2, 1); g3.addEdge(0, 3); g3.addEdge(3, 4); g3.addEdge(1, 3); g3.test(); // Let us create a graph with 3 vertices // connected in the form of cycle Graph g4 = new Graph(3); g4.addEdge(0, 1); g4.addEdge(1, 2); g4.addEdge(2, 0); g4.test(); // Let us create a graph with all vertices // with zero degree Graph g5 = new Graph(3); g5.test(); }} // This code contributed by PrinciRaj1992 <script>// A Javascript program to check if a given graph is Eulerian or not // This class represents an undirected graph using adjacency list// representationclass Graph{ // Constructor constructor(v) { this.V = v; this.adj = new Array(v); for (let i = 0; i < v; ++i) this.adj[i] = []; } // Function to add an edge into the graph addEdge(v,w) { this.adj[v].push(w);// Add w to v's list. this.adj[w].push(v); //The graph is undirected } // A function used by DFS DFSUtil(v,visited) { // Mark the current node as visited visited[v] = true; // Recur for all the vertices adjacent to this vertex for(let i of this.adj[v]) { let n = i; if (!visited[n]) this.DFSUtil(n, visited); } } // Method to check if all non-zero degree vertices are // connected. It mainly does DFS traversal starting from isConnected() { // Mark all the vertices as not visited let visited = new Array(this.V); let i; for (i = 0; i < this.V; i++) visited[i] = false; // Find a vertex with non-zero degree for (i = 0; i < this.V; i++) if (this.adj[i].length != 0) break; // If there are no edges in the graph, return true if (i == this.V) return true; // Start DFS traversal from a vertex with non-zero degree this.DFSUtil(i, visited); // Check if all non-zero degree vertices are visited for (i = 0; i < this.V; i++) if (visited[i] == false && this.adj[i].length > 0) return false; return true; } /* The function returns one of the following values 0 --> If graph is not Eulerian 1 --> If graph has an Euler path (Semi-Eulerian) 2 --> If graph has an Euler Circuit (Eulerian) */ isEulerian() { // Check if all non-zero degree vertices are connected if (this.isConnected() == false) return 0; // Count vertices with odd degree let odd = 0; for (let i = 0; i < this.V; i++) if (this.adj[i].length%2!=0) odd++; // If count is more than 2, then graph is not Eulerian if (odd > 2) return 0; // If odd count is 2, then semi-eulerian. // If odd count is 0, then eulerian // Note that odd count can never be 1 for undirected graph return (odd==2)? 1 : 2; } // Function to run test cases test() { let res = this.isEulerian(); if (res == 0) document.write("graph is not Eulerian<br>"); else if (res == 1) document.write("graph has a Euler path<br>"); else document.write("graph has a Euler cycle<br>"); }} // Driver method// Let us create and test graphs shown in above figureslet g1 = new Graph(5);g1.addEdge(1, 0);g1.addEdge(0, 2);g1.addEdge(2, 1);g1.addEdge(0, 3);g1.addEdge(3, 4);g1.test(); let g2 = new Graph(5);g2.addEdge(1, 0);g2.addEdge(0, 2);g2.addEdge(2, 1);g2.addEdge(0, 3);g2.addEdge(3, 4);g2.addEdge(4, 0);g2.test(); let g3 = new Graph(5);g3.addEdge(1, 0);g3.addEdge(0, 2);g3.addEdge(2, 1);g3.addEdge(0, 3);g3.addEdge(3, 4);g3.addEdge(1, 3);g3.test(); // Let us create a graph with 3 vertices// connected in the form of cyclelet g4 = new Graph(3);g4.addEdge(0, 1);g4.addEdge(1, 2);g4.addEdge(2, 0);g4.test(); // Let us create a graph with all vertices// with zero degreelet g5 = new Graph(3);g5.test(); // This code is contributed by avanitrachhadiya2155</script> Output: graph has a Euler path graph has a Euler cycle graph is not Eulerian graph has a Euler cycle graph has a Euler cycle Time Complexity: O(V+E)Next Articles: Eulerian Path and Circuit for a Directed Graphs. Fleury’s Algorithm to print a Eulerian Path or Circuit? References: http://en.wikipedia.org/wiki/Eulerian_pathPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above StartingTheLife princiraj1992 xXShreyXx vishalreddy127 avanitrachhadiya2155 gulshankumarar231 varshagumber28 amartyaghoshgfg Euler-Circuit Graph Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Topological Sorting Detect Cycle in a Directed Graph Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Ford-Fulkerson Algorithm for Maximum Flow Problem Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) Detect cycle in an undirected graph Traveling Salesman Problem (TSP) Implementation Find the number of islands | Set 1 (Using DFS) m Coloring Problem | Backtracking-5 Hamiltonian Cycle | Backtracking-6
[ { "code": null, "e": 26473, "s": 26445, "text": "\n18 Jan, 2022" }, { "code": null, "e": 26624, "s": 26473, "text": "Eulerian Path is a path in graph that visits every edge exactly once. Eulerian Circuit is an Eulerian Path which starts and ends on the same vertex. " }, { "code": null, "e": 28432, "s": 26628, "text": "How to find whether a given graph is Eulerian or not? The problem is same as following question. “Is it possible to draw a given graph without lifting pencil from the paper and without tracing any of the edges more than once”.A graph is called Eulerian if it has an Eulerian Cycle and called Semi-Eulerian if it has an Eulerian Path. The problem seems similar to Hamiltonian Path which is NP complete problem for a general graph. Fortunately, we can find whether a given graph has a Eulerian Path or not in polynomial time. In fact, we can find it in O(V+E) time. Following are some interesting properties of undirected graphs with an Eulerian path and cycle. We can use these properties to find whether a graph is Eulerian or not.Eulerian Cycle An undirected graph has Eulerian cycle if following two conditions are true. ....a) All vertices with non-zero degree are connected. We don’t care about vertices with zero degree because they don’t belong to Eulerian Cycle or Path (we only consider all edges). ....b) All vertices have even degree.Eulerian Path An undirected graph has Eulerian Path if following two conditions are true. ....a) Same as condition (a) for Eulerian Cycle ....b) If zero or two vertices have odd degree and all other vertices have even degree. Note that only one vertex with odd degree is not possible in an undirected graph (sum of all degrees is always even in an undirected graph)Note that a graph with no edges is considered Eulerian because there are no edges to traverse.How does this work? In Eulerian path, each time we visit a vertex v, we walk through two unvisited edges with one end point as v. Therefore, all middle vertices in Eulerian Path must have even degree. For Eulerian Cycle, any vertex can be middle vertex, therefore all vertices must have even degree. " }, { "code": null, "e": 28438, "s": 28434, "text": "C++" }, { "code": null, "e": 28443, "s": 28438, "text": "Java" }, { "code": null, "e": 28451, "s": 28443, "text": "Python3" }, { "code": null, "e": 28454, "s": 28451, "text": "C#" }, { "code": null, "e": 28465, "s": 28454, "text": "Javascript" }, { "code": "// A C++ program to check if a given graph is Eulerian or not#include<iostream>#include <list>using namespace std; // A class that represents an undirected graphclass Graph{ int V; // No. of vertices list<int> *adj; // A dynamic array of adjacency listspublic: // Constructor and destructor Graph(int V) {this->V = V; adj = new list<int>[V]; } ~Graph() { delete [] adj; } // To avoid memory leak // function to add an edge to graph void addEdge(int v, int w); // Method to check if this graph is Eulerian or not int isEulerian(); // Method to check if all non-zero degree vertices are connected bool isConnected(); // Function to do DFS starting from v. Used in isConnected(); void DFSUtil(int v, bool visited[]);}; void Graph::addEdge(int v, int w){ adj[v].push_back(w); adj[w].push_back(v); // Note: the graph is undirected} void Graph::DFSUtil(int v, bool visited[]){ // Mark the current node as visited and print it visited[v] = true; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i, visited);} // Method to check if all non-zero degree vertices are connected.// It mainly does DFS traversal starting frombool Graph::isConnected(){ // Mark all the vertices as not visited bool visited[V]; int i; for (i = 0; i < V; i++) visited[i] = false; // Find a vertex with non-zero degree for (i = 0; i < V; i++) if (adj[i].size() != 0) break; // If there are no edges in the graph, return true if (i == V) return true; // Start DFS traversal from a vertex with non-zero degree DFSUtil(i, visited); // Check if all non-zero degree vertices are visited for (i = 0; i < V; i++) if (visited[i] == false && adj[i].size() > 0) return false; return true;} /* The function returns one of the following values 0 --> If graph is not Eulerian 1 --> If graph has an Euler path (Semi-Eulerian) 2 --> If graph has an Euler Circuit (Eulerian) */int Graph::isEulerian(){ // Check if all non-zero degree vertices are connected if (isConnected() == false) return 0; // Count vertices with odd degree int odd = 0; for (int i = 0; i < V; i++) if (adj[i].size() & 1) odd++; // If count is more than 2, then graph is not Eulerian if (odd > 2) return 0; // If odd count is 2, then semi-eulerian. // If odd count is 0, then eulerian // Note that odd count can never be 1 for undirected graph return (odd)? 1 : 2;} // Function to run test casesvoid test(Graph &g){ int res = g.isEulerian(); if (res == 0) cout << \"graph is not Eulerian\\n\"; else if (res == 1) cout << \"graph has a Euler path\\n\"; else cout << \"graph has a Euler cycle\\n\";} // Driver program to test above functionint main(){ // Let us create and test graphs shown in above figures Graph g1(5); g1.addEdge(1, 0); g1.addEdge(0, 2); g1.addEdge(2, 1); g1.addEdge(0, 3); g1.addEdge(3, 4); test(g1); Graph g2(5); g2.addEdge(1, 0); g2.addEdge(0, 2); g2.addEdge(2, 1); g2.addEdge(0, 3); g2.addEdge(3, 4); g2.addEdge(4, 0); test(g2); Graph g3(5); g3.addEdge(1, 0); g3.addEdge(0, 2); g3.addEdge(2, 1); g3.addEdge(0, 3); g3.addEdge(3, 4); g3.addEdge(1, 3); test(g3); // Let us create a graph with 3 vertices // connected in the form of cycle Graph g4(3); g4.addEdge(0, 1); g4.addEdge(1, 2); g4.addEdge(2, 0); test(g4); // Let us create a graph with all vertices // with zero degree Graph g5(3); test(g5); return 0;}", "e": 32218, "s": 28465, "text": null }, { "code": "// A Java program to check if a given graph is Eulerian or notimport java.io.*;import java.util.*;import java.util.LinkedList; // This class represents an undirected graph using adjacency list// representationclass Graph{ private int V; // No. of vertices // Array of lists for Adjacency List Representation private LinkedList<Integer> adj[]; // Constructor Graph(int v) { V = v; adj = new LinkedList[v]; for (int i=0; i<v; ++i) adj[i] = new LinkedList(); } //Function to add an edge into the graph void addEdge(int v, int w) { adj[v].add(w);// Add w to v's list. adj[w].add(v); //The graph is undirected } // A function used by DFS void DFSUtil(int v,boolean visited[]) { // Mark the current node as visited visited[v] = true; // Recur for all the vertices adjacent to this vertex Iterator<Integer> i = adj[v].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) DFSUtil(n, visited); } } // Method to check if all non-zero degree vertices are // connected. It mainly does DFS traversal starting from boolean isConnected() { // Mark all the vertices as not visited boolean visited[] = new boolean[V]; int i; for (i = 0; i < V; i++) visited[i] = false; // Find a vertex with non-zero degree for (i = 0; i < V; i++) if (adj[i].size() != 0) break; // If there are no edges in the graph, return true if (i == V) return true; // Start DFS traversal from a vertex with non-zero degree DFSUtil(i, visited); // Check if all non-zero degree vertices are visited for (i = 0; i < V; i++) if (visited[i] == false && adj[i].size() > 0) return false; return true; } /* The function returns one of the following values 0 --> If graph is not Eulerian 1 --> If graph has an Euler path (Semi-Eulerian) 2 --> If graph has an Euler Circuit (Eulerian) */ int isEulerian() { // Check if all non-zero degree vertices are connected if (isConnected() == false) return 0; // Count vertices with odd degree int odd = 0; for (int i = 0; i < V; i++) if (adj[i].size()%2!=0) odd++; // If count is more than 2, then graph is not Eulerian if (odd > 2) return 0; // If odd count is 2, then semi-eulerian. // If odd count is 0, then eulerian // Note that odd count can never be 1 for undirected graph return (odd==2)? 1 : 2; } // Function to run test cases void test() { int res = isEulerian(); if (res == 0) System.out.println(\"graph is not Eulerian\"); else if (res == 1) System.out.println(\"graph has a Euler path\"); else System.out.println(\"graph has a Euler cycle\"); } // Driver method public static void main(String args[]) { // Let us create and test graphs shown in above figures Graph g1 = new Graph(5); g1.addEdge(1, 0); g1.addEdge(0, 2); g1.addEdge(2, 1); g1.addEdge(0, 3); g1.addEdge(3, 4); g1.test(); Graph g2 = new Graph(5); g2.addEdge(1, 0); g2.addEdge(0, 2); g2.addEdge(2, 1); g2.addEdge(0, 3); g2.addEdge(3, 4); g2.addEdge(4, 0); g2.test(); Graph g3 = new Graph(5); g3.addEdge(1, 0); g3.addEdge(0, 2); g3.addEdge(2, 1); g3.addEdge(0, 3); g3.addEdge(3, 4); g3.addEdge(1, 3); g3.test(); // Let us create a graph with 3 vertices // connected in the form of cycle Graph g4 = new Graph(3); g4.addEdge(0, 1); g4.addEdge(1, 2); g4.addEdge(2, 0); g4.test(); // Let us create a graph with all vertices // with zero degree Graph g5 = new Graph(3); g5.test(); }}// This code is contributed by Aakash Hasija", "e": 36381, "s": 32218, "text": null }, { "code": "# Python program to check if a given graph is Eulerian or not#Complexity : O(V+E) from collections import defaultdict # This class represents a undirected graph using adjacency list representation class 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) self.graph[v].append(u) # A function used by isConnected def DFSUtil(self, v, visited): # Mark the current node as visited visited[v] = True # Recur for all the vertices adjacent to this vertex for i in self.graph[v]: if visited[i] == False: self.DFSUtil(i, visited) '''Method to check if all non-zero degree vertices are connected. It mainly does DFS traversal starting from node with non-zero degree''' def isConnected(self): # Mark all the vertices as not visited visited = [False]*(self.V) # Find a vertex with non-zero degree for i in range(self.V): if len(self.graph[i]) > 1: break # If there are no edges in the graph, return true if i == self.V-1: return True # Start DFS traversal from a vertex with non-zero degree self.DFSUtil(i, visited) # Check if all non-zero degree vertices are visited for i in range(self.V): if visited[i] == False and len(self.graph[i]) > 0: return False return True '''The function returns one of the following values 0 --> If graph is not Eulerian 1 --> If graph has an Euler path (Semi-Eulerian) 2 --> If graph has an Euler Circuit (Eulerian) ''' def isEulerian(self): # Check if all non-zero degree vertices are connected if self.isConnected() == False: return 0 else: # Count vertices with odd degree odd = 0 for i in range(self.V): if len(self.graph[i]) % 2 != 0: odd += 1 '''If odd count is 2, then semi-eulerian. If odd count is 0, then eulerian If count is more than 2, then graph is not Eulerian Note that odd count can never be 1 for undirected graph''' if odd == 0: return 2 elif odd == 2: return 1 elif odd > 2: return 0 # Function to run test cases def test(self): res = self.isEulerian() if res == 0: print(\"graph is not Eulerian\") elif res == 1: print(\"graph has a Euler path\") else: print(\"graph has a Euler cycle\") # Let us create and test graphs shown in above figuresg1 = Graph(5)g1.addEdge(1, 0)g1.addEdge(0, 2)g1.addEdge(2, 1)g1.addEdge(0, 3)g1.addEdge(3, 4)g1.test() g2 = Graph(5)g2.addEdge(1, 0)g2.addEdge(0, 2)g2.addEdge(2, 1)g2.addEdge(0, 3)g2.addEdge(3, 4)g2.addEdge(4, 0)g2.test() g3 = Graph(5)g3.addEdge(1, 0)g3.addEdge(0, 2)g3.addEdge(2, 1)g3.addEdge(0, 3)g3.addEdge(3, 4)g3.addEdge(1, 3)g3.test() # Let us create a graph with 3 vertices# connected in the form of cycleg4 = Graph(3)g4.addEdge(0, 1)g4.addEdge(1, 2)g4.addEdge(2, 0)g4.test() # Let us create a graph with all vertices# with zero degreeg5 = Graph(3)g5.test() # This code is contributed by Neelam Yadav", "e": 39823, "s": 36381, "text": null }, { "code": "// A C# program to check if a given graph is Eulerian or notusing System;using System.Collections.Generic; // This class represents an undirected graph using adjacency list// representationpublic class Graph{ private int V; // No. of vertices // Array of lists for Adjacency List Representation private List<int> []adj; // Constructor Graph(int v) { V = v; adj = new List<int>[v]; for (int i=0; i<v; ++i) adj[i] = new List<int>(); } //Function to add an edge into the graph void addEdge(int v, int w) { adj[v].Add(w);// Add w to v's list. adj[w].Add(v); //The graph is undirected } // A function used by DFS void DFSUtil(int v,bool []visited) { // Mark the current node as visited visited[v] = true; // Recur for all the vertices adjacent to this vertex foreach(int i in adj[v]){ int n = i; if (!visited[n]) DFSUtil(n, visited); } } // Method to check if all non-zero degree vertices are // connected. It mainly does DFS traversal starting from bool isConnected() { // Mark all the vertices as not visited bool []visited = new bool[V]; int i; for (i = 0; i < V; i++) visited[i] = false; // Find a vertex with non-zero degree for (i = 0; i < V; i++) if (adj[i].Count != 0) break; // If there are no edges in the graph, return true if (i == V) return true; // Start DFS traversal from a vertex with non-zero degree DFSUtil(i, visited); // Check if all non-zero degree vertices are visited for (i = 0; i < V; i++) if (visited[i] == false && adj[i].Count > 0) return false; return true; } /* The function returns one of the following values 0 --> If graph is not Eulerian 1 --> If graph has an Euler path (Semi-Eulerian) 2 --> If graph has an Euler Circuit (Eulerian) */ int isEulerian() { // Check if all non-zero degree vertices are connected if (isConnected() == false) return 0; // Count vertices with odd degree int odd = 0; for (int i = 0; i < V; i++) if (adj[i].Count%2!=0) odd++; // If count is more than 2, then graph is not Eulerian if (odd > 2) return 0; // If odd count is 2, then semi-eulerian. // If odd count is 0, then eulerian // Note that odd count can never be 1 for undirected graph return (odd==2)? 1 : 2; } // Function to run test cases void test() { int res = isEulerian(); if (res == 0) Console.WriteLine(\"graph is not Eulerian\"); else if (res == 1) Console.WriteLine(\"graph has a Euler path\"); else Console.WriteLine(\"graph has a Euler cycle\"); } // Driver method public static void Main(String []args) { // Let us create and test graphs shown in above figures Graph g1 = new Graph(5); g1.addEdge(1, 0); g1.addEdge(0, 2); g1.addEdge(2, 1); g1.addEdge(0, 3); g1.addEdge(3, 4); g1.test(); Graph g2 = new Graph(5); g2.addEdge(1, 0); g2.addEdge(0, 2); g2.addEdge(2, 1); g2.addEdge(0, 3); g2.addEdge(3, 4); g2.addEdge(4, 0); g2.test(); Graph g3 = new Graph(5); g3.addEdge(1, 0); g3.addEdge(0, 2); g3.addEdge(2, 1); g3.addEdge(0, 3); g3.addEdge(3, 4); g3.addEdge(1, 3); g3.test(); // Let us create a graph with 3 vertices // connected in the form of cycle Graph g4 = new Graph(3); g4.addEdge(0, 1); g4.addEdge(1, 2); g4.addEdge(2, 0); g4.test(); // Let us create a graph with all vertices // with zero degree Graph g5 = new Graph(3); g5.test(); }} // This code contributed by PrinciRaj1992", "e": 43902, "s": 39823, "text": null }, { "code": "<script>// A Javascript program to check if a given graph is Eulerian or not // This class represents an undirected graph using adjacency list// representationclass Graph{ // Constructor constructor(v) { this.V = v; this.adj = new Array(v); for (let i = 0; i < v; ++i) this.adj[i] = []; } // Function to add an edge into the graph addEdge(v,w) { this.adj[v].push(w);// Add w to v's list. this.adj[w].push(v); //The graph is undirected } // A function used by DFS DFSUtil(v,visited) { // Mark the current node as visited visited[v] = true; // Recur for all the vertices adjacent to this vertex for(let i of this.adj[v]) { let n = i; if (!visited[n]) this.DFSUtil(n, visited); } } // Method to check if all non-zero degree vertices are // connected. It mainly does DFS traversal starting from isConnected() { // Mark all the vertices as not visited let visited = new Array(this.V); let i; for (i = 0; i < this.V; i++) visited[i] = false; // Find a vertex with non-zero degree for (i = 0; i < this.V; i++) if (this.adj[i].length != 0) break; // If there are no edges in the graph, return true if (i == this.V) return true; // Start DFS traversal from a vertex with non-zero degree this.DFSUtil(i, visited); // Check if all non-zero degree vertices are visited for (i = 0; i < this.V; i++) if (visited[i] == false && this.adj[i].length > 0) return false; return true; } /* The function returns one of the following values 0 --> If graph is not Eulerian 1 --> If graph has an Euler path (Semi-Eulerian) 2 --> If graph has an Euler Circuit (Eulerian) */ isEulerian() { // Check if all non-zero degree vertices are connected if (this.isConnected() == false) return 0; // Count vertices with odd degree let odd = 0; for (let i = 0; i < this.V; i++) if (this.adj[i].length%2!=0) odd++; // If count is more than 2, then graph is not Eulerian if (odd > 2) return 0; // If odd count is 2, then semi-eulerian. // If odd count is 0, then eulerian // Note that odd count can never be 1 for undirected graph return (odd==2)? 1 : 2; } // Function to run test cases test() { let res = this.isEulerian(); if (res == 0) document.write(\"graph is not Eulerian<br>\"); else if (res == 1) document.write(\"graph has a Euler path<br>\"); else document.write(\"graph has a Euler cycle<br>\"); }} // Driver method// Let us create and test graphs shown in above figureslet g1 = new Graph(5);g1.addEdge(1, 0);g1.addEdge(0, 2);g1.addEdge(2, 1);g1.addEdge(0, 3);g1.addEdge(3, 4);g1.test(); let g2 = new Graph(5);g2.addEdge(1, 0);g2.addEdge(0, 2);g2.addEdge(2, 1);g2.addEdge(0, 3);g2.addEdge(3, 4);g2.addEdge(4, 0);g2.test(); let g3 = new Graph(5);g3.addEdge(1, 0);g3.addEdge(0, 2);g3.addEdge(2, 1);g3.addEdge(0, 3);g3.addEdge(3, 4);g3.addEdge(1, 3);g3.test(); // Let us create a graph with 3 vertices// connected in the form of cyclelet g4 = new Graph(3);g4.addEdge(0, 1);g4.addEdge(1, 2);g4.addEdge(2, 0);g4.test(); // Let us create a graph with all vertices// with zero degreelet g5 = new Graph(3);g5.test(); // This code is contributed by avanitrachhadiya2155</script>", "e": 47565, "s": 43902, "text": null }, { "code": null, "e": 47574, "s": 47565, "text": "Output: " }, { "code": null, "e": 47691, "s": 47574, "text": "graph has a Euler path\ngraph has a Euler cycle\ngraph is not Eulerian\ngraph has a Euler cycle\ngraph has a Euler cycle" }, { "code": null, "e": 48012, "s": 47691, "text": "Time Complexity: O(V+E)Next Articles: Eulerian Path and Circuit for a Directed Graphs. Fleury’s Algorithm to print a Eulerian Path or Circuit? References: http://en.wikipedia.org/wiki/Eulerian_pathPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 48028, "s": 48012, "text": "StartingTheLife" }, { "code": null, "e": 48042, "s": 48028, "text": "princiraj1992" }, { "code": null, "e": 48052, "s": 48042, "text": "xXShreyXx" }, { "code": null, "e": 48067, "s": 48052, "text": "vishalreddy127" }, { "code": null, "e": 48088, "s": 48067, "text": "avanitrachhadiya2155" }, { "code": null, "e": 48106, "s": 48088, "text": "gulshankumarar231" }, { "code": null, "e": 48121, "s": 48106, "text": "varshagumber28" }, { "code": null, "e": 48137, "s": 48121, "text": "amartyaghoshgfg" }, { "code": null, "e": 48151, "s": 48137, "text": "Euler-Circuit" }, { "code": null, "e": 48157, "s": 48151, "text": "Graph" }, { "code": null, "e": 48163, "s": 48157, "text": "Graph" }, { "code": null, "e": 48261, "s": 48163, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 48281, "s": 48261, "text": "Topological Sorting" }, { "code": null, "e": 48314, "s": 48281, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 48382, "s": 48314, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 48432, "s": 48382, "text": "Ford-Fulkerson Algorithm for Maximum Flow Problem" }, { "code": null, "e": 48507, "s": 48432, "text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)" }, { "code": null, "e": 48543, "s": 48507, "text": "Detect cycle in an undirected graph" }, { "code": null, "e": 48591, "s": 48543, "text": "Traveling Salesman Problem (TSP) Implementation" }, { "code": null, "e": 48638, "s": 48591, "text": "Find the number of islands | Set 1 (Using DFS)" }, { "code": null, "e": 48674, "s": 48638, "text": "m Coloring Problem | Backtracking-5" } ]
Python | Arrange the files in directories according to extensions - GeeksforGeeks
09 Sep, 2019 In this article, we will learn how to arrange the files in different directories according to their extensions. When you have a lot of files with different extension than you can simply use the script for your help. Below is the Python implementation – import os # Using system functions import shutil # Moving file to different folders. # Changing the folder location.os.chdir(os.getcwd())cwd = os.getcwd() # For listing files from the folder. l = [f for f in os.listdir(cwd) if os.path.isfile(f)] l2 = [] # Get the extension of file from list l. for value in l: s = value.split('.')[1] l2.append(s)print(l, l2) # We remove duplicate values from # list l2 and checks if directory # exists otherwise we create new one for extension in set(l2): dirname = extension if os.path.exists(cwd+'\'+extension): pass else: os.makedirs(dirname) # We use zip function and list l and# l2 passed as arguments.# If extension in file is same and# file not exists then we move the file. for files, extension in zip(l, l2): if extension in files: if os.path.exists(cwd+'\'+extension+'\'+files): pass else: shutil.move(cwd+'\'+files, cwd+'\'+extension) print(extension, files) else : print('error') Files Not Arranged: Files Arranged: ['arrange.py', 'mydata.pdf', 'python.exe', 'resume.doc'] ['py', 'pdf', 'exe', 'doc'] py arrange.py pdf mydata.pdf exe python.exe doc resume.doc python-utility 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 How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25587, "s": 25559, "text": "\n09 Sep, 2019" }, { "code": null, "e": 25803, "s": 25587, "text": "In this article, we will learn how to arrange the files in different directories according to their extensions. When you have a lot of files with different extension than you can simply use the script for your help." }, { "code": null, "e": 25840, "s": 25803, "text": "Below is the Python implementation –" }, { "code": "import os # Using system functions import shutil # Moving file to different folders. # Changing the folder location.os.chdir(os.getcwd())cwd = os.getcwd() # For listing files from the folder. l = [f for f in os.listdir(cwd) if os.path.isfile(f)] l2 = [] # Get the extension of file from list l. for value in l: s = value.split('.')[1] l2.append(s)print(l, l2) # We remove duplicate values from # list l2 and checks if directory # exists otherwise we create new one for extension in set(l2): dirname = extension if os.path.exists(cwd+'\\'+extension): pass else: os.makedirs(dirname) # We use zip function and list l and# l2 passed as arguments.# If extension in file is same and# file not exists then we move the file. for files, extension in zip(l, l2): if extension in files: if os.path.exists(cwd+'\\'+extension+'\\'+files): pass else: shutil.move(cwd+'\\'+files, cwd+'\\'+extension) print(extension, files) else : print('error')", "e": 26866, "s": 25840, "text": null }, { "code": null, "e": 26886, "s": 26866, "text": "Files Not Arranged:" }, { "code": null, "e": 26902, "s": 26886, "text": "Files Arranged:" }, { "code": null, "e": 27047, "s": 26902, "text": "['arrange.py', 'mydata.pdf', 'python.exe', 'resume.doc'] ['py', 'pdf', 'exe', 'doc']\npy arrange.py\npdf mydata.pdf\nexe python.exe\ndoc resume.doc\n" }, { "code": null, "e": 27062, "s": 27047, "text": "python-utility" }, { "code": null, "e": 27069, "s": 27062, "text": "Python" }, { "code": null, "e": 27167, "s": 27069, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27185, "s": 27167, "text": "Python Dictionary" }, { "code": null, "e": 27220, "s": 27185, "text": "Read a file line by line in Python" }, { "code": null, "e": 27252, "s": 27220, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27274, "s": 27252, "text": "Enumerate() in Python" }, { "code": null, "e": 27316, "s": 27274, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27346, "s": 27316, "text": "Iterate over a list in Python" }, { "code": null, "e": 27372, "s": 27346, "text": "Python String | replace()" }, { "code": null, "e": 27401, "s": 27372, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27445, "s": 27401, "text": "Reading and Writing to text files in Python" } ]
Local inner class in Java
In Java, just like methods, variables of a class too can have another class as its member. Writing a class within another is allowed in Java. The class written within is called the nested class, and the class that holds the inner class is called the outer class. Following is the syntax to write a nested class. Here, the class Outer_Demo is the outer class and the class Inner_Demo is the nested class. class Outer_Demo { class Inner_Demo { } } Nested classes are divided into two types. Non-static nested classes − These are the non-static members of a class. Non-static nested classes − These are the non-static members of a class. Static nested classes − These are the static members of a class. Static nested classes − These are the static members of a class. Inner classes are a security mechanism in Java. We know a class cannot be associated with the access modifier private, but if we have the class as a member of other class, then the inner class can be made private. And this is also used to access the private members of a class. Inner classes are of three types depending on how and where you define them. They are − Inner Class Method-local Inner Class Anonymous Inner Class Creating an inner class is quite simple. You just need to write a class within a class. Unlike a class, an inner class can be private and once you declare an inner class private, it cannot be accessed from an object outside the class. Following is the program to create an inner class and access it. In the given example, we make the inner class private and access the class through a method. Live Demo class Outer_Demo { int num; // inner class private class Inner_Demo { public void print() { System.out.println("This is an inner class"); } } // Accessing he inner class from the method within void display_Inner() { Inner_Demo inner = new Inner_Demo(); inner.print(); } } public class My_class { public static void main(String args[]) { // Instantiating the outer class Outer_Demo outer = new Outer_Demo(); // Accessing the display_Inner() method. outer.display_Inner(); } } Here you can observe that Outer_Demo is the outer class, Inner_Demo is the inner class, display_Inner() is the method inside which we are instantiating the inner class, and this method is invoked from the main method. If you compile and execute the above program, you will get the following result. This is an inner class. As mentioned earlier, inner classes are also used to access the private members of a class. Suppose, a class is having private members to access them. Write an inner class in it, return the private members from a method within the inner class, say, getValue(), and finally from another class (from which you want to access the private members) call the getValue() method of the inner class. To instantiate the inner class, initially you have to instantiate the outer class. Thereafter, using the object of the outer class, following is the way in which you can instantiate the inner class. Outer_Demo outer = new Outer_Demo(); Outer_Demo.Inner_Demo inner = outer.new Inner_Demo(); The following program shows how to access the private members of a class using inner class. Example class Outer_Demo { // private variable of the outer class private int num = 175; // inner class public class Inner_Demo { public int getNum() { System.out.println("This is the getnum method of the inner class"); return num; } } } public class My_class2 { public static void main(String args[]) { // Instantiating the outer class Outer_Demo outer = new Outer_Demo(); // Instantiating the inner class Outer_Demo.Inner_Demo inner = outer.new Inner_Demo(); System.out.println(inner.getNum()); } } If you compile and execute the above program, you will get the following result. This is the getnum method of the inner class: 175 In Java, we can write a class within a method and this will be a local type. Like local variables, the scope of the inner class is restricted within the method. A method-local inner class can be instantiated only within the method where the inner class is defined. The following program shows how to use a method-local inner class. Example Live Demo public class Outerclass { // instance method of the outer class void my_Method() { int num = 23; // method-local inner class class MethodInner_Demo { public void print() { System.out.println("This is method inner class "+num); } } // end of inner class // Accessing the inner class MethodInner_Demo inner = new MethodInner_Demo(); inner.print(); } public static void main(String args[]) { Outerclass outer = new Outerclass(); outer.my_Method(); } } If you compile and execute the above program, you will get the following result. This is method inner class 23 An inner class declared without a class name is known as an anonymous inner class. In case of anonymous inner classes, we declare and instantiate them at the same time. Generally, they are used whenever you need to override the method of a class or an interface. The syntax of an anonymous inner class is as follows. Syntax AnonymousInner an_inner = new AnonymousInner() { public void my_method() { ........ ........ } }; The following program shows how to override the method of a class using anonymous inner class. Live Demo abstract class AnonymousInner { public abstract void mymethod(); } public class Outer_class { public static void main(String args[]) { AnonymousInner inner = new AnonymousInner() { public void mymethod() { System.out.println("This is an example of anonymous inner class"); } }; inner.mymethod(); } } If you compile and execute the above program, you will get the following result. This is an example of anonymous inner class In the same way, you can override the methods of the concrete class as well as the interface using an anonymous inner class. Generally, if a method accepts an object of an interface, an abstract class, or a concrete class, then we can implement the interface, extend the abstract class, and pass the object to the method. If it is a class, then we can directly pass it to the method. But in all the three cases, you can pass an anonymous inner class to the method. Here is the syntax of passing an anonymous inner class as a method argument. obj.my_Method(new My_Class() { public void Do() { ..... ..... } }); The following program shows how to pass an anonymous inner class as a method argument. Live Demo // interface interface Message { String greet(); } public class My_class { // method which accepts the object of interface Message public void displayMessage(Message m) { System.out.println(m.greet() + ", This is an example of anonymous inner class as an argument"); } public static void main(String args[]) { // Instantiating the class My_class obj = new My_class(); // Passing an anonymous inner class as an argument obj.displayMessage(new Message() { public String greet() { return "Hello"; } }); } } If you compile and execute the above program, it gives you the following result. Hello, This is an example of anonymous inner class as an argument
[ { "code": null, "e": 1325, "s": 1062, "text": "In Java, just like methods, variables of a class too can have another class as its member. Writing a class within another is allowed in Java. The class written within is called the nested class, and the class that holds the inner class is called the outer class." }, { "code": null, "e": 1466, "s": 1325, "text": "Following is the syntax to write a nested class. Here, the class Outer_Demo is the outer class and the class Inner_Demo is the nested class." }, { "code": null, "e": 1514, "s": 1466, "text": "class Outer_Demo {\n class Inner_Demo {\n }\n}" }, { "code": null, "e": 1557, "s": 1514, "text": "Nested classes are divided into two types." }, { "code": null, "e": 1630, "s": 1557, "text": "Non-static nested classes − These are the non-static members of a class." }, { "code": null, "e": 1703, "s": 1630, "text": "Non-static nested classes − These are the non-static members of a class." }, { "code": null, "e": 1768, "s": 1703, "text": "Static nested classes − These are the static members of a class." }, { "code": null, "e": 1833, "s": 1768, "text": "Static nested classes − These are the static members of a class." }, { "code": null, "e": 2111, "s": 1833, "text": "Inner classes are a security mechanism in Java. We know a class cannot be associated with the access modifier private, but if we have the class as a member of other class, then the inner class can be made private. And this is also used to access the private members of a class." }, { "code": null, "e": 2199, "s": 2111, "text": "Inner classes are of three types depending on how and where you define them. They are −" }, { "code": null, "e": 2211, "s": 2199, "text": "Inner Class" }, { "code": null, "e": 2236, "s": 2211, "text": "Method-local Inner Class" }, { "code": null, "e": 2258, "s": 2236, "text": "Anonymous Inner Class" }, { "code": null, "e": 2493, "s": 2258, "text": "Creating an inner class is quite simple. You just need to write a class within a class. Unlike a class, an inner class can be private and once you declare an inner class private, it cannot be accessed from an object outside the class." }, { "code": null, "e": 2651, "s": 2493, "text": "Following is the program to create an inner class and access it. In the given example, we make the inner class private and access the class through a method." }, { "code": null, "e": 2662, "s": 2651, "text": " Live Demo" }, { "code": null, "e": 3221, "s": 2662, "text": "class Outer_Demo {\n int num;\n // inner class\n private class Inner_Demo {\n public void print() {\n System.out.println(\"This is an inner class\");\n }\n }\n // Accessing he inner class from the method within\n void display_Inner() {\n Inner_Demo inner = new Inner_Demo();\n inner.print();\n }\n}\npublic class My_class {\n public static void main(String args[]) {\n // Instantiating the outer class\n Outer_Demo outer = new Outer_Demo();\n // Accessing the display_Inner() method.\n outer.display_Inner();\n }\n}" }, { "code": null, "e": 3439, "s": 3221, "text": "Here you can observe that Outer_Demo is the outer class, Inner_Demo is the inner class, display_Inner() is the method inside which we are instantiating the inner class, and this method is invoked from the main method." }, { "code": null, "e": 3520, "s": 3439, "text": "If you compile and execute the above program, you will get the following result." }, { "code": null, "e": 3544, "s": 3520, "text": "This is an inner class." }, { "code": null, "e": 3935, "s": 3544, "text": "As mentioned earlier, inner classes are also used to access the private members of a class. Suppose, a class is having private members to access them. Write an inner class in it, return the private members from a method within the inner class, say, getValue(), and finally from another class (from which you want to access the private members) call the getValue() method of the inner class." }, { "code": null, "e": 4134, "s": 3935, "text": "To instantiate the inner class, initially you have to instantiate the outer class. Thereafter, using the object of the outer class, following is the way in which you can instantiate the inner class." }, { "code": null, "e": 4225, "s": 4134, "text": "Outer_Demo outer = new Outer_Demo();\nOuter_Demo.Inner_Demo inner = outer.new Inner_Demo();" }, { "code": null, "e": 4317, "s": 4225, "text": "The following program shows how to access the private members of a class using inner class." }, { "code": null, "e": 4325, "s": 4317, "text": "Example" }, { "code": null, "e": 4899, "s": 4325, "text": "class Outer_Demo {\n // private variable of the outer class\n private int num = 175;\n // inner class\n public class Inner_Demo {\n public int getNum() {\n System.out.println(\"This is the getnum method of the inner class\");\n return num;\n }\n }\n}\npublic class My_class2 {\n public static void main(String args[]) {\n // Instantiating the outer class\n Outer_Demo outer = new Outer_Demo();\n // Instantiating the inner class\n Outer_Demo.Inner_Demo inner = outer.new Inner_Demo();\n System.out.println(inner.getNum());\n }\n}" }, { "code": null, "e": 4980, "s": 4899, "text": "If you compile and execute the above program, you will get the following result." }, { "code": null, "e": 5030, "s": 4980, "text": "This is the getnum method of the inner class: 175" }, { "code": null, "e": 5191, "s": 5030, "text": "In Java, we can write a class within a method and this will be a local type. Like local variables, the scope of the inner class is restricted within the method." }, { "code": null, "e": 5362, "s": 5191, "text": "A method-local inner class can be instantiated only within the method where the inner class is defined. The following program shows how to use a method-local inner class." }, { "code": null, "e": 5370, "s": 5362, "text": "Example" }, { "code": null, "e": 5381, "s": 5370, "text": " Live Demo" }, { "code": null, "e": 5929, "s": 5381, "text": "public class Outerclass {\n // instance method of the outer class\n void my_Method() {\n int num = 23;\n // method-local inner class\n class MethodInner_Demo {\n public void print() {\n System.out.println(\"This is method inner class \"+num);\n }\n } // end of inner class\n // Accessing the inner class\n MethodInner_Demo inner = new MethodInner_Demo();\n inner.print();\n }\n public static void main(String args[]) {\n Outerclass outer = new Outerclass();\n outer.my_Method();\n }\n}" }, { "code": null, "e": 6010, "s": 5929, "text": "If you compile and execute the above program, you will get the following result." }, { "code": null, "e": 6040, "s": 6010, "text": "This is method inner class 23" }, { "code": null, "e": 6357, "s": 6040, "text": "An inner class declared without a class name is known as an anonymous inner class. In case of anonymous inner classes, we declare and instantiate them at the same time. Generally, they are used whenever you need to override the method of a class or an interface. The syntax of an anonymous inner class is as follows." }, { "code": null, "e": 6364, "s": 6357, "text": "Syntax" }, { "code": null, "e": 6480, "s": 6364, "text": "AnonymousInner an_inner = new AnonymousInner() {\n public void my_method() {\n ........\n ........\n }\n};" }, { "code": null, "e": 6575, "s": 6480, "text": "The following program shows how to override the method of a class using anonymous inner class." }, { "code": null, "e": 6586, "s": 6575, "text": " Live Demo" }, { "code": null, "e": 6943, "s": 6586, "text": "abstract class AnonymousInner {\n public abstract void mymethod();\n}\npublic class Outer_class {\n public static void main(String args[]) {\n AnonymousInner inner = new AnonymousInner() {\n public void mymethod() {\n System.out.println(\"This is an example of anonymous inner class\");\n }\n };\n inner.mymethod();\n }\n}" }, { "code": null, "e": 7024, "s": 6943, "text": "If you compile and execute the above program, you will get the following result." }, { "code": null, "e": 7068, "s": 7024, "text": "This is an example of anonymous inner class" }, { "code": null, "e": 7193, "s": 7068, "text": "In the same way, you can override the methods of the concrete class as well as the interface using an anonymous inner class." }, { "code": null, "e": 7452, "s": 7193, "text": "Generally, if a method accepts an object of an interface, an abstract class, or a concrete class, then we can implement the interface, extend the abstract class, and pass the object to the method. If it is a class, then we can directly pass it to the method." }, { "code": null, "e": 7610, "s": 7452, "text": "But in all the three cases, you can pass an anonymous inner class to the method. Here is the syntax of passing an anonymous inner class as a method argument." }, { "code": null, "e": 7696, "s": 7610, "text": "obj.my_Method(new My_Class() {\n public void Do() {\n .....\n .....\n }\n});" }, { "code": null, "e": 7783, "s": 7696, "text": "The following program shows how to pass an anonymous inner class as a method argument." }, { "code": null, "e": 7794, "s": 7783, "text": " Live Demo" }, { "code": null, "e": 8382, "s": 7794, "text": "// interface\ninterface Message {\n String greet();\n}\npublic class My_class {\n // method which accepts the object of interface Message\n public void displayMessage(Message m) {\n System.out.println(m.greet() + \", This is an example of anonymous inner class as an argument\");\n }\n public static void main(String args[]) {\n // Instantiating the class\n My_class obj = new My_class();\n // Passing an anonymous inner class as an argument\n obj.displayMessage(new Message() {\n public String greet() {\n return \"Hello\";\n }\n });\n }\n}" }, { "code": null, "e": 8463, "s": 8382, "text": "If you compile and execute the above program, it gives you the following result." }, { "code": null, "e": 8529, "s": 8463, "text": "Hello, This is an example of anonymous inner class as an argument" } ]
Spring Security - Quick Guide
Introduction and Overview Basic components of Spring Security AuthenticationFilter AuthenticationManager AuthenticationProvider UserDetailsService PasswordEncoder Spring Security Context Form Login Login with a Database Login Attempts Limit AuthenticationFilter AuthenticationManager AuthenticationProvider UserDetailsService PasswordEncoder Spring Security Context Form Login Login with a Database Login Attempts Limit Getting Started (Practical Guide) In addition to providing various inbuilt authentication and authorization options, Spring Security allows us to customize our authentication process as much as we want. Starting from a custom login page to our very own customized authentication providers and authentication filters, we can pretty much customize every aspect of the authentication process. We can define our own authentication process which can range from basic authentication using a username and a password to a complex one such as two-factor authentication using tokens and OTP’s. Also, we can use various databases – both relational and non-relational, use various password encoders, lock malicious users out of their accounts, and so on. Today, we are going to discuss three such customizations, namely – custom form-login, a database provided authentication, and limiting login attempts. Though these are pretty basic use-cases, yet these still will let us have a closer look into Spring Security’s authentication and authorization process. We are also going to set up a registration page through which the users will be able to register themselves with our application. First of all, let’s take a look at the architecture of Spring Security. It starts with servlet filters. These filters intercept requests, perform operations on them, and then pass the requests on to next filters in the filter chain or request handlers or block them if they do not meet certain conditions. It is during this process that Spring Security can authenticate requests and perform various authentication checks on the requests. It can also prevent unauthenticated or malicious requests from accessing our protected resources by not allowing them to pass through. Thus our application and resources stay protected. The basic components of Spring Security, as we can see in the above diagram are given below. We shall discuss them briefly as we go along. We shall also discuss their roles in the authentication and authorization process. This is the filter that intercepts requests and attempts to authenticate it. In Spring Security, it converts the request to an Authentication Object and delegates the authentication to the AuthenticationManager. It is the main strategy interface for authentication. It uses the lone method authenticate() to authenticate the request. The authenticate() method performs the authentication and returns an Authentication Object on successful authentication or throw an AuthenticationException in case of authentication failure. If the method can’t decide, it will return null. The process of authentication in this process is delegated to the AuthenticationProvider which we will discuss next. The AuthenticationManager is implemented by the ProviderManager which delegates the process to one or more AuthenticationProvider instances. Any class implementing the AuthenticationProvider interface must implement the two methods – authenticate() and supports(). First, let us talk about the supports() method. It is used to check if the particular authentication type is supported by our AuthenticationProvider implementation class. If it is supported it returns true or else false. Next, the authenticate() method. Here is where the authentication occurs. If the authentication type is supported, the process of authentication is started. Here is this class can use the loadUserByUsername() method of the UserDetailsService implementation. If the user is not found, it can throw a UsernameNotFoundException. On the other hand, if the user is found, then the authentication details of the user are used to authenticate the user. For example, in the basic authentication scenario, the password provided by the user may be checked with the password in the database. If they are found to match with each other, it is a success scenario. Then we can return an Authentication object from this method which will be stored in the Security Context, which we will discuss later. It is one of the core interfaces of Spring Security. The authentication of any request mostly depends on the implementation of the UserDetailsService interface. It is most commonly used in database backed authentication to retrieve user data. The data is retrieved with the implementation of the lone loadUserByUsername() method where we can provide our logic to fetch the user details for a user. The method will throw a UsernameNotFoundException if the user is not found. Until Spring Security 4, the use of PasswordEncoder was optional. The user could store plain text passwords using in-memory authentication. But Spring Security 5 has mandated the use of PasswordEncoder to store passwords. This encodes the user’s password using one its many implementations. The most common of its implementations is the BCryptPasswordEncoder. Also, we can use an instance of the NoOpPasswordEncoder for our development purposes. It will allow passwords to be stored in plain text. But it is not supposed to be used for production or real-world applications. This is where the details of the currently authenticated user are stored on successful authentication. The authentication object is then available throughout the application for the session. So, if we need the username or any other user details, we need to get the SecurityContext first. This is done with the SecurityContextHolder, a helper class, which provides access to the security context. We can use the setAuthentication() and getAuthentication() methods for storing and retrieving the user details respectively. Moving on, let’s now discuss the three custom implementations we are going to use for our application. When we add Spring Security to an existing Spring application it adds a login form and sets up a dummy user. This is Spring Security in auto-configuration mode. In this mode, it also sets up the default filters, authentication-managers, authentication-providers, and so on. This setup is an in-memory authentication setup. We can override this auto-configuration to set up our own users and authentication process. We can also set up our custom login method like a custom login form. Spring Security only has to made aware of the details of the login form like – the URI of the login form, the login processing URL, etc.. It will then render our login form for the application and carry out the process of authentication along with the other provided configurations or Spring’s own implementation. This custom form setup will only have to abide by certain rules to be integrated with Spring Security. We need to have a username parameter and a password parameter and the parameter names should be “username” and “password” since those are the default names. In case, we use our own parameter names for these fields in the custom we have to inform Spring Security of those changes using the usernameParameter() and passwordParameter() methods. Similarly, for every change we do to the login form or the form login method, we will have to inform Spring Security of those changes with appropriate methods so that it can integrate them with the authentication process. As we discussed, Spring Security automatically provides an in-memory authentication implementation by default. We can override this by authenticating users whose details are stored in a database. In this case, while authenticating a user, we can verify the credentials provided by the user against those in the database for authentication. We can also let new users register in our application and store their credentials in the same database. Also, we can provide methods to change or update their passwords or roles or other data. As a result, this provides us with persistent user data which can be used for longer periods of time. To limit login attempts in our application we can use Spring Security’s isAccountNonLocked property. Spring Security’s UserDetails provides us with that property. We can set up an authentication method wherein, if any user or someone else provides incorrect credentials for more than a certain number of times, we can lock their account. Spring Security disables authentication for a locked user even if the user provides correct credentials. This is an in-built feature provided by Spring Security. We can store the number of incorrect login attempts in our database. Then against each incorrect authentication attempt, we can update and check with the database table. When the number of such attempts exceeds a given number, we can lock the user out of their account. Consequently, the user will not be able to log in again until their account is unlocked. Let’s start with our application now. The tools we will be needing for this application are listed below − A Java IDE − preferable STS 4, but Eclipse, IntelliJ Idea or any other IDE will do. A Java IDE − preferable STS 4, but Eclipse, IntelliJ Idea or any other IDE will do. MySql Server Community Edition − We need to download and install MySql Community Server in our system. We can go to the official website by clicking here. MySql Server Community Edition − We need to download and install MySql Community Server in our system. We can go to the official website by clicking here. MySql Workbench − It is a GUI tool that we can use to interact with MySql databases. MySql Workbench − It is a GUI tool that we can use to interact with MySql databases. Let’s set up the database first. We will use a MySql database instance for this application. MySql Server Community Edition is available for free download and use. We will use MySql Workbench to connect with our MySql Server and create a database called “spring” to use with our application. Then we will create two tables – users and attempts– to persist our users and login attempts. As mentioned earlier, the details of the users registering with our application will be stored in the users table. The number of login attempts by any user will be stored in the attempts table against his username. This way we can track the attempts and take necessary action. Let’s take a the look at the SQL to setup our users table and attempts table. CREATE TABLE users ( username VARCHAR(45) NOT NULL , password VARCHAR(45) NOT NULL , account_non_locked TINYINT NOT NULL DEFAULT 1 , PRIMARY KEY (username) ); CREATE TABLE attempts ( id int(45) NOT NULL AUTO_INCREMENT, username varchar(45) NOT NULL, attempts varchar(45) NOT NULL, PRIMARY KEY (id) ); We can now add a dummy user to our application. INSERT INTO users(username,password,account_non_locked) VALUES ('user','12345', true); As usual, we will use the Spring Initializer to setup our project. We are going to create a Maven project, with Spring Boot version 2.3.2. Let’s name our project formlogin(we can choose any name we want) and group id as com.tutorial.spring.security. Furthermore, we will use Java version 8 for this project. Now, coming to the dependencies, we are going to keep our application as simple as possible for this demo. We will keep our focus on the features we want to explore today. So we will choose the minimum number of dependencies that will help us set up our application and get it up and running quickly. Let’s go through the dependencies − Spring Web − It bundles all dependencies related to web development including Spring MVC, REST, and an embedded Tomcat Server. Spring Web − It bundles all dependencies related to web development including Spring MVC, REST, and an embedded Tomcat Server. Spring Security − For the implementation of security features provided by Spring Security. Spring Security − For the implementation of security features provided by Spring Security. Thymeleaf − A server-side Java template engine for HTML5/XHTML/XML. Thymeleaf − A server-side Java template engine for HTML5/XHTML/XML. Spring Data JPA − In addition to using all features defined by JPA specification, Spring Data JPA adds its own features such as the no-code implementation of the repository pattern and the creation of database queries from the method name. Spring Data JPA − In addition to using all features defined by JPA specification, Spring Data JPA adds its own features such as the no-code implementation of the repository pattern and the creation of database queries from the method name. Mysql Driver − For the MySQL database driver. Mysql Driver − For the MySQL database driver. With these five dependencies, we can set up our project now. Let’s click on the generate button. This will download our project as a zip file. We can extract it to a folder of our choice. Then we open the project in our IDE. We will be using Spring Tool Suite 4 for this. example. Let’s load our project into STS. It will take a little time for our IDE to download the dependencies and validating them. Let’s take a look at our pom.xml file. pom.xml <?xml version="1.0" encoding="ISO-8859-1"?> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.tutorial.spring.security</groupId> <artifactId>formlogin</artifactId> <version>0.0.1-SNAPSHOT</version> <name>formlogin</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime<scope> <optional>true</optional> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test<artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> We can see that our project details along with our dependencies are enlisted here. We will configure our data source in the application.properties file. As we will be using our local MySQL DB as the data source, so we provide the url, username, and password of our local DB instance here. We have named our database as “spring”. spring.datasource.url=jdbc:mysql://localhost:3306/spring spring.datasource.username=root spring.datasource.password=root Let’s create our entities now. We start with the User entity which contains three fields – username, password, and accountNonLocked. This User class also implements the UserDetails interface of Spring Security. This class provides core user information. It is used to store user data which can be later encapsulated into Authentication objects. It is not recommended to implement the interface directly. But for our case, since this is a simple application to demonstrate the login with a database, we have implemented this interface directly here to keep thingssimple. We can implement this interface by using a wrapper class around our User entity. User.java package com.tutorial.spring.security.formlogin.model; import java.util.Collection; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; @Entity @Table(name = "users") public class User implements UserDetails { /** * */ private static final long serialVersionUID = 1L; @Id private String username; private String password; @Column(name = "account_non_locked") private boolean accountNonLocked; public User() { } public User(String username, String password, boolean accountNonLocked) { this.username = username; this.password = password; this.accountNonLocked = accountNonLocked; } @Override public Collection< extends GrantedAuthority> getAuthorities() { return List.of(() -> "read"); } @Override public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return accountNonLocked; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } public void setAccountNonLocked(Boolean accountNonLocked) { this.accountNonLocked = accountNonLocked; } public boolean getAccountNonLocked() { return accountNonLocked; } } The accountNonLocked field is to be noted here. Every User in Spring Security has the account unlocked by default. To override that property and to lock the users out of their accounts once they exceed the permissible number of attempts, we shall be using this property. If the user exceeds the number of invalid attempts permissible, we shall use this property to lock him out of his account. Also, during every authentication attempt, we shall be checking this property with the isAccountNonLocked() method along with the credentials to authenticate the user. Any user with a locked account will not be allowed to authenticate into the application. For the other methods of the UserDetails interface, we can simply provide an implementation that returns true for now as we shall not be exploring these properties for this application. For the list of authorities for this user, let’s assign him a dummy role for now. We shall not be using this property either for this application. Attempts.java Moving on, let’s create our Attempts entity to persist our invalid attempts count. As created in the database, we will have the three fields here – username, an integer named attempts to keep counts of the number of attempts, and an identifier. package com.tutorial.spring.security.formlogin.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Attempts { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String username; private int attempts; /** * @return the id */ public int getId() { return id; } /** * @param id the id to set */ public void setId(int id) { this.id = id; } /** * @return the username */ public String getUsername() { return username; } /** * @param username the username to set */ public void setUsername(String username) { this.username = username; } /** * @return the attempts */ public int getAttempts() { return attempts; } /** * @param attempts the attempts to set */ public void setAttempts(int attempts) { this.attempts = attempts; } } We have created the entities, let’s create the repositories to store and retrieve data. We will have two repositories, one for each entity class. For both the repository interfaces, we will extend the JpaRepository which provides us with in-built implementations to save and retrieve data from the database configured in our application.properties file. We can also add our methods or queries here in addition to the provided ones. UserRepository.java package com.tutorial.spring.security.formlogin.repository; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.tutorial.spring.security.formlogin.model.User; @Repository public interface UserRepository extends JpaRepository<User, String> { Optional<User> findUserByUsername(String username); } As discussed, we have added our method to retrieve a user by username here. This will return our user details including username, password and account locked status. AttemptsRepository.java package com.tutorial.spring.security.formlogin.repository; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.tutorial.spring.security.formlogin.model.Attempts; @Repository public interface AttemptsRepository extends JpaRepository<Attempts, Integer> { Optional<Attempts> findAttemptsByUsername(String username); } Similarly, for the Attempts, in our AttemptsRepository, we have added a custom method findAttemptsByUsername(String username) to get data about user attempts using the username. This will return us an Attempts object with the username and the number of failed authentication attempts the user has made. Since we are going to use a custom login form, we have to override the default configuration of Spring Security. To do this we create our configuration class which extends the WebSecurityConfigurerAdapter class of Spring Security. package com.tutorial.spring.security.formlogin.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration public class ApplicationConfig extends WebSecurityConfigurerAdapter { @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests().antMatchers("/register**") .permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .invalidateHttpSession(true) .clearAuthentication(true) .permitAll(); } } Here we did two things− First, we have specified the implementation of the PasswordEncoder interface that we are going to use. We have used an instance of BCryptPasswordEncoder to encode our passwords for this example. The PasswordEncoder interface has many implementations and we can use any of them. We have chosen BCryptPasswordEncoder here as it the most commonly used implementation. It uses the very strong BCrypt hashing algorithm to encode the passwords. It does so by incorporating a salt to protect against rainbow table attacks. In addition to this, bcrypt is an adaptive function: over time, the iteration count can be increased to make it slower, so it remains resistant to brute-force search attacks even with increasing computation power. Secondly, we have overridden the configure() method to provide our implementation of the login method. Whenever we use a custom form for authentication in place of the one provided by Spring Security, we have to inform Spring Security of it using the formLogin() method. We then also specify our login URL – /login. We will map the URL to our custom login page in our Controller later. We have also specified that the endpoints starting with /register, /login and the logout page need not be protected. We did so using the permitAll() method. This allows everyone to access these endpoints. Other than these endpoints, all endpoints are to be authenticated(). That is to say, users must be logged in to access all the other endpoints. On logout, we have specified that the session is to be invalidated and authentication stored in the application’s SecurityContext be cleared. Now, we will setup our authentication process. We are going to setup authentication using a database and locking of user accounts. Let’s create our implementation of UserDetailsService first. As we have discussed before, we need to provide our custom implementation for authentication using a database. This is because, Spring Security, as we know, only provides an in-memory authentication implementation by default. Therefore, we need to override that implementation with our database based process. To do so, we need to override the loadUserByUsername() method of UserDetailsService. package com.tutorial.spring.security.formlogin.security; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.provisioning.UserDetailsManager; import org.springframework.stereotype.Service; import com.tutorial.spring.security.formlogin.model.User; import com.tutorial.spring.security.formlogin.repository.UserRepository; @Service public class SecurityUserDetailsService implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findUserByUsername(username) .orElseThrow(() -< new UsernameNotFoundException("User not present")); return user; } public void createUser(UserDetails user) { userRepository.save((User) user); } } As we can see here, we have implemented the loadUserByUsername() method here. Here we are fetching the user from our database using the UserRepository interface. If the user is not found it throws UsernameNotFoundException. We also have a createUser() method. We will use this method to add users to our database who have registered in our application using UserRepository. We will now implement our custom authentication provider. It will implement the AuthenticationProvider interface. We have two methods here that we have to override and implement. package com.tutorial.spring.security.formlogin.security; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.LockedException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; import com.tutorial.spring.security.formlogin.model.Attempts; import com.tutorial.spring.security.formlogin.model.User; import com.tutorial.spring.security.formlogin.repository.AttemptsRepository; import com.tutorial.spring.security.formlogin.repository.UserRepository; @Component public class AuthProvider implements AuthenticationProvider { private static final int ATTEMPTS_LIMIT = 3; @Autowired private SecurityUserDetailsService userDetailsService; @Autowired private PasswordEncoder passwordEncoder; @Autowired private AttemptsRepository attemptsRepository; @Autowired private UserRepository userRepository; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getName(); import com.tutorial.spring.security.formlogin.repository.UserRepository; @Component public class AuthProvider implements AuthenticationProvider { private static final int ATTEMPTS_LIMIT = 3; @Autowired private SecurityUserDetailsService userDetailsService; @Autowired private PasswordEncoder passwordEncoder; @Autowired private AttemptsRepository attemptsRepository; @Autowired private UserRepository userRepository; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getName(); Optional<Attempts> userAttempts = attemptsRepository.findAttemptsByUsername(username); if (userAttempts.isPresent()) { Attempts attempts = userAttempts.get(); attempts.setAttempts(0); attemptsRepository.save(attempts); } } private void processFailedAttempts(String username, User user) { Optional<Attempts> userAttempts = attemptsRepository.findAttemptsByUsername(username); if (userAttempts.isEmpty()) { Attempts attempts = new Attempts(); attempts.setUsername(username); attempts.setAttempts(1); attemptsRepository.save(attempts); } else { Attempts attempts = userAttempts.get(); attempts.setAttempts(attempts.getAttempts() + 1); attemptsRepository.save(attempts); if (attempts.getAttempts() + 1 > ATTEMPTS_LIMIT) { user.setAccountNonLocked(false); userRepository.save(user); throw new LockedException("Too many invalid attempts. Account is locked!!"); } } } @Override public boolean supports(Class<?> authentication) { return true; } } authenticate() − This method returns a fully authenticated object including credentials on successful authentication. This object is then stored in the SecurityContext. To perform authentication we will use the loaduserByUsername() method of the SecurityUserDetailsService class of our Application. Here we perform multiple things − First, we extract the user credentials from the Authentication request object which is passed as a parameter to our function. This authentication object was prepared by the AuthenticationFilter class and passed down the AuthenticationProvider through the AuthenticationManager. We also fetch the user details from the database using the loadUserByUsername() method. Now, first, we check if the user account has been locked due to previous failed authentication attempts. If we find that the account is locked, we throw a LockedException, and the user will be unable to authenticate unless the account is unlocked again. If the account is not locked, we match the provided password along with the one stored against the user in the database. This is done using the matches() method of the PasswordEncoder interface. If the passwords match, and the account has not been locked by then, we return a fully authenticated object. Here we have used an instance UsernamePasswordAuthenticationToken class (as it is a username-password authentication) that implements Authentication. Meanwhile, we also reset the attempts counter to 0. On the other hand, if the password doesn’t match, we check for a few conditions − If it is the user’s first attempt, then, probably his name would not be in the database. We check for this using the method findAttemptsByUsername() from the AttemptsRepository. If not found, we make an entry for the user in the database, with the number of attempts set to one. If a user is found, then we increase the number of attempts by 1. We then check against the maximum number of failed attempts allowed, using a constant value we defined earlier. If the number is more than the allowed number of attempts, then the user is locked our of the application and a LockedException is thrown. supports() − We also have the supports method that checks if our authentication type is supported by our AuthenticationProvider implementation class. It returns true, false, or null if it matches, doesn’t match, or if it can’t decide respectively. We have hardcoded it to be true for now. Now let’s create our controller package. It will contain our HelloController class. Using this controller class we will map our views to the endpoints and serve those views when the respective endpoints are hit. We will also autowire the PasswordEncoder and the UserDetailsService classes in this component. These injected dependencies will be used in creating our user. Let’s now create our endpoints. package com.tutorial.spring.security.formlogin.controller; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.LockedException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import com.tutorial.spring.security.formlogin.model.User; import com.tutorial.spring.security.formlogin.security.SecurityUserDetailsService; @Controller public class HelloController { @Autowired private SecurityUserDetailsService userDetailsManager; @Autowired private PasswordEncoder passwordEncoder; @GetMapping("/") public String index() { return "index"; } @GetMapping("/login") public String login(HttpServletRequest request, HttpSession session) { session.setAttribute( "error", getErrorMessage(request, "SPRING_SECURITY_LAST_EXCEPTION") ); return "login"; } @GetMapping("/register") public String register() { return "register"; } @PostMapping( value = "/register", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = { MediaType.APPLICATION_ATOM_XML_VALUE, MediaType.APPLICATION_JSON_VALUE } ) public void addUser(@RequestParam Map<String, String> body) { User user = new User(); user.setUsername(body.get("username")); user.setPassword(passwordEncoder.encode(body.get("password"))); user.setAccountNonLocked(true); userDetailsManager.createUser(user); } private String getErrorMessage(HttpServletRequest request, String key) { Exception exception = (Exception) request.getSession().getAttribute(key); String error = ""; if (exception instanceof BadCredentialsException) { error = "Invalid username and password!"; } else if (exception instanceof LockedException) { error = exception.getMessage(); } else { error = "Invalid username and password!"; } return error; } } index ("/") – This endpoint will serve the index page of our application. As we have configured earlier, we shall be protecting this page and allow only authenticated users will be able to access this page. login ("/login") – This will be used to serve our custom login page, as mentioned earlier. Any unauthenticated user will be redirected to this endpoint for authentication. register("/register") (GET) – We will have two “register” endpoints for our application. One will be to serve the registration page. The other one will be to handle the registration process. So, the former one will use an Http GET and the latter will be a POST endpoint. register("/register") (POST) – We will use this endpoint to handle the user registration process. We will get the user name and password from the parameters. Then we will encode the password using the passwordEncoder that we have @Autowired into this component. We also set user account as unlocked at this point. We will then save this user data in our users table with the createUser() method. In addition to the above, we have the getErrorMessage() method. It is used to determine the last thrown exception to add a message in our login template. This way, we can be aware of authentication errors and display proper messages. We have created our endpoints, the only thing left is to create our views. First, we will create our index page. This page will be accessible to users only on successful authentication. This page has access to the Servlet request object using which we can display the user name of the logged in user. <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <title> Hello World! </title> </head> <body> <h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1> <form th:action="@{/logout}" method="post"> <input type="submit" value="Sign Out"/> </form> </body> <html> Next, we create our login view. This display our custom login form with the username and password fields. This view will also be rendered in case of a logout or failed authentication and will display appropriate messages for each case. <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <title>Spring Security Example</title> </head> <body> <div th:if="${param.error}"> <p th:text="${session.error}" th:unless="${session == null}">[...]</p> </div> <div th:if="${param.logout}">You have been logged out.</div> <form th:action="@{/login}" method="post> <div> <label> User Name : <input type="text" name="username" /> </label> </div> <div> <label> Password: <input type="password" name="password" /> </label> </div> <div> <input type="submit" value="Sign In" /> </div> </form> </body> </html> Moving, we create our required view, the register view. This view will let users register themselves with the application. This user data will be stored in the database which will then be used for authentication. <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <form action="/register" method="post"> <div class="container"> <h1>Register</h1> <p>Please fill in this form to create an account.</p> <hr> <label for="username"> <b>Username</b> </label> <input type="text" placeholder="Enter Username" name="username" id="username" required> <label for="password"><b>Password</b></label> <input type="password" placeholder="Enter Password" name="password" id="password" required> <button type="submit" class="registerbtn">Register</button> </div> </form> </body> </html> Our final project structure should look something similar to this. Running the Application We can then run the application as a SpringBootApp. When we go localhost:8080 on our browser it will redirect us back to the login page. On successful authentication it will take us the index view with a greeting. Since, we have allowed only three failed attempts before the account gets locked, so on the third failed authentication the user get locked and the message is displayed on the screen. On hitting the /register endpoint we can also register a new user. Conclusion From today’s article, we have learned how to use a custom form for login using a database using an annotation-based configuration. We have also learned how to prevent multiple failed login attempts. While doing we have seen how we can implement our own AuthenticationProvider and UserDetailsService to authenticate users using our custom authentication process. Introduction and Overview Getting Started (Practical Guide) Spring Security comes with a ton of built-in features and tools for our convenience. In this example, we are going to discuss three of those interesting and useful features − Form-login Remember Me Logout Form-based login is one form of Username/password authentication that Spring Security provides support for. This is provided through an Html form. Whenever a user requests a protected resource, Spring Security checks for the authentication of the request. If the request is not authenticated/authorized, the user will be redirected to the login page. The login page must be somehow rendered by the application. Spring Security provides that login form by default. Moreover, any other configuration, if needed, must be explicitly provided as given below − protected void configure(HttpSecurity http) throws Exception { http // ... .formLogin( form -> form .loginPage("/login") .permitAll() ); } This code requires a login.html file to be present in the templates folder which would be returned on hitting the /login. This HTML file should contain a login form. Furthermore, the request should be a post request to /login. The parameter names should be “username” and “password” for username and password respectively. In addition to this, a CSRF Token also needs to be included with the form. The above code snippet will be clearer once we are done with code exercise. This type of authentication requires a remember-me cookie to be sent to the browser. This cookie stores user information/authentication principal and it is stored in the browser. So, the website can remember the identity of the user next time when the session is started. Spring Security has the necessary implementations in place for this operation. One uses hashing to preserve the security of cookie-based tokens while the other uses a database or other persistent storage mechanism to store the generated tokens. The default URL /logout logs the user out by− Invalidating the HTTP Session Cleaning up any RememberMe authentication that was configured Clearing the SecurityContextHolder Redirect to /login?logout WebSecurityConfigurerAdapter automatically applies logout capabilities to the Spring Boot application. Getting Started (Practical Guide) As usual, we shall start by going to start.spring.io. Here we choose a maven project. We name the project “formlogin” and choose the desired Java version. I am choosing Java 8 for this example. We also go on to add the following dependencies − Spring Web Spring Security Thymeleaf Spring Boot DevTools Thymeleaf is a templating engine for Java. It allows us to quickly develop static or dynamic web pages for rendering in the browser. It is extremely extensible and allows us to define and customize the processing of our templates in fine detail. In addition to this, we can learn more about Thymeleaf by clicking this link. Let’s move on to generate our project and download it. We then extract it to a folder of our choice and use any IDE to open it. I shall be using Spring Tools Suite 4. It is available for free downloading from the https://spring.io/tools website and is optimized for spring applications. Let’s take a look at our pom.xml file. It should look something similar to this − <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.1.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <groupId> com.spring.security</groupId> <artifactId>formlogin</artifactId> <version>0.0.1-SNAPSHOT</version> <name>formlogin</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Let’s create a package in our folder /src/main/java under the default package. We shall be naming it as config as we would place all our configuration classes here. So, the name should look something similar to this – com.tutorial.spring.security.formlogin.config. package com.tutorial.spring.security.formlogin.config; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.provisioning.UserDetailsManager; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import com.spring.security.formlogin.AuthFilter; @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Bean protected UserDetailsService userDetailsService() { UserDetailsManager userDetailsManager = new InMemoryUserDetailsManager(); UserDetails user = User.withUsername("abby") .password(passwordEncoder().encode("12345")) .authorities("read") .build(); userDetailsManager.createUser(user); return userDetailsManager; } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); }; @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests().anyRequest() .authenticated() .and() .formLogin() .and() .rememberMe() .and() .logout() .logoutUrl("/logout") .logoutSuccessUrl("/login") .deleteCookies("remember-me"); } } Inside of our config package, we have created the WebSecurityConfig class. This class extends the WebSecurityConfigurerAdapter of Spring Security. We shall be using this class for our security configurations, so let’s annotate it with an @Configuration annotation. As a result, Spring Security knows to treat this class a configuration class. As we can see, configuring applications have been made very easy by Spring. Let’s take a look at our configuration class. First, we shall create a bean of our UserDetailsService class by using the userDetailsService() method. We shall be using this bean for managing our users for this application. Here, to keep things simple, we shall use an InMemoryUserDetailsManager instance to create a user. This user, along with our given username and password, will contain a simple “read” authority. Now, let’s look at our PasswordEncoder. We shall be using a BCryptPasswordEncoder instance for this example. Hence, while creating the user, we used the passwordEncoder to encode our plaintext password like this .password(passwordEncoder().encode("12345")) After the above steps, we move on to our next configuration. Here, we override the configure method of WebSecurityConfigurerAdapter class. This method takes HttpSecurity as a parameter. We shall be configuring this to use our form login and logout, as well as a remember-me function. Http Security Configuration We can observe that all these functionalities are available in Spring Security. Let’s study the below section in detail − http.csrf().disable() .authorizeRequests().anyRequest().authenticated() .and() .formLogin() .and() .rememberMe() .and() .logout() .logoutUrl("/logout") .logoutSuccessUrl("/login") .deleteCookies("remember-me"); There are a few points to note here − We have disabled csrf or Cross-Site Request Forgery protection As this is a simple application only for demonstration purposes, we can safely disable this for now. Then we add configuration which requires all requests to be authenticated. As we shall see later, we will have a single “/” endpoint for the index page of this application, for simplicity. After that, we shall be using the formLogin() functionality of Spring Security as mentioned above. This generates a simple login page. Then, we use the rememberMe() functionality of Spring Security. This will perform two things. Firstly, it will add a “Remember Me” checkbox to our default login form that we generated using formLogin(). And, secondly, ticking the checkbox generates the remember-me cookie. The cookie stores the identity of the user and the browser stores it. Spring Security detects the cookie in future sessions to automate the login. As a result, the user can access the application again without logging in again. And lastly, we have the logout() functionality. For this too, a default functionality has been provided by Spring security. Here it performs two important functions − Invalidates the Http session, and unbinds objects bound to the session. It clears the remember-me cookie. Removes the authentication from Spring’s Security context. We also, provided a logoutSuccessUrl(), so that the application comes back to the login page after logout. This completes our application configuration. We shall now create a dummy index page now for the user to view when he logs in. It will also contain a logout button. In our /src/main/resources/templates, we add a index.html file.Then add some Html content to it. <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <title>Hello, world!</title> </head> <body> <h1>Hello, world!</h1> <a href="logout">logout</a> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> </body> </html> This content is from Bootstrap 4 getting started template. We also add <a href="logout">logout</a> to our file, so as the user can log out of the application using this link. The Resource Controller We have created the protected resource, we now add the controller to serve this resource. package com.tutorial.spring.security.formlogin.controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class AuthController { @GetMapping("/") public String home() { return "index"; } } As we can see, it is a very simple controller. It only has a get endpoint which serves our index.html file when the start our application. Let’s run the application as a Spring Boot Application. We can go to http://localhost:8080 on our browser when the application starts. It should ask us for username and password. Additionally, we shall also be able to see the remember-me checkbox. Now, if we provide the user information as we had configured in our WebSecurity config file, we shall be able to log in. Also, if we tick the remember-me checkbox, we shall be able to see the remember-me cookie in our browser’s developer tools section. As we can see the cookie is sent along with our login request. Also, included in the web page is a link for log out. On clicking the link, we shall be logged out of our application and sent back to our login page. Introduction and Overview Spring Security Tags The authorize Tag The authentication tag The csrfInput Tag The csrfMetaTags Tag Getting Started (Practical Guide) In Spring MVC applications using JSP, we can use the Spring Security tags for applying security constraints as well as for accessing security information. Spring Security Tag library provides basic support for such operations. Using such tags, we can control the information displayed to the user based on his roles or permissions. Also, we can include CSRF protection features in our forms. To use Spring security tags, we must have the security taglib declared in our JSP file. <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> Now, we can use Spring Security tags with the “sec” prefix. Let’s now see the usage of the tags. The authorize Tag The first tag we will be discussing is the authorize tag. Let’s check out some usage examples. <sec:authorize access="!isAuthenticated()"> Login </sec:authorize> <sec:authorize access="isAuthenticated()"> Logout </sec:authorize> <sec:authorize access="hasRole('ADMIN')"> Hello Admin. </sec:authorize> As we can see, we can use this tag to hide or show sections of information based on access or roles. To evaluate roles or access we also use the following Spring Security Expressions − hasRole(“ADMIN”) − evaluates to true if the current user has the admin role. hasRole(“ADMIN”) − evaluates to true if the current user has the admin role. hasAnyRole(‘ADMIN’,’USER’) − evaluates to true if the current user has any of the listed roles hasAnyRole(‘ADMIN’,’USER’) − evaluates to true if the current user has any of the listed roles isAnonymous() − evaluates to true if the current user is an anonymous user isAnonymous() − evaluates to true if the current user is an anonymous user isRememberMe() − evaluates to true if the current user is a remember-me user isRememberMe() − evaluates to true if the current user is a remember-me user isFullyAuthenticated() − evaluates to true if the user is authenticated and is neither anonymous nor a remember-me user isFullyAuthenticated() − evaluates to true if the user is authenticated and is neither anonymous nor a remember-me user As we can see, the access attribute is where the web-security expression is specified. Then, Spring Security evaluates the expression The evaluation is generally delegated to SecurityExpressionHandler<FilterInvocation>, which is defined in the application context. If it returns true, then the user can get access to the information given in that section. If we use the authorize tag with Spring Security ‘s Permission Evaluator, we can also check user permissions as given below − <sec:authorize access="hasPermission(#domain,'read') or hasPermission(#domain,'write')"> This content is visible to users who have read or write permission. </sec:authorize> We can also allow or restrict the user from clicking on certain links within our content. <sec:authorize url="/admin"> This content will only be visible to users who are authorized to send requests to the "/admin" URL. </sec:authorize> The authentication tag When we want access to the current Authentication object stored in the Spring Security Context, we can use the authentication tag. Then we can use it to render properties of the object directly in our JSP page. For example, if we want to render the principal property of the Authentication object in our page, we can do it as follows − <sec:authentication property="principal.username" /> The csrfInput Tag We can use the csrfInput tag to insert a hidden form field with the correct values for the CSRF protection token when CSRF protection is enabled. If CSRF protection is not enabled, this tag outputs nothing. We can place the tag within the HTML <form></form> block along with other input fields. However, we must not place the tag within the <form:form></form:form> block as Spring Security automatically inserts a CSRF form field within those tags and also takes care of Spring forms automatically. <form method="post" action="/do/something"> <sec:csrfInput /> Username:<br /> <input type="text" username="username" /> ... </form> The csrfMetaTags Tag We can use this tag to insert meta tags which contain the CSRF protection token form field and header names and CSRF protection token value. These meta tags can be useful for employing CSRF protection within Javascript in our application. However, this tag only works when we have enabled CSRF protection in our application, otherwise, this tag outputs nothing. <html> <head> <title>CSRF Protection in Javascript</title> <sec:csrfMetaTags /> <script type="text/javascript" language="javascript"> var csrfParam = $("meta[name='_csrf_param']").attr("content"); var csrfToken = $("meta[name='_csrf']").attr("content"); </script> </head> <body> ... </body> </html> Getting Started (Practical Guide) Now that we have discussed the tags, let’s build an application to demonstrate the usage of the tags. We shall be using Spring Tool Suite 4 as our IDE. Additionally, we shall be using the Apache Tomcat server to serve our application. So, let’s get started. Setting up the Application Let’s create a simple Maven Project in STS. We can name our application as taglibsdemo, and package it as a .war file. When we have finished setting up our application it should have a structure similar to this. The pom.xml file We shall add these following dependencies to our application − Spring Web MVC Spring-Security-Web Spring-Security-Core Spring-Security-Taglibs Spring-Security-Config Javax Servlet Api JSTL After adding these dependencies, our pom.xml should look similar to this − <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorial.spring.security</groupId> <artifactId>taglibsdemo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.source>1.8</maven.compiler.source> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>5.0.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>5.0.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-taglibs</artifactId> <version>5.0.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>5.0.4.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project> Let’s create our base package for the application. We can name it com.taglibsdemo. Within the package, let’s create another package for our configuration files. Since, it will be holding the configuration files, we can name it config. ApplicationConfig.java Let’s create our first configuration class ApplicationConfig.java. package com.taglibsdemo.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @EnableWebMvc @Configuration @ComponentScan({ "com.taglibsdemo.controller"} ) public class ApplicationConfig { @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/views/"); viewResolver.setSuffix(".jsp"); return viewResolver; } } Let’s break down the code here − @EnableWebMvc − We use @EnableWebMvc to enable Spring MVC. So, we add this annotation to an @Configuration class to import the Spring MVC configuration from WebMvcConfigurationSupport. WebMvcConfigurationSupport is the main class that provides the configuration for the MVC Java config. Not using this annotation may result in things like content-type and accept header, generally content negotiation not working. @EnableWebMvc registers a RequestMappingHandlerMapping, a RequestMappingHandlerAdapter, and an ExceptionHandlerExceptionResolver among others in support of processing requests with annotated controller methods using annotations such as @RequestMapping , @ExceptionHandler, and others. @Configuration − This annotation indicates that the class declares one or more @Bean methods and may be processed by the Spring IoC container to generate bean definitions and service requests for those beans at runtime. A @Configuration class is typically bootstrapped using either AnnotationConfigApplicationContext or its web-capable variant, AnnotationConfigWebApplicationContext. @ComponentScan − @ComponentScan annotation is used to tell Spring the packages to scan for annotated components. @ComponentScan also used to specify base packages and base package classes using thebasePackageClasses or basePackages attributes of @ComponentScan. InternalResourceViewResolver − To resolve the provided URI to the actual URI in the format prefix + viewname + suffix. setViewClass() − To set the view class that should be used to create views. setPrefix() − To set the prefix that gets prepended to view names when building a URL. setSuffix() − To set the suffix that gets appended to view names when building a URL. WebSecurityConfig.java Next we shall create our WebSecurityConfig class which will extend the familiar WebSecurityConfigurerAdapter class of Spring Security. package com.taglibsdemo.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.User.UserBuilder; @EnableWebSecurity @ComponentScan("com.taglibsdemo") public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @SuppressWarnings("deprecation") @Bean public UserDetailsService userdetailsService() { UserBuilder users = User.withDefaultPasswordEncoder(); InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); manager.createUser(users.username("rony").password("rony123").roles("USER").build()); manager.createUser(users.username("admin").password("admin123").roles("ADMIN").build()); return manager; } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/index", "/").permitAll() .antMatchers("/admin", "/user").authenticated() .and() .formLogin() .and() .logout() .logoutRequestMatcher( new AntPathRequestMatcher("/logout") ); } } Let’s break the code down here − WebSecurityConfigurerAdapter − The abstract class that implements WebSecurityConfigurer WebSecurityConfigurer and allows us to override methods for security configuration. @EnableWebSecurity − It enables Spring to automatically find and apply the @Configuration class to the global WebSecurity. We then create a UserDetailsService Bean using the method to create users using the InMemoryUserDetailsManager instance. We create two users – one with role “USER” and another with role “ADMIN” and add them to Spring Security. After that, we override the configure method with HttpSecurity as a parameter. We make our home page or index page accessible to all and admin page to be accessible when the user is authenticated. Next, we add Spring Security form login and logout. So, with those steps our security configuration is complete. Now, we are ready to move on to the next step. SpringSecurityApplicationInitializer.java Moving on, now we shall create the SpringSecurityApplicationInitializer.java class which extends the AbstractSecurityWebApplicationInitializer class of Spring Security. package com.taglibsdemo.config; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; public class SpringSecurityApplicationInitializer extends AbstractSecurityWebApplicationInitializer { } AbstractSecurityWebApplicationInitializer is an abstract class that implements Spring’s WebApplicationInitializer. So, SpringServletContainerInitializer will initialize the concrete implementations of this class if the classpath contains spring-web module. MvcWebApplicationInitializer.java package com.taglibsdemo.config; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class MvcWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class</?>[] getRootConfigClasses() { return new Class[] {WebSecurityConfig.class}; } @Override protected Class</?>[] getServletConfigClasses() { return null; } @Override protected String[] getServletMappings() { return new String[] {"/"}; } } AbstractAnnotationConfigDispatcherServletInitializer − This class extends WebApplicationInitializer. We need this class as a base class for initializing a Spring application in Servlet container environment.As a result, the subclass of AbstractAnnotationConfigDispatcherServletInitializer will provide the classes annotated with @Configuration, Servlet config classes and DispatcherServlet mapping pattern. getRootConfigClasses() − This method must be implemented by the class extending AbstractAnnotationConfigDispatcherServletInitializer. It provides “root” application context configuration. getServletConfigClasses() − This method too, must be implemented to provide DispatcherServlet application context configuration. getServletMappings() − This method is used specify the servlet mapping(s) for the DispatcherServlet. We have set up the configuration classes. Now , we shall create our controller to serve the JSP pages. HelloController.java package com.taglibsdemo.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class HelloController { @GetMapping("/") public String index() { return "index"; } @GetMapping("/user") public String user() { return "admin"; } @GetMapping("/admin") public String admin() { return "admin"; } } Here, we have created three endpoints – “/”, “/user”, and “/admin”. As specified in our configuration previously, we will allow unauthorized access to the index page “/”. On the other hand, the “/user” and “/admin” endpoints would be authorized only access. Secure Content to serve Moving on, we shall now create the JSP pages which are to be served on hitting the specific endpoints. For this, inside our src/main folder we create a folder called webapp. Inside this folder, we create our WEB-INF folder and further as in ApplicationConfig.java class we add the views folder. Here, in this folder we shall be adding the views. Let’s add our home page, i.e., index.jsp first. <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Home Page</title> </head> <body> <a href="user">User</a> <a href="admin">Admin</a> <br> <br> Welcome to the Application! </body> </html> Then we shall create our admin.jsp file. Let’s add it. <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="http://www.springframework.org/security/tags" prefix="security"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> Welcome to Admin Page! <a href="logout"> Logout </a> <br> <br> <security:authorize access="hasRole('ADMIN')"> Hello Admin! </security:authorize> </body> </html> here, we have added <%@ taglib uri="http://www.springframework.org/security/tags" prefix="security"%>. This is going to let us the Spring security tag libs as discussed before. As we can see, we have the added the “authorize” tag around the content. This content is will be only accessible by our admin. Any other user accessing this page will not be able to view this content. Running the application We now right click on the project and choose Run On Server. When the server starts and our application is running we can go to localhost:8080/taglibsdemo/ on our browser to view the page. Login page Now, if we click on the User link in our application, we shall be asked to log in. Here, as we can see in our controller, we are serving the admin page for bothe the user and admin links. But our user, if he is not an admin cannot view the content which is protected by our “authorize”tag. Let’s log in as the user first. We can see that the “Hello Admin!” content is not visible to us. This is because the current user doesn’t have the admin role. Let’s logout and log in as admin now. We are now able to see the protected content “Hello Admin!” as the current user has the admin role. Conclusion We have learnt how we can use the Spring Security tag library to protect our content and get access to the current Authentication object in Our Spring Security Context. Fundamentals Getting started (Practical Guide) In this we are going to discuss how to configure Spring Security with XML configuration. We shall be developing a simple Spring application with Spring Security. While doing so, we will discuss in details about each component that we are using. Authentication − Authentication is ensuring the user or the client is who they claim to be. There are many ways in which Spring Security enables us to perform authentication. Spring Security supports Basic Authentication, LDAP authentication, JDBC authentication, etc. Authorization − Ensuring if the user has permission for the action. If our application is a complex one, with different kinds of users such as admins, regular users, other less privileged users, we need to maintain access control in our application. For example, a guest user should not be able to access admin content. So, to control access to various resources within our application, we need to check if a user has permission to access that resource. The above topics are the two main components of Spring Security. Spring security provided us with various in-built features to implement authentication and authorization in our application. We can use these features with our changes to secure an application very quickly. In addition to this, Spring Security also allows plenty of customizations to the features mentioned before to implement our own complex authentications and authorizations. Let’s look at a basic example using in-built Spring Security features. In this example, we shall be securing our application with options provided out-of-box by Spring security. This is will give us an idea of the various components of Spring Security and how we can use them for our application. We shall be using XML to configure our application’s Security features. The tools we shall be using for our application will be Spring Tool Suite 4 and Apache Tomcat Server 9.0. They are both available for free download and use. First, let’s start a new simple Maven Project in STS. We can choose group id, artifact id as per our choice. After that, we click on Finish. As a result, we have added our project to our workspace. Let’s give STS some time to build and validate our project. Our project structure would finally look similar to this. Next, let’s add the dependencies. We are going to choose the following dependencies. Spring Web MVC Spring-Security-Web Spring-Security-Core Spring-Security-Config Javax Servlet API pom.xml With these dependencies added, we are ready to configure our project. Let’s take a look at our pom.xml file. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorial.spring.security</groupId> <artifactId>xmlconfigurationdemo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>Spring Security with XML configuration</name> <description>Spring Security with XML configuration</description> <properties> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.source>1.8</maven.compiler.source> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.2.RELEASE<version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>5.0.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>5.0.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>5.0.0.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project> Controller and views First, We are going to create our controller. So, let’s create a package called controller and add our HomeController class to the package. package com.tutorial.spring.security.xmlconfigurationdemo.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class HomeController { @GetMapping("/") public String index() { return "index"; } @GetMapping("/admin") public String admin() { return "admin"; } } Here, we have two endpoints – “index” and “admin”. While the index page is will be accessible to all, we will protect our “admin” page. Since, we have created the routes, let’s also add the pages. In our /src/main/webapp folder, let’s create a folder called WEB-INF. Then inside it, we will create a folder called views where we will create our views. Let’s create our first view− <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <h2>Welcome to Spring Security!</h2> </body> </html> Then we create our admin view. <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> Hello Admin </body> </html> Moving on, let’s configure our application. Configurations. web.xml Now, let’s add our first xml file – the web.xml file. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE xml> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/app-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/security-config.xml </param-value> </context-param> <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> Code breakdown Dispatcher Servlet − The first servlet we have declared here is the Dispatcher servlet. The dispatcher servlet is the entry point of any Spring MVC application and is at the core of the entire Spring MVC framework design. It intercepts all HTTP requests and dispatches them to registered handlers for processing a web request. It also provides convenient mapping and exception handling facilities. The order in which servlets are loaded depends on “load-on-startup” value. Servlets with a lower value of “load-on-startup” are loaded before the ones with a higher value. contextConfigLocation − It is a string that indicates where context(s) can be found. This string represents a path to a file where our configurations can be loaded. servlet-mapping − We use Servlet Mapping to tell Spring Container which request to route to which servlet. In our case, we are routing all our requests to our “spring” Dispatcher servlet. listener − The classes that listen to certain types of events, and trigger an appropriate functionality when that event occurs. Each listener is bound to an event. In our case, we will create a root web-application context for the web-application with the ContextLoaderListener. This is then put in the ServletContext that can be used to load and unload the spring-managed beans. filter − Spring uses Filters to process requests before handing them over to the Dispatcher Servlet and also used to process responses after they are dispatched. The DelegatingFilterProxy links the application context to the web.xml file. The requests that are coming to this application will pass through our filter which we named “spring SecurityFilterChain” before they reach their controllers. This is where Spring Security can take over the request and perform operations on it before passing it on to the next set of filters or handlers. security-config.xml Next we will create our security-config.xml file. <?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd"> <http auto-config="true"> <intercept-url pattern="/admin" access="hasRole('ROLE_ADMIN')" /> </http> <authentication-manager> <authentication-provider> <user-service> <user name="admin" password="{noop}1234" authorities="ROLE_ADMIN" /> </user-service> </authentication-provider> </authentication-manager> <beans:bean id ="passwordEncoder" class = "org.springframework.security.crypto.password.NoOpPasswordEncoder" factory-method = "getInstance"> </beans:bean> </beans:beans> Code breakdown http element − The parent of all web-related namespace functionality. Here, we can configure which URLs to intercept, what permissions are required, which type of login to use, and all such configuration. auto-config − Setting this attribute to true automatically sets up form-login, basic login, and logout functionalities. Spring Security generates them by using standard values and the features enabled. intercept-url − It sets the pattern of the URLs that we want to protecte, using the access attribute. access − It specifies which users are permitted to access the URL specified by the pattern attribute. It is done on the basis of the roles and permissions of a user. We can use SPEL with this attribute. authentication-manager − The <authentication-manager> is used to configure users, their passwords, and roles in the application. These users will be one who can access the protected parts of the application given they have the appropriate roles. A DaoAuthenticationProvider bean will be created by the <authentication-provider< and the <user-service< element will create an InMemoryDaoImpl. All authentication-provider elements will allow the users to be authenticated by providing the user information to the authentication-manager. password-encoder − This will register a password encoder bean. To keep things simple here we have used the NoOpPasswordEncoder. Moving on we create out last configuration file – the app-config file. Here we are going to add our view resolver code and define our base package. app-config.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <mvc:annotation-driven /> <context:component-scan base-package="com.tutorial.spring.security.xmlconfigurationdemo.controller"> </context:component-scan> <context:annotation-config> </context:annotation-config> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans> Here, as we can see we are registering our views that we created earlier. For this, we are using the InternalResourceViewResolver class which will map the provided URI to the actual URI. For example, using the above configuration, if we request the URI “/admin“, DispatcherServlet will forward the request to the prefix + viewname + suffix = /WEB-INF/views/admin.jsp view. Running the application With this simple configuration, we have our application ready to be served. We can right-click on the project and choose Run on Server. We can choose our Tomcat server. When the server starts, we can go to localhost:8080/xmlconfigurationdemo to interact with our application. If, we enter the correct credentials we shall be able to login and see our desired content. OAuth2.0 Fundamentals OAuth2.0 Getting started(Practical Guide) OAuth 2.0 was developed by IETF OAuth Working Group and published in October of 2012. It serves as an open authorization protocol for enabling a third party application to get limited access to an HTTP service on behalf of the resource owner. It can do so while not revealing the identity or the long-term credentials of the user. A third-party application itself can also use it on its behalf. The working principle of OAuth consists of the delegation of user authentication to a service hosting the user account and authorizing the third-party application access to the account of the user. Let us consider an example. Let us say we want to login to a website “clientsite.com”. We can sign in via Facebook, Github, Google or Microsoft. We select any options of the options given above, and we are redirected to the respective website for login. If login is successful, we are asked if we want to give clientsite.com access to the specific data requested by it. We select our desired option and we are redirected to clientsite.com with an authorization code or error code and our login is successful or not depending on our action in the third-party resource. This is the basic working principle of OAuth 2. There are five key actors involved in an OAuth system. Let’s list them out − User / Resource Owner − The end-user, who is responsible for the authentication and for providing consent to share resources with the client. User / Resource Owner − The end-user, who is responsible for the authentication and for providing consent to share resources with the client. User-Agent − The browser used by the User. User-Agent − The browser used by the User. Client − The application requesting an access token. Client − The application requesting an access token. Authorization Server − The server that is used to authenticate the user/client. It issues access tokens and tracks them throughout their lifetime. Authorization Server − The server that is used to authenticate the user/client. It issues access tokens and tracks them throughout their lifetime. Resource Server − The API that provides access to the requested resource. It validates the access tokens and provides authorization. Resource Server − The API that provides access to the requested resource. It validates the access tokens and provides authorization. We will be developing a Spring Boot Application with Spring Security and OAuth 2.0 to illustrate the above. We will be developing a basic application with an in-memory database to store user credentials now. The application will make it easy for us to understand the workings of OAuth 2.0 with Spring Security. Let’s use the Spring initializer to create a maven project in Java 8. Let’s start by going to start.spring.io. We generate an application with the following dependencies− Spring Web Spring Security Cloud OAuth2 Spring Boot Devtools With the above configuration, we click on the Generate button to generate a project. The project will be downloaded in a zip file. We extract the zip to a folder. We can then open the project in an IDE of our choice. I am using Spring Tools Suite here as it is optimized for spring applications. We can also use Eclipse or IntelliJ Idea as we wish. So, we open the project in STS, let the dependencies get downloaded. Then we can see the project structure in our package explorer window. It should resemble the screenshot below. If we open the pom.xml file we can view the dependencies and other details related to the project. It should look something like this. <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.tutorial</groupId> <artifactId>spring.security.oauth2</artifactId> <version>0.0.1-SNAPSHOT</version> <name>spring.security.oauth2</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> <spring-cloud.version>Hoxton.SR6</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot<groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-oauth2</artifactId> </dependency> <dependency> <groupId>org.springframework.boot<groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> <dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement><build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Now, to the base package of our application, i.e., com.tutorial.spring.security.oauth2, let’s add a new package named config where we shall add our configuration classes. Let’s create our first configuration class, UserConfig which extends the WebSecurityConfigurerAdapter class of Spring Security to manage the users of the client application. We annotate the class with @Configuration annotation to tell Spring that it is a configuration class. package com.tutorial.spring.security.oauth2.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.provisioning.UserDetailsManager; @Configuration public class UserConfig extends WebSecurityConfigurerAdapter { @Bean public UserDetailsService userDetailsService() { UserDetailsManager userDetailsManager = new InMemoryUserDetailsManager(); UserDetails user = User.withUsername("john") .password("12345") .authorities("read") .build(); userDetailsManager.createUser(user); return userDetailsManager; } @Bean public PasswordEncoder passwordEncoder() { return NoOpPasswordEncoder.getInstance(); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } } We then add a bean of the UserDetailsService to retrieve the user details for authentication and authorization. To put it in the Spring context we annotate it with @Bean. To keep this tutorial simple and easy to understand, we use an InMemoryUserDetailsManager instance. For a real-world application, we can use other implementations like JdbcUserDetailsManager to connect to a database and so on. To be able to create users easily for this example we use the UserDetailsManager interface which extends the UserDetailsService and has methods like createUser(), updateUser() and so on. Then, we create a user using the builder class. We give him a username, password and a “read” authority for now. Then, using the createUser() method, we add the newly created user and return the instance of UserDetailsManager thus putting it in the Spring context. To be able to use the UserDetailsService defined by us, it is necessary to provide a PasswordEncoder bean in the Spring context. Again, to keep it simple for now we use the NoOpPasswordEncoder. The NoOpPasswordEncoder should not be used otherwise for real-world applications for production as it is not secure. NoOpPasswordEncoder does not encode the password and is only useful for developing or testing scenarios or proof of concepts. We should always use the other highly secure options provided by Spring Security, the most popular of which is the BCryptPasswordEncoder, which we will be using later in our series of tutorials. To put it in the Spring context we annotate the method with @Bean. We then override the AuthenticationManager bean method of WebSecurityConfigurerAdapter, which returns the authenticationManagerBean to put the authentication manager into the Spring context. Now, to add the client configurations we add a new configuration class named AuthorizationServerConfig which extends AuthorizationServerConfigurerAdapter class of Spring Security. The AuthorizationServerConfigurerAdapter class is used to configure the authorization server using the spring security oauth2 module. We annotate this class with @Configuration as well. To add the authorization server functionality to this class we need to add the @EnableAuthorizationServer annotation so that the application can behave as an authorization server. package com.tutorial.spring.security.oauth2.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("oauthclient1") .secret("oauthsecret1") .scopes("read") .authorizedGrantTypes("password") } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager); } } For checking oauth tokens, Spring Security oauth exposes two endpoints – /oauth/check_token and /oauth/token_key. These endpoints are protected by default behind denyAll(). tokenKeyAccess() and checkTokenAccess() methods open these endpoints for use. We autowire the AuthenticationManager bean we configured in the UserConfig class as a dependency here which we shall be using later. We then override two of the configure() methods of the AuthorizationServerConfigurerAdapter to provide an in-memory implementation of the client details service. The first method which uses the ClientDetailsServiceConfigurer as a parameter, as the name suggests, allows us to configure the clients for the authorization server. These clients represent the applications that will be able to use the functionality of this authorization server. Since this is a basic application for learning the implementation of OAuth2, we will keep things simple for now and use an in-memory implementation with the following attributes − clientId − the id of the client. Required. clientId − the id of the client. Required. secret − the client secret, required for trusted clients secret − the client secret, required for trusted clients scope − the limiting scope of the client, in other words, client permissions. If left empty or undefined, the client is not limited by any scope. scope − the limiting scope of the client, in other words, client permissions. If left empty or undefined, the client is not limited by any scope. authorizedGrantTypes − the grant types that the client is authorized to use. The grant type denotes the way by which the client obtains the token from the authorization server. We will be using the “password” grant type as it is the simplest. Later, we shall be using another grant type for another use-case. authorizedGrantTypes − the grant types that the client is authorized to use. The grant type denotes the way by which the client obtains the token from the authorization server. We will be using the “password” grant type as it is the simplest. Later, we shall be using another grant type for another use-case. In “password” authorization grant type, the user needs to provide his/her username, password and scope to our client application, which then uses those credentials along with its credentials for the authorization server we want the tokens from. The other configure() method that we overrode, uses AuthorizationServerEndpointsConfigurer as a parameter, is used to attach the AuthenticationManager to authorization server configuration. With these basic configurations, our Authorization server is ready to use. Let’s go ahead and start it and use it. We will be using Postman ( https://www.postman.com/downloads/ ) for making our requests. When using STS, we can launch our application and start seeing see the logs in our console. When the application starts, we can find the oauth2 endpoints exposed by our application in the console. Of those endpoints, we will be using the following the below token for now − /oauth/token – for obtaining the token. If we check the postman snapshot here, we can notice a few things. Let’s list them down below. The URL − Our Spring Boot Application is running at port 8080 of our local machine, so the request is pointed to http://localhost:8080. The next part is /oauth/token, which we know, is the endpoint exposed by OAuth for generating the token. The query params− Since this is a “password” authorization grant type, the user needs to provide his/her username, password and scope to our client application, which then uses those credentials along with its credentials to the authorization server we want the tokens from. Client Authorization − The Oauth system requires the client to be authorized to be able to provide the token. Hence, under the Authorization header, we provide the client authentication information, namely username and password that we configured in our application. Let’s take a closer look at the query params and the authorization header − The query params Client credentials If everything is correct, we shall be able to see our generated token in the response along with a 200 ok status. The response We can test our server, by putting wrong credentials or no credentials, and we will get back an error which would say the request is unauthorized or has bad credentials. This is our basic oauth authorization server, that uses the password grant type to generate and provide a password. Next, let’s implement a more secure, and a more common application of the oauth2 authentication, i.e. with an authorization code grant type. We will update our current application for this purpose. The authorization grant type is different from the password grant type in the sense that the user doesn’t have to share his credentials with the client application. He shares them with the authorization server only and in return authorization code is sent to the client which it uses to authenticate the client. It is more secure than the password grant type as user credentials are not shared with the client application and hence the user’s information stays safe. The client application doesn’t get access to any important user information unless approved by the user. In a few simple steps, we can set up a basic oauth server with an authorization grant type in our application. Let’s see how. package com.tutorial.spring.security.oauth2.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("oauthclient1") .secret("oauthsecret1") .scopes("read") .authorizedGrantTypes("password") .and() .withClient("oauthclient2") .secret("oauthsecret2") .scopes("read") .authorizedGrantTypes("authorization_code") .redirectUris("http://locahost:9090"); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager); } } Let’s add a second client for this operation oauthclient2 for this operation with a new secret and read scope. Here we have changed the grant type to authorization code for this client. We also added a redirect URI so that the authorization server can callback the client. So, basically the redirect URI is the URI of the client. Now, we have to establish a connection between the user and the authorization server. We have to set an interface for the authorization server where the user can provide the credentials. We use the formLogin() implementation of Spring Security to achieve that functionality while keeping things simple. We also make sure that all requests are authenticated. package com.tutorial.spring.security.oauth2.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.provisioning.UserDetailsManager; @SuppressWarnings("deprecation") @Configuration public class UserConfig extends WebSecurityConfigurerAdapter { @Bean public UserDetailsService userDetailsService() { UserDetailsManager userDetailsManager = new InMemoryUserDetailsManager(); UserDetails user = User.withUsername("john") .password("12345") .authorities("read") .build(); userDetailsManager.createUser(user); return userDetailsManager; } @Bean public PasswordEncoder passwordEncoder() { return NoOpPasswordEncoder.getInstance(); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override protected void configure(HttpSecurity http) throws Exception { http.formLogin(); http.authorizeRequests().anyRequest().authenticated(); } } This completes our setup for the authorization grant type. Now to test our setup and launch our application. We launch our browser at http://localhost:8080/oauth/authorize?response_type=code&client_id=oauthclient2&scope=read. We will redirected to the default form login page of Spring Security. Here, the response type code implies that the authorization server will return an access code which will be used by the client to log in. When we use the user credentials we will be asked if I want to grant the permissions asked by the client, in a similar screen as shown below. If we approve and click Authorize we shall see we are redirected to our given redirect url along with the access code. In our case the we are redirected to http://locahost:9090/?code=7Hibnw, as we specified in the application. We can use the code now as a client in Postman to login to the authorization server. As we can see here, we have used the code received from the authorization server in our URL, and the grant_type as authorization_code and scope as read. We acted as the client and provided the client credentials as configured in our application. When we make this request we get back our access_token which we can use further. So, we have seen how we can configure Spring Security with OAuth 2.0. The application is pretty simple and easy to understand and helps us understand the process fairly easily. We have used two kinds of authorization grant types and seen how we can use them to acquire access tokens for our client application. JWT Introduction and overview Getting started with Spring Security using JWT(Practical Guide) JSON Web Token or JWT, as it is more commonly called, is an open Internet standard (RFC 7519) for securely transmitting trusted information between parties in a compact way. The tokens contain claims that are encoded as a JSON object and are digitally signed using a private secret or a public key/private key pair. They are self-contained and verifiable as they are digitally signed. JWT’s can be signed and/or encrypted. The signed tokens verify the integrity of the claims contained in the token, while the encrypted ones hide the claims from other parties. JWT’s can also be used for the exchange of information though they more commonly used for authorization as they offer a lot of advantages over session management using in-memory random tokens. The biggest of them being the enabling the delegation of authentication logic to a third-party server like AuthO etc. A JWT token is divided into 3 parts namely – header, payload, and signature in the format of [Header].[Payload].[Signature] Header − The Header of a JWT token contains the list cryptographic operations that are applied to the JWT. This can be the signing technique, metadata information about the content-type and so on. The header is presented as a JSON object which is encoded to a base64URL. An example of a valid JWT header would be Header − The Header of a JWT token contains the list cryptographic operations that are applied to the JWT. This can be the signing technique, metadata information about the content-type and so on. The header is presented as a JSON object which is encoded to a base64URL. An example of a valid JWT header would be { "alg": "HS256", "typ": "JWT" } Here, “alg” gives us information about the type of algorithm used and “typ gives us the type of the information. Payload − The payload part of JWT contains the actual data to be transferred using the token. This part is also known as the “claims” part of the JWT token. The claims can be of three types – registered, public and private. Payload − The payload part of JWT contains the actual data to be transferred using the token. This part is also known as the “claims” part of the JWT token. The claims can be of three types – registered, public and private. The registered claims are the ones which are recommended but not mandatory claims such as iss(issuer), sub(subject), aud(audience) and others. The registered claims are the ones which are recommended but not mandatory claims such as iss(issuer), sub(subject), aud(audience) and others. Public claims are those that are defined by those using the JWTs. Public claims are those that are defined by those using the JWTs. Private claims or custom claims are user-defined claims created for the purpose of sharing the information between the concerned parties. Private claims or custom claims are user-defined claims created for the purpose of sharing the information between the concerned parties. Example of a payload object could be. { "sub": "12345", "name": "Johnny Hill", "admin": false } The payload object, like the header object is base64Url encoded as well and this string forms the second part of the JWT. Signature− The signature part of the JWT is used for the verification that the message wasn’t changed along the way. If the tokens are signed with private key, it also verifies that the sender is who it says it is. It is created using the encoded header, encoded payload, a secret and the algorithm specified in the header. An example of a signature would be. Signature− The signature part of the JWT is used for the verification that the message wasn’t changed along the way. If the tokens are signed with private key, it also verifies that the sender is who it says it is. It is created using the encoded header, encoded payload, a secret and the algorithm specified in the header. An example of a signature would be. HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret) If we put the header, payload and signature we get a token as given below. eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6I kpvaG4gRG9lIiwiYWRtaW4iOmZhbHNlfQ.gWDlJdpCTIHVYKkJSfAVNUn0ZkAjMxskDDm-5Fhe WJ7xXgW8k5CllcGk4C9qPrfa1GdqfBrbX_1x1E39JY8BYLobAfAg1fs_Ky8Z7U1oCl6HL63yJq_ wVNBHp49hWzg3-ERxkqiuTv0tIuDOasIdZ5FtBdtIP5LM9Oc1tsuMXQXCGR8GqGf1Hl2qv8MCyn NZJuVdJKO_L3WGBJouaTpK1u2SEleVFGI2HFvrX_jS2ySzDxoO9KjbydK0LNv_zOI7kWv-gAmA j-v0mHdJrLbxD7LcZJEGRScCSyITzo6Z59_jG_97oNLFgBKJbh12nvvPibHpUYWmZuHkoGvuy5RLUA Now, this token can be used in the Authorization header using the Bearer schema as. Authorization − Bearer <token> The use of JWT token for authorization is the most common of its applications. The token is usually generated in the server and sent to the client where it is stored in the session storage or local storage. To access a protected resource the client would send the JWT in the header as given above. We will see the JWT implementation in Spring Security in the section below. The application we are going to develop will handle basic user authentication and authorization with JWT’s. Let’s get started by going to start.spring.io where we will create a Maven application with the following dependencies. Spring Web Spring Security We generate the project and when it is downloaded, we extract it to a folder of our choice. We can then use any IDE of our choice. I am going to use Spring Tools Suite 4 as it is most optimized for Spring applications. Apart from the above-mentioned dependencies we are also going to include the jwt dependency from io.jsonwebtoken from the Maven central repository as it is not included in the spring initializer. This dependency takes care of all operations involving the JWT including building the token, parsing it for claims and so on. <dependency> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> Our pom.xml file should now look similar to this. <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.1.RELEASE<version> <relativePath /> <!-- lookup parent from repository --> </parent> <groupId>com.spring.security</groupId> <artifactId>jwtbasic</artifactId> <version>0.0.1-SNAPSHOT</version> <name>jwtbasic</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test<scope> <dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Now that our project is set up we are going to create our controller class Hello Controller which exposes a Get endpoint. package com.spring.security.jwtbasic.controllers; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @GetMapping("/hello") public String hello() { return "hello"; } } Now we are going to create a package called config where we add the configuration class that extends the WebSecurityConfigurerAdapter class of Spring Security. This will provide us with all the required functions and definitions for project configuration and security of our application. For now, we provide the BcryptPasswordEncoder instance by implementing a method that generates the same. We annotate the method with @Bean to add to our Spring Context. package com.spring.security.jwtbasic.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import com.spring.security.jwtbasic.jwtutils.JwtAuthenticationEntryPoint; import com.spring.security.jwtbasic.jwtutils.JwtFilter; @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } The JWT includes a secret which we will define in our application.properties file as given below. secret=somerandomsecret Now let’s create a package called jwtutils. This package is going to contain all classes and interface related to JWT operations, which will include. Generating token Validating token Checking the signature Verifying claims and permissions In this package, we create our first class called Token Manager. This class will be responsible for the creation and validation of tokens using io.jsonwebtoken.Jwts. package com.spring.security.jwtbasic.jwtutils; import java.io.Serializable; import java.util.Base64; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Component; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; @Component public class TokenManager implements Serializable { /** * */ private static final long serialVersionUID = 7008375124389347049L; public static final long TOKEN_VALIDITY = 10 * 60 * 60; @Value("${secret}") private String jwtSecret; public String generateJwtToken(UserDetails userDetails) { Map<String, Object> claims = new HashMap<>(); return Jwts.builder().setClaims(claims).setSubject(userDetails.getUsername()) .setIssuedAt(new Date(System.currentTimeMillis())) .setExpiration(new Date(System.currentTimeMillis() + TOKEN_VALIDITY * 1000)) .signWith(SignatureAlgorithm.HS512, jwtSecret).compact(); } public Boolean validateJwtToken(String token, UserDetails userDetails) { String username = getUsernameFromToken(token); Claims claims = Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody(); Boolean isTokenExpired = claims.getExpiration().before(new Date()); return (username.equals(userDetails.getUsername()) && !isTokenExpired); } public String getUsernameFromToken(String token) { final Claims claims = Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody(); return claims.getSubject(); } } Here, as all tokens should have an expiration date, we start with a token validity constant. Here, we want our token to be valid for 10 minutes after generation. We will use this value when we generate our token. Then we extract the value of our singing key from the application.properties file into our jwtSecret field using the @Value annotation. We have two methods here − generateJwtToken() − This method is used to generate a token on successful authentication by the user. To create the token here we use the username, issue date of token and the expiration date of the token. This will form the payload part of the token or claims as we had discussed earlier. To generate the token we use the builder() method of Jwts. This method returns a new JwtBuilder instance that can be used to create compact JWT serialized strings. To set the claims we use the setClaims() method and then set each of the claims. For this token we have setSubject(username), issue date and expiration date. We can also put our custom claims as we had discussed above. This can be any value we want which might include user role, user authorities and so on. Then we set the signature part of the token. This is done using the signWith() method, we set the hashing algorithm we prefer to use and the secret key. Then we use thecompact() method that builds the JWT and serializes it to a compact, URL-safe string according to the JWT Compact Serialization rules. validateJwtToken() − Now that the generation of the token is taken care of, we should focus on the process of validation of the token when it comes as a part of requests. To validate the token means to verify the request is an authenticated one and that the token is the one that was generated and sent to the user. Here, we need to parse the token for the claims such as username, roles, authorities, validity period etc. validateJwtToken() − Now that the generation of the token is taken care of, we should focus on the process of validation of the token when it comes as a part of requests. To validate the token means to verify the request is an authenticated one and that the token is the one that was generated and sent to the user. Here, we need to parse the token for the claims such as username, roles, authorities, validity period etc. To validate the token we need to parse it first. This is done using the parser() method of Jwts. We then need to set the signing key that we used to generate the token and then use parseClaimsJws() method on the token to parse the compact serialized JWS string based on the builder’s current configuration state and return the resulting Claims JWS instance. The getBody() method is then used to return the claims instance that was used while generating the token. From this obtained claims instance, we extract the subject and the expiry date to verify the validity of the token. The username should be the username of the user and the token should not be expired. If both these conditions are met, we return true, which signifies that the token is valid. The next class we would be creating is the JwtUserDetailsService. This class will extend the UserDetailsService of Spring security and we will implement the loadUserByUsername() method as given below − package com.spring.security.jwtbasic.jwtutils; import java.util.ArrayList; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; @Service public class JwtUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { if ("randomuser123".equals(username)) { return new User("randomuser123", "$2a$10$slYQmyNdGzTn7ZLBXBChFOC9f6kFjAqPhccnP6DxlWXx2lPk1C3G6", new ArrayList<>()); } else { throw new UsernameNotFoundException("User not found with username: " + username); } } } Here, since this is a basic application for the sole purpose of the demonstration of JWT authentication, we have resorted to a set of our user details, instead of using a database. We have given the username as “randomuser123” and encoded the password, which is “password” as “$2a$10$slYQmyNdGzTn7ZLBXBChFOC9f6kFjAqPhccnP6DxlWXx2lPk1C3G6” for our convenience. Next, we create classes for our Request and Response models. These models determine how our request and response formats would be for authentication. The first snapshot given below is the request model. As we can see, we shall be accepting two properties – username and password in our request. package com.spring.security.jwtbasic.jwtutils.models; import java.io.Serializable; public class JwtRequestModel implements Serializable { /** * */ private static final long serialVersionUID = 2636936156391265891L; private String username; private String password; public JwtRequestModel() { } public JwtRequestModel(String username, String password) { super(); this.username = username; this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } Below is the code for response model on successful authentication. As we can see, we will be sending the token back to the user on successful authentication. package com.spring.security.jwtbasic.jwtutils.models; import java.io.Serializable; public class JwtResponseModel implements Serializable { /** * */ private static final long serialVersionUID = 1L; private final String token; public JwtResponseModel(String token) { this.token = token; } public String getToken() { return token; } } For authentication now, let’s create a controller as given below. package com.spring.security.jwtbasic.jwtutils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.DisabledException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.spring.security.jwtbasic.jwtutils.models.JwtRequestModel; import com.spring.security.jwtbasic.jwtutils.models.JwtResponseModel; @RestController @CrossOrigin public class JwtController { @Autowired private JwtUserDetailsService userDetailsService; @Autowired private AuthenticationManager authenticationManager; @Autowired private TokenManager tokenManager; @PostMapping("/login") public ResponseEntity<> createToken(@RequestBody JwtRequestModel request) throws Exception { try { authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword()) ); } catch (DisabledException e) { throw new Exception("USER_DISABLED", e); } catch (BadCredentialsException e) { throw new Exception("INVALID_CREDENTIALS", e); } final UserDetails userDetails = userDetailsService.loadUserByUsername(request.getUsername()); final String jwtToken = tokenManager.generateJwtToken(userDetails); return ResponseEntity.ok(new JwtResponseModel(jwtToken)); } } If we go through the code we can see that, we have autowired three dependencies namely, JwtUserDetailsService, AuthenticationManager and TokenManager. While we have already seen the implementation of JwtUserDetailsService and TokenManager classes above, the authentication manager bean is one we shall be creating in our WebSecurityConfig class. AuthenticationManager class will take care of our authentication. We shall be using the UsernamePasswordAuthenticationToken model for authentication of the request. If authentication succeeds we shall generate a JWT for the user, which can be sent in the Authorization header of the subsequent requests to get any resource. As we can see, we are using the loadUserByUsername() method of our JwtUserDetailsService class and the generateJwtToken() from TokenManager class. This generated JWT is sent to the user as a response on successful authentication as mentioned above. Now it’s time we created our Filter. The filter class will be used to track our requests and detect if they contain the valid token in the header. If the token is valid we let the request proceed otherwise we send a 401 error (Unauthorized). package com.spring.security.jwtbasic.jwtutils; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import io.jsonwebtoken.ExpiredJwtException; @Component public class JwtFilter extends OncePerRequestFilter { @Autowired private JwtUserDetailsService userDetailsService; @Autowired private TokenManager tokenManager; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String tokenHeader = request.getHeader("Authorization"); String username = null; String token = null; if (tokenHeader != null && tokenHeader.startsWith("Bearer ")) { token = tokenHeader.substring(7); try { username = tokenManager.getUsernameFromToken(token); } catch (IllegalArgumentException e) { System.out.println("Unable to get JWT Token"); } catch (ExpiredJwtException e) { System.out.println("JWT Token has expired"); } } else { System.out.println("Bearer String not found in token"); } if (null != username &&SecurityContextHolder.getContext().getAuthentication() == null) { UserDetails userDetails = userDetailsService.loadUserByUsername(username); if (tokenManager.validateJwtToken(token, userDetails)) { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( userDetails, null, userDetails.getAuthorities()); authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authenticationToken); } } filterChain.doFilter(request, response); } } As we can see above, we have autowired the JwtUserDetailsService and TokenManager classes here as well. We have extended the OncePerRequestFilter of SpringSecurity which makes sure the filter is run for every request. We have provided our implementation to the overridden method doFilterInternal() of the OncePerRequestFilter class. The method here extracts the token from the header and validates it with the help of validateJwtToken() method of our TokenManager class. During validation, it checks for the username and the expiration date. If both the values are valid, we save the authentication in our Spring Security context and let the code proceed to the next filter in our filter chain. If any of the validation fails or there is an issue with the token or if the token is not found we throw the appropriate exceptions and send back an appropriate response while blocking the request from moving ahead. Having created the filter for our requests, we now create the JwtAutheticationEntryPoint class. This class extends Spring’s AuthenticationEntryPoint class and rejects every unauthenticated request with an error code 401 sent back to the client. We have overridden the commence() method of AuthenticationEntryPoint class to do that. package com.spring.security.jwtbasic.jwtutils; import java.io.IOException; import java.io.Serializable; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.stereotype.Component; @Component public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); } } Now, let’s get back to our WebSecurityConfig class and finish the rest of our configuration. If we remember, we are going to require our AuthenticationManager bean for our Jwt controller class and add the filter we just created to our configuration. We are also going to configure which requests are to be authenticated and which are not to be. We shall also add the AuthenticationEntryPoint to our requests to send back the 401 error response. Since, we also do not need to maintain session variables while using jwt we can make our session STATELESS. package com.spring.security.jwtbasic.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import com.spring.security.jwtbasic.jwtutils.JwtAuthenticationEntryPoint; import com.spring.security.jwtbasic.jwtutils.JwtFilter; @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private JwtAuthenticationEntryPoint authenticationEntryPoint; @Autowired private UserDetailsService userDetailsService; @Autowired private JwtFilter filter; @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests().antMatchers("/login").permitAll() .anyRequest().authenticated() .and() .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint) .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); http.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class); } } As we can see, we have done all of that, and now our application is ready to go. Let’s start the application and use postman for making our requests. Here we have made our first request to get the token, and as we can see on providing the correct username/password combination we get back our token. Now using that token in our header, let’s call the /hello endpoint. As we can see, since the request is authenticated, we get the desired response back. Now, if we tamper with the token or do not send the Authorization header, we will get a 401 error as configured in our application. This ensures that the protection our request using the JWT. 102 Lectures 8 hours Karthikeya T 39 Lectures 5 hours Chaand Sheikh 73 Lectures 5.5 hours Senol Atac 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac 69 Lectures 5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 1861, "s": 1835, "text": "Introduction and Overview" }, { "code": null, "e": 2079, "s": 1861, "text": "Basic components of Spring Security\n\nAuthenticationFilter\nAuthenticationManager\nAuthenticationProvider\nUserDetailsService\nPasswordEncoder\nSpring Security Context\nForm Login\nLogin with a Database\nLogin Attempts Limit\n\n" }, { "code": null, "e": 2100, "s": 2079, "text": "AuthenticationFilter" }, { "code": null, "e": 2122, "s": 2100, "text": "AuthenticationManager" }, { "code": null, "e": 2145, "s": 2122, "text": "AuthenticationProvider" }, { "code": null, "e": 2164, "s": 2145, "text": "UserDetailsService" }, { "code": null, "e": 2180, "s": 2164, "text": "PasswordEncoder" }, { "code": null, "e": 2204, "s": 2180, "text": "Spring Security Context" }, { "code": null, "e": 2215, "s": 2204, "text": "Form Login" }, { "code": null, "e": 2237, "s": 2215, "text": "Login with a Database" }, { "code": null, "e": 2258, "s": 2237, "text": "Login Attempts Limit" }, { "code": null, "e": 2292, "s": 2258, "text": "Getting Started (Practical Guide)" }, { "code": null, "e": 3002, "s": 2292, "text": "In addition to providing various inbuilt authentication and authorization options, Spring Security allows us to customize our authentication process as much as we want. Starting from a custom login page to our very own customized authentication providers and authentication filters, we can pretty much customize every aspect of the authentication process. We can define our own authentication process which can range from basic authentication using a username and a password to a complex one such as two-factor authentication using tokens and OTP’s. Also, we can use various databases – both relational and non-relational, use various password encoders, lock malicious users out of their accounts, and so on." }, { "code": null, "e": 3436, "s": 3002, "text": "Today, we are going to discuss three such customizations, namely – custom form-login, a database provided authentication, and limiting login attempts. Though these are pretty basic use-cases, yet these still will let us have a closer look into Spring Security’s authentication and authorization process. We are also going to set up a registration page through which the users will be able to register themselves with our application." }, { "code": null, "e": 4060, "s": 3436, "text": "First of all, let’s take a look at the architecture of Spring Security. It starts with servlet filters. These filters intercept requests, perform operations on them, and then pass the requests on to next filters in the filter chain or request handlers or block them if they do not meet certain conditions. It is during this process that Spring Security can authenticate requests and perform various authentication checks on the requests. It can also prevent unauthenticated or malicious requests from accessing our protected resources by not allowing them to pass through. Thus our application and resources stay protected." }, { "code": null, "e": 4282, "s": 4060, "text": "The basic components of Spring Security, as we can see in the above diagram are given below. We shall discuss them briefly as we go along. We shall also discuss their roles in the authentication and authorization process." }, { "code": null, "e": 4494, "s": 4282, "text": "This is the filter that intercepts requests and attempts to authenticate it. In Spring Security, it converts the request to an Authentication Object and delegates the authentication to the AuthenticationManager." }, { "code": null, "e": 4973, "s": 4494, "text": "It is the main strategy interface for authentication. It uses the lone method authenticate() to authenticate the request. The authenticate() method performs the authentication and returns an Authentication Object on successful authentication or throw an AuthenticationException in case of authentication failure. If the method can’t decide, it will return null. The process of authentication in this process is delegated to the AuthenticationProvider which we will discuss next." }, { "code": null, "e": 5785, "s": 4973, "text": "The AuthenticationManager is implemented by the ProviderManager which delegates the process to one or more AuthenticationProvider instances. Any class implementing the AuthenticationProvider interface must implement the two methods – authenticate() and supports(). First, let us talk about the supports() method. It is used to check if the particular authentication type is supported by our AuthenticationProvider implementation class. If it is supported it returns true or else false. Next, the authenticate() method. Here is where the authentication occurs. If the authentication type is supported, the process of authentication is started. Here is this class can use the loadUserByUsername() method of the UserDetailsService implementation. If the user is not found, it can throw a UsernameNotFoundException." }, { "code": null, "e": 6246, "s": 5785, "text": "On the other hand, if the user is found, then the authentication details of the user are used to authenticate the user. For example, in the basic authentication scenario, the password provided by the user may be checked with the password in the database. If they are found to match with each other, it is a success scenario. Then we can return an Authentication object from this method which will be stored in the Security Context, which we will discuss later." }, { "code": null, "e": 6720, "s": 6246, "text": "It is one of the core interfaces of Spring Security. The authentication of any request mostly depends on the implementation of the UserDetailsService interface. It is most commonly used in database backed authentication to retrieve user data. The data is retrieved with the implementation of the lone loadUserByUsername() method where we can provide our logic to fetch the user details for a user. The method will throw a UsernameNotFoundException if the user is not found." }, { "code": null, "e": 7295, "s": 6720, "text": "Until Spring Security 4, the use of PasswordEncoder was optional. The user could store plain text passwords using in-memory authentication. But Spring Security 5 has mandated the use of PasswordEncoder to store passwords. This encodes the user’s password using one its many implementations. The most common of its implementations is the BCryptPasswordEncoder. Also, we can use an instance of the NoOpPasswordEncoder for our development purposes. It will allow passwords to be stored in plain text. But it is not supposed to be used for production or real-world applications." }, { "code": null, "e": 7816, "s": 7295, "text": "This is where the details of the currently authenticated user are stored on successful authentication. The authentication object is then available throughout the application for the session. So, if we need the username or any other user details, we need to get the SecurityContext first. This is done with the SecurityContextHolder, a helper class, which provides access to the security context. We can use the setAuthentication() and getAuthentication() methods for storing and retrieving the user details respectively." }, { "code": null, "e": 7919, "s": 7816, "text": "Moving on, let’s now discuss the three custom implementations we are going to use for our application." }, { "code": null, "e": 8717, "s": 7919, "text": "When we add Spring Security to an existing Spring application it adds a login form and sets up a dummy user. This is Spring Security in auto-configuration mode. In this mode, it also sets up the default filters, authentication-managers, authentication-providers, and so on. This setup is an in-memory authentication setup. We can override this auto-configuration to set up our own users and authentication process. We can also set up our custom login method like a custom login form. Spring Security only has to made aware of the details of the login form like – the URI of the login form, the login processing URL, etc.. It will then render our login form for the application and carry out the process of authentication along with the other provided configurations or Spring’s own implementation." }, { "code": null, "e": 9384, "s": 8717, "text": "This custom form setup will only have to abide by certain rules to be integrated with Spring Security. We need to have a username parameter and a password parameter and the parameter names should be “username” and “password” since those are the default names. In case, we use our own parameter names for these fields in the custom we have to inform Spring Security of those changes using the usernameParameter() and passwordParameter() methods. Similarly, for every change we do to the login form or the form login method, we will have to inform Spring Security of those changes with appropriate methods so that it can integrate them with the authentication process." }, { "code": null, "e": 10019, "s": 9384, "text": "As we discussed, Spring Security automatically provides an in-memory authentication implementation by default. We can override this by authenticating users whose details are stored in a database. In this case, while authenticating a user, we can verify the credentials provided by the user against those in the database for authentication. We can also let new users register in our application and store their credentials in the same database. Also, we can provide methods to change or update their passwords or roles or other data. As a result, this provides us with persistent user data which can be used for longer periods of time." }, { "code": null, "e": 10878, "s": 10019, "text": "To limit login attempts in our application we can use Spring Security’s isAccountNonLocked property. Spring Security’s UserDetails provides us with that property. We can set up an authentication method wherein, if any user or someone else provides incorrect credentials for more than a certain number of times, we can lock their account. Spring Security disables authentication for a locked user even if the user provides correct credentials. This is an in-built feature provided by Spring Security. We can store the number of incorrect login attempts in our database. Then against each incorrect authentication attempt, we can update and check with the database table. When the number of such attempts exceeds a given number, we can lock the user out of their account. Consequently, the user will not be able to log in again until their account is unlocked." }, { "code": null, "e": 10985, "s": 10878, "text": "Let’s start with our application now. The tools we will be needing for this application are listed below −" }, { "code": null, "e": 11069, "s": 10985, "text": "A Java IDE − preferable STS 4, but Eclipse, IntelliJ Idea or any other IDE will do." }, { "code": null, "e": 11153, "s": 11069, "text": "A Java IDE − preferable STS 4, but Eclipse, IntelliJ Idea or any other IDE will do." }, { "code": null, "e": 11308, "s": 11153, "text": "MySql Server Community Edition − We need to download and install MySql Community Server in our system. We can go to the official website by clicking here." }, { "code": null, "e": 11463, "s": 11308, "text": "MySql Server Community Edition − We need to download and install MySql Community Server in our system. We can go to the official website by clicking here." }, { "code": null, "e": 11548, "s": 11463, "text": "MySql Workbench − It is a GUI tool that we can use to interact with MySql databases." }, { "code": null, "e": 11633, "s": 11548, "text": "MySql Workbench − It is a GUI tool that we can use to interact with MySql databases." }, { "code": null, "e": 11925, "s": 11633, "text": "Let’s set up the database first. We will use a MySql database instance for this application. MySql Server Community Edition is available for free download and use. We will use MySql Workbench to connect with our MySql Server and create a database called “spring” to use with our application." }, { "code": null, "e": 12296, "s": 11925, "text": "Then we will create two tables – users and attempts– to persist our users and login attempts. As mentioned earlier, the details of the users registering with our application will be stored in the users table. The number of login attempts by any user will be stored in the attempts table against his username. This way we can track the attempts and take necessary action." }, { "code": null, "e": 12374, "s": 12296, "text": "Let’s take a the look at the SQL to setup our users table and attempts table." }, { "code": null, "e": 12697, "s": 12374, "text": "CREATE TABLE users ( \n username VARCHAR(45) NOT NULL , password VARCHAR(45) NOT NULL , \n account_non_locked TINYINT NOT NULL DEFAULT 1 , \n PRIMARY KEY (username)\n); \nCREATE TABLE attempts ( \n id int(45) NOT NULL AUTO_INCREMENT, \n username varchar(45) NOT NULL, attempts varchar(45) NOT NULL, PRIMARY KEY (id) \n);" }, { "code": null, "e": 12745, "s": 12697, "text": "We can now add a dummy user to our application." }, { "code": null, "e": 12834, "s": 12745, "text": "INSERT INTO users(username,password,account_non_locked) \nVALUES ('user','12345', true);\n" }, { "code": null, "e": 13142, "s": 12834, "text": "As usual, we will use the Spring Initializer to setup our project. We are going to create a Maven project, with Spring Boot version 2.3.2. Let’s name our project formlogin(we can choose any name we want) and group id as com.tutorial.spring.security. Furthermore, we will use Java version 8 for this project." }, { "code": null, "e": 13479, "s": 13142, "text": "Now, coming to the dependencies, we are going to keep our application as simple as possible for this demo. We will keep our focus on the features we want to explore today. So we will choose the minimum number of dependencies that will help us set up our application and get it up and running quickly. Let’s go through the dependencies −" }, { "code": null, "e": 13606, "s": 13479, "text": "Spring Web − It bundles all dependencies related to web development including Spring MVC, REST, and an embedded Tomcat Server." }, { "code": null, "e": 13733, "s": 13606, "text": "Spring Web − It bundles all dependencies related to web development including Spring MVC, REST, and an embedded Tomcat Server." }, { "code": null, "e": 13824, "s": 13733, "text": "Spring Security − For the implementation of security features provided by Spring Security." }, { "code": null, "e": 13915, "s": 13824, "text": "Spring Security − For the implementation of security features provided by Spring Security." }, { "code": null, "e": 13983, "s": 13915, "text": "Thymeleaf − A server-side Java template engine for HTML5/XHTML/XML." }, { "code": null, "e": 14051, "s": 13983, "text": "Thymeleaf − A server-side Java template engine for HTML5/XHTML/XML." }, { "code": null, "e": 14291, "s": 14051, "text": "Spring Data JPA − In addition to using all features defined by JPA specification, Spring Data JPA adds its own features such as the no-code implementation of the repository pattern and the creation of database queries from the method name." }, { "code": null, "e": 14531, "s": 14291, "text": "Spring Data JPA − In addition to using all features defined by JPA specification, Spring Data JPA adds its own features such as the no-code implementation of the repository pattern and the creation of database queries from the method name." }, { "code": null, "e": 14577, "s": 14531, "text": "Mysql Driver − For the MySQL database driver." }, { "code": null, "e": 14623, "s": 14577, "text": "Mysql Driver − For the MySQL database driver." }, { "code": null, "e": 14904, "s": 14623, "text": "With these five dependencies, we can set up our project now. Let’s click on the generate button. This will download our project as a zip file. We can extract it to a folder of our choice. Then we open the project in our IDE. We will be using Spring Tool Suite 4 for this. example." }, { "code": null, "e": 15065, "s": 14904, "text": "Let’s load our project into STS. It will take a little time for our IDE to download the dependencies and validating them. Let’s take a look at our pom.xml file." }, { "code": null, "e": 15073, "s": 15065, "text": "pom.xml" }, { "code": null, "e": 17725, "s": 15073, "text": "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?> \n<project xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 \n https://maven.apache.org/xsd/maven-4.0.0.xsd\" \n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n xmlns=\"http://maven.apache.org/POM/4.0.0\"> \n <modelVersion>4.0.0</modelVersion> \n <parent> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-starter-parent</artifactId> \n <version>2.3.1.RELEASE</version> \n <relativePath/> \n <!-- lookup parent from repository --> \n </parent> \n <groupId>com.tutorial.spring.security</groupId> \n <artifactId>formlogin</artifactId> \n <version>0.0.1-SNAPSHOT</version> \n <name>formlogin</name> \n <description>Demo project for Spring Boot</description> \n <properties> <java.version>1.8</java.version> \n </properties>\n <dependencies> \n <dependency> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-starter-data-jpa</artifactId> \n </dependency> \n <dependency> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-starter-security</artifactId> \n </dependency> \n <dependency> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-starter-thymeleaf</artifactId> \n </dependency> \n <dependency> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-starter-web</artifactId> \n </dependency> \n <dependency> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-devtools</artifactId> \n <scope>runtime<scope> <optional>true</optional>\n </dependency> \n <dependency> \n <groupId>mysql</groupId>\n <artifactId>mysql-connector-java</artifactId> \n <scope>runtime</scope> </dependency> \n <dependency> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-starter-test</artifactId> \n <scope>test</scope> \n <exclusions> \n <exclusion> \n <groupId>org.junit.vintage</groupId> \n <artifactId>junit-vintage-engine</artifactId> \n </exclusion> \n </exclusions> \n </dependency> \n <dependency> \n <groupId>org.springframework.security</groupId> \n <artifactId>spring-security-test<artifactId> \n <scope>test</scope> \n </dependency>\n </dependencies> \n <build> \n <plugins> \n <plugin> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-maven-plugin</artifactId> \n </plugin> \n </plugins> \n </build> \n</project>" }, { "code": null, "e": 17808, "s": 17725, "text": "We can see that our project details along with our dependencies are enlisted here." }, { "code": null, "e": 18054, "s": 17808, "text": "We will configure our data source in the application.properties file. As we will be using our local MySQL DB as the data source, so we provide the url, username, and password of our local DB instance here. We have named our database as “spring”." }, { "code": null, "e": 18178, "s": 18054, "text": "spring.datasource.url=jdbc:mysql://localhost:3306/spring \nspring.datasource.username=root \nspring.datasource.password=root\n" }, { "code": null, "e": 18829, "s": 18178, "text": "Let’s create our entities now. We start with the User entity which contains three fields – username, password, and accountNonLocked. This User class also implements the UserDetails interface of Spring Security. This class provides core user information. It is used to store user data which can be later encapsulated into Authentication objects. It is not recommended to implement the interface directly. But for our case, since this is a simple application to demonstrate the login with a database, we have implemented this interface directly here to keep thingssimple. We can implement this interface by using a wrapper class around our User entity." }, { "code": null, "e": 18839, "s": 18829, "text": "User.java" }, { "code": null, "e": 20710, "s": 18839, "text": "package com.tutorial.spring.security.formlogin.model; \n\nimport java.util.Collection; \nimport java.util.List;\nimport javax.persistence.Column; \nimport javax.persistence.Entity; \nimport javax.persistence.Id; \nimport javax.persistence.Table; \nimport org.springframework.security.core.GrantedAuthority; \nimport org.springframework.security.core.userdetails.UserDetails; \n\n@Entity \n@Table(name = \"users\") \npublic class User implements UserDetails { \n\n /** \n * \n */ \n private static final long serialVersionUID = 1L;\n\n @Id \n private String username; \n private String password; @Column(name = \"account_non_locked\")\n private boolean accountNonLocked; \n\n public User() { \n } \n public User(String username, String password, boolean accountNonLocked) { \n this.username = username; \n this.password = password; \n this.accountNonLocked = accountNonLocked; \n } \n @Override \n public Collection< extends GrantedAuthority> getAuthorities() { \n return List.of(() -> \"read\"); \n }\n @Override\n public String getPassword() { \n return password; \n } \n public void setPassword(String password) { \n this.password = password; \n } \n @Override \n public String getUsername() { \n return username; \n } \n public void setUsername(String username) { \n this.username = username; \n } \n @Override \n public boolean isAccountNonExpired() { \n return true; \n } \n @Override\n public boolean isAccountNonLocked() { \n return accountNonLocked; \n } \n @Override public boolean isCredentialsNonExpired() { \n return true; \n } \n @Override public boolean isEnabled() { \n return true; \n } \n \n public void setAccountNonLocked(Boolean accountNonLocked) { \n this.accountNonLocked = accountNonLocked; \n } \n public boolean getAccountNonLocked() { \n return accountNonLocked; \n } \n}" }, { "code": null, "e": 21361, "s": 20710, "text": "The accountNonLocked field is to be noted here. Every User in Spring Security has the account unlocked by default. To override that property and to lock the users out of their accounts once they exceed the permissible number of attempts, we shall be using this property. If the user exceeds the number of invalid attempts permissible, we shall use this property to lock him out of his account. Also, during every authentication attempt, we shall be checking this property with the isAccountNonLocked() method along with the credentials to authenticate the user. Any user with a locked account will not be allowed to authenticate into the application." }, { "code": null, "e": 21547, "s": 21361, "text": "For the other methods of the UserDetails interface, we can simply provide an implementation that returns true for now as we shall not be exploring these properties for this application." }, { "code": null, "e": 21694, "s": 21547, "text": "For the list of authorities for this user, let’s assign him a dummy role for now. We shall not be using this property either for this application." }, { "code": null, "e": 21708, "s": 21694, "text": "Attempts.java" }, { "code": null, "e": 21953, "s": 21708, "text": "Moving on, let’s create our Attempts entity to persist our invalid attempts count. As created in the database, we will have the three fields here – username, an integer named attempts to keep counts of the number of attempts, and an identifier." }, { "code": null, "e": 23023, "s": 21953, "text": "package com.tutorial.spring.security.formlogin.model; \n\nimport javax.persistence.Entity; \nimport javax.persistence.GeneratedValue; \nimport javax.persistence.GenerationType; \nimport javax.persistence.Id; \n\n@Entity \npublic class Attempts { \n @Id \n @GeneratedValue(strategy = GenerationType.IDENTITY) \n private int id;\n private String username; \n private int attempts;\n \n /** \n * @return the id \n */ \n public int getId() { \n return id; \n } \n /** \n * @param id the id to set \n */ \n public void setId(int id) { \n this.id = id; \n } \n /** \n * @return the username \n */ \n public String getUsername() { \n return username; \n }\n /** \n * @param username the username to set \n */ \n public void setUsername(String username) { \n this.username = username; \n } \n /** \n * @return the attempts \n */ \n public int getAttempts() { \n return attempts; \n } \n /** \n * @param attempts the attempts to set \n */ \n public void setAttempts(int attempts) { \n this.attempts = attempts; \n } \n}" }, { "code": null, "e": 23455, "s": 23023, "text": "We have created the entities, let’s create the repositories to store and retrieve data. We will have two repositories, one for each entity class. For both the repository interfaces, we will extend the JpaRepository which provides us with in-built implementations to save and retrieve data from the database configured in our application.properties file. We can also add our methods or queries here in addition to the provided ones." }, { "code": null, "e": 23475, "s": 23455, "text": "UserRepository.java" }, { "code": null, "e": 23879, "s": 23475, "text": "package com.tutorial.spring.security.formlogin.repository; \n\nimport java.util.Optional; \nimport org.springframework.data.jpa.repository.JpaRepository; \nimport org.springframework.stereotype.Repository; \nimport com.tutorial.spring.security.formlogin.model.User; \n\n@Repository public interface UserRepository extends JpaRepository<User, String> { \n Optional<User> findUserByUsername(String username); \n}" }, { "code": null, "e": 24045, "s": 23879, "text": "As discussed, we have added our method to retrieve a user by username here. This will return our user details including username, password and account locked status." }, { "code": null, "e": 24069, "s": 24045, "text": "AttemptsRepository.java" }, { "code": null, "e": 24494, "s": 24069, "text": "package com.tutorial.spring.security.formlogin.repository; \n\nimport java.util.Optional;\nimport org.springframework.data.jpa.repository.JpaRepository; \nimport org.springframework.stereotype.Repository; \nimport com.tutorial.spring.security.formlogin.model.Attempts; \n\n@Repository \npublic interface AttemptsRepository extends JpaRepository<Attempts, Integer> { \n Optional<Attempts> findAttemptsByUsername(String username); \n}" }, { "code": null, "e": 24797, "s": 24494, "text": "Similarly, for the Attempts, in our AttemptsRepository, we have added a custom method findAttemptsByUsername(String username) to get data about user attempts using the username. This will return us an Attempts object with the username and the number of failed authentication attempts the user has made." }, { "code": null, "e": 25028, "s": 24797, "text": "Since we are going to use a custom login form, we have to override the default configuration of Spring Security. To do this we create our configuration class which extends the WebSecurityConfigurerAdapter class of Spring Security." }, { "code": null, "e": 26131, "s": 25028, "text": "package com.tutorial.spring.security.formlogin.config; \n\nimport org.springframework.context.annotation.Bean; \nimport org.springframework.context.annotation.Configuration; \nimport org.springframework.security.config.annotation.web.builders.HttpSecurity;\nimport org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; \nimport org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; \nimport org.springframework.security.crypto.password.PasswordEncoder; \n@Configuration \npublic class ApplicationConfig extends WebSecurityConfigurerAdapter { \n @Bean \n public PasswordEncoder passwordEncoder() { \n return new BCryptPasswordEncoder(); \n } \n @Override \n protected void configure(HttpSecurity http) throws Exception { \n http \n .csrf().disable()\n .authorizeRequests().antMatchers(\"/register**\")\n .permitAll() .anyRequest().authenticated() \n .and() \n .formLogin() .loginPage(\"/login\")\n .permitAll() \n .and() \n .logout() .invalidateHttpSession(true) \n .clearAuthentication(true) .permitAll(); \n }\n}" }, { "code": null, "e": 26155, "s": 26131, "text": "Here we did two things−" }, { "code": null, "e": 26885, "s": 26155, "text": "First, we have specified the implementation of the PasswordEncoder interface that we are going to use. We have used an instance of BCryptPasswordEncoder to encode our passwords for this example. The PasswordEncoder interface has many implementations and we can use any of them. We have chosen BCryptPasswordEncoder here as it the most commonly used implementation. It uses the very strong BCrypt hashing algorithm to encode the passwords. It does so by incorporating a salt to protect against rainbow table attacks. In addition to this, bcrypt is an adaptive function: over time, the iteration count can be increased to make it slower, so it remains resistant to brute-force search attacks even with increasing computation power." }, { "code": null, "e": 26988, "s": 26885, "text": "Secondly, we have overridden the configure() method to provide our implementation of the login method." }, { "code": null, "e": 27156, "s": 26988, "text": "Whenever we use a custom form for authentication in place of the one provided by Spring Security, we have to inform Spring Security of it using the formLogin() method." }, { "code": null, "e": 27271, "s": 27156, "text": "We then also specify our login URL – /login. We will map the URL to our custom login page in our Controller later." }, { "code": null, "e": 27620, "s": 27271, "text": "We have also specified that the endpoints starting with /register, /login and the logout page need not be protected. We did so using the permitAll() method. This allows everyone to access these endpoints. Other than these endpoints, all endpoints are to be authenticated(). That is to say, users must be logged in to access all the other endpoints." }, { "code": null, "e": 27762, "s": 27620, "text": "On logout, we have specified that the session is to be invalidated and authentication stored in the application’s SecurityContext be cleared." }, { "code": null, "e": 27893, "s": 27762, "text": "Now, we will setup our authentication process. We are going to setup authentication using a database and locking of user accounts." }, { "code": null, "e": 28349, "s": 27893, "text": "Let’s create our implementation of UserDetailsService first. As we have discussed before, we need to provide our custom implementation for authentication using a database. This is because, Spring Security, as we know, only provides an in-memory authentication implementation by default. Therefore, we need to override that implementation with our database based process. To do so, we need to override the loadUserByUsername() method of UserDetailsService." }, { "code": null, "e": 29499, "s": 28349, "text": "package com.tutorial.spring.security.formlogin.security; \n\nimport java.util.Optional; \nimport org.springframework.beans.factory.annotation.Autowired; \nimport org.springframework.security.core.userdetails.UserDetails; \nimport org.springframework.security.core.userdetails.UserDetailsService; \nimport org.springframework.security.core.userdetails.UsernameNotFoundException; \nimport org.springframework.security.provisioning.UserDetailsManager; \nimport org.springframework.stereotype.Service; \nimport com.tutorial.spring.security.formlogin.model.User; \nimport com.tutorial.spring.security.formlogin.repository.UserRepository; \n\n@Service\npublic class SecurityUserDetailsService implements UserDetailsService { \n @Autowired \n private UserRepository userRepository; \n \n @Override \n public UserDetails loadUserByUsername(String username) \n throws UsernameNotFoundException { \n User user = userRepository.findUserByUsername(username) \n .orElseThrow(() -< new UsernameNotFoundException(\"User not present\")); \n return user; \n } \n public void createUser(UserDetails user) { \n userRepository.save((User) user); \n } \n}" }, { "code": null, "e": 29723, "s": 29499, "text": "As we can see here, we have implemented the loadUserByUsername() method here. Here we are fetching the user from our database using the UserRepository interface. If the user is not found it throws UsernameNotFoundException." }, { "code": null, "e": 29873, "s": 29723, "text": "We also have a createUser() method. We will use this method to add users to our database who have registered in our application using UserRepository." }, { "code": null, "e": 30052, "s": 29873, "text": "We will now implement our custom authentication provider. It will implement the AuthenticationProvider interface. We have two methods here that we have to override and implement." }, { "code": null, "e": 33374, "s": 30052, "text": "package com.tutorial.spring.security.formlogin.security; \n\nimport java.util.Optional; \nimport org.springframework.beans.factory.annotation.Autowired; \nimport org.springframework.security.authentication.AuthenticationProvider; \nimport org.springframework.security.authentication.BadCredentialsException; \nimport org.springframework.security.authentication.LockedException; \nimport org.springframework.security.authentication.UsernamePasswordAuthenticationToken; \nimport org.springframework.security.core.Authentication; \nimport org.springframework.security.core.AuthenticationException; \nimport org.springframework.security.crypto.password.PasswordEncoder; \nimport org.springframework.stereotype.Component;\n\nimport com.tutorial.spring.security.formlogin.model.Attempts; \nimport com.tutorial.spring.security.formlogin.model.User; \nimport com.tutorial.spring.security.formlogin.repository.AttemptsRepository;\nimport com.tutorial.spring.security.formlogin.repository.UserRepository;\n\n@Component public class AuthProvider implements AuthenticationProvider {\n private static final int ATTEMPTS_LIMIT = 3; \n \n @Autowired \n private SecurityUserDetailsService userDetailsService; \n @Autowired private PasswordEncoder passwordEncoder; \n @Autowired private AttemptsRepository attemptsRepository; \n @Autowired private UserRepository userRepository; \n @Override \n public Authentication authenticate(Authentication authentication) \n throws AuthenticationException {\n String username = authentication.getName();\n\nimport com.tutorial.spring.security.formlogin.repository.UserRepository; \n\n@Component public class AuthProvider implements AuthenticationProvider { \n private static final int ATTEMPTS_LIMIT = 3; \n @Autowired private SecurityUserDetailsService userDetailsService; \n @Autowired private PasswordEncoder passwordEncoder; \n @Autowired private AttemptsRepository attemptsRepository; \n @Autowired private UserRepository userRepository; \n @Override \n public Authentication authenticate(Authentication authentication) \n throws AuthenticationException { \n String username = authentication.getName();\n Optional<Attempts> \n userAttempts = attemptsRepository.findAttemptsByUsername(username); \n if (userAttempts.isPresent()) { \n Attempts attempts = userAttempts.get();\n attempts.setAttempts(0); attemptsRepository.save(attempts); \n } \n } \n private void processFailedAttempts(String username, User user) { \n Optional<Attempts> \n userAttempts = attemptsRepository.findAttemptsByUsername(username); \n if (userAttempts.isEmpty()) { \n Attempts attempts = new Attempts(); \n attempts.setUsername(username); \n attempts.setAttempts(1); \n attemptsRepository.save(attempts); \n } else {\n Attempts attempts = userAttempts.get(); \n attempts.setAttempts(attempts.getAttempts() + 1); \n attemptsRepository.save(attempts);\n \n if (attempts.getAttempts() + 1 > \n ATTEMPTS_LIMIT) {\n user.setAccountNonLocked(false); \n userRepository.save(user); \n throw new LockedException(\"Too many invalid attempts. Account is locked!!\"); \n } \n }\n }\n @Override public boolean supports(Class<?> authentication) { \n return true; \n }\n}" }, { "code": null, "e": 33707, "s": 33374, "text": "authenticate() − This method returns a fully authenticated object including credentials on successful authentication. This object is then stored in the SecurityContext. To perform authentication we will use the loaduserByUsername() method of the SecurityUserDetailsService class of our Application. Here we perform multiple things −" }, { "code": null, "e": 33985, "s": 33707, "text": "First, we extract the user credentials from the Authentication request object which is passed as a parameter to our function. This authentication object was prepared by the AuthenticationFilter class and passed down the AuthenticationProvider through the AuthenticationManager." }, { "code": null, "e": 34073, "s": 33985, "text": "We also fetch the user details from the database using the loadUserByUsername() method." }, { "code": null, "e": 34327, "s": 34073, "text": "Now, first, we check if the user account has been locked due to previous failed authentication attempts. If we find that the account is locked, we throw a LockedException, and the user will be unable to authenticate unless the account is unlocked again." }, { "code": null, "e": 34522, "s": 34327, "text": "If the account is not locked, we match the provided password along with the one stored against the user in the database. This is done using the matches() method of the PasswordEncoder interface." }, { "code": null, "e": 34833, "s": 34522, "text": "If the passwords match, and the account has not been locked by then, we return a fully authenticated object. Here we have used an instance UsernamePasswordAuthenticationToken class (as it is a username-password authentication) that implements Authentication. Meanwhile, we also reset the attempts counter to 0." }, { "code": null, "e": 34915, "s": 34833, "text": "On the other hand, if the password doesn’t match, we check for a few conditions −" }, { "code": null, "e": 35093, "s": 34915, "text": "If it is the user’s first attempt, then, probably his name would not be in the database. We check for this using the method findAttemptsByUsername() from the AttemptsRepository." }, { "code": null, "e": 35194, "s": 35093, "text": "If not found, we make an entry for the user in the database, with the number of attempts set to one." }, { "code": null, "e": 35260, "s": 35194, "text": "If a user is found, then we increase the number of attempts by 1." }, { "code": null, "e": 35372, "s": 35260, "text": "We then check against the maximum number of failed attempts allowed, using a constant value we defined earlier." }, { "code": null, "e": 35511, "s": 35372, "text": "If the number is more than the allowed number of attempts, then the user is locked our of the application and a LockedException is thrown." }, { "code": null, "e": 35800, "s": 35511, "text": "supports() − We also have the supports method that checks if our authentication type is supported by our AuthenticationProvider implementation class. It returns true, false, or null if it matches, doesn’t match, or if it can’t decide respectively. We have hardcoded it to be true for now." }, { "code": null, "e": 36203, "s": 35800, "text": "Now let’s create our controller package. It will contain our HelloController class. Using this controller class we will map our views to the endpoints and serve those views when the respective endpoints are hit. We will also autowire the PasswordEncoder and the UserDetailsService classes in this component. These injected dependencies will be used in creating our user. Let’s now create our endpoints." }, { "code": null, "e": 38666, "s": 36203, "text": "package com.tutorial.spring.security.formlogin.controller; \n\nimport java.util.Map;\nimport javax.servlet.http.HttpServletRequest; \nimport javax.servlet.http.HttpSession; \nimport org.springframework.beans.factory.annotation.Autowired; \nimport org.springframework.http.MediaType; \nimport org.springframework.security.authentication.BadCredentialsException; \nimport org.springframework.security.authentication.LockedException; \nimport org.springframework.security.crypto.password.PasswordEncoder; \nimport org.springframework.stereotype.Controller; \nimport org.springframework.web.bind.annotation.GetMapping; \nimport org.springframework.web.bind.annotation.PostMapping; \nimport org.springframework.web.bind.annotation.RequestParam; \nimport com.tutorial.spring.security.formlogin.model.User; \nimport com.tutorial.spring.security.formlogin.security.SecurityUserDetailsService; \n@Controller \npublic class HelloController { \n @Autowired private SecurityUserDetailsService userDetailsManager; \n @Autowired\n private PasswordEncoder passwordEncoder; \n \n @GetMapping(\"/\") \n public String index() { \n return \"index\"; \n }\n @GetMapping(\"/login\") \n public String login(HttpServletRequest request, HttpSession session) { \n session.setAttribute(\n \"error\", getErrorMessage(request, \"SPRING_SECURITY_LAST_EXCEPTION\")\n ); \n return \"login\"; \n } \n @GetMapping(\"/register\") \n public String register() { \n return \"register\"; \n } \n @PostMapping(\n value = \"/register\", \n consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = { \n MediaType.APPLICATION_ATOM_XML_VALUE, MediaType.APPLICATION_JSON_VALUE }\n )\n public void addUser(@RequestParam Map<String, String> body) {\n User user = new User(); user.setUsername(body.get(\"username\")); \n user.setPassword(passwordEncoder.encode(body.get(\"password\"))); \n user.setAccountNonLocked(true); userDetailsManager.createUser(user); \n }\n private String getErrorMessage(HttpServletRequest request, String key) {\n Exception exception = (Exception) request.getSession().getAttribute(key); \n String error = \"\"; \n if (exception instanceof BadCredentialsException) { \n error = \"Invalid username and password!\"; \n } else if (exception instanceof LockedException) { \n error = exception.getMessage(); \n } else { \n error = \"Invalid username and password!\"; \n } \n return error;\n }\n}" }, { "code": null, "e": 38873, "s": 38666, "text": "index (\"/\") – This endpoint will serve the index page of our application. As we have configured earlier, we shall be protecting this page and allow only authenticated users will be able to access this page." }, { "code": null, "e": 39045, "s": 38873, "text": "login (\"/login\") – This will be used to serve our custom login page, as mentioned earlier. Any unauthenticated user will be redirected to this endpoint for authentication." }, { "code": null, "e": 39316, "s": 39045, "text": "register(\"/register\") (GET) – We will have two “register” endpoints for our application. One will be to serve the registration page. The other one will be to handle the registration process. So, the former one will use an Http GET and the latter will be a POST endpoint." }, { "code": null, "e": 39712, "s": 39316, "text": "register(\"/register\") (POST) – We will use this endpoint to handle the user registration process. We will get the user name and password from the parameters. Then we will encode the password using the passwordEncoder that we have @Autowired into this component. We also set user account as unlocked at this point. We will then save this user data in our users table with the createUser() method." }, { "code": null, "e": 39946, "s": 39712, "text": "In addition to the above, we have the getErrorMessage() method. It is used to determine the last thrown exception to add a message in our login template. This way, we can be aware of authentication errors and display proper messages." }, { "code": null, "e": 40021, "s": 39946, "text": "We have created our endpoints, the only thing left is to create our views." }, { "code": null, "e": 40247, "s": 40021, "text": "First, we will create our index page. This page will be accessible to users only on successful authentication. This page has access to the Servlet request object using which we can display the user name of the logged in user." }, { "code": null, "e": 40718, "s": 40247, "text": "<!DOCTYPE html> \n<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:th=\"https://www.thymeleaf.org\" xmlns:sec=\"https://www.thymeleaf.org/thymeleaf-extras-springsecurity3\"> \n <head> \n <title>\n Hello World!\n </title> \n </head>\n <body> \n <h1 th:inline=\"text\">Hello [[${#httpServletRequest.remoteUser}]]!</h1> \n <form th:action=\"@{/logout}\" method=\"post\"> \n <input type=\"submit\" value=\"Sign Out\"/> \n </form>\n </body> \n<html> " }, { "code": null, "e": 40954, "s": 40718, "text": "Next, we create our login view. This display our custom login form with the username and password fields. This view will also be rendered in case of a logout or failed authentication and will display appropriate messages for each case." }, { "code": null, "e": 41728, "s": 40954, "text": "<!DOCTYPE html> \n<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:th=\"https://www.thymeleaf.org\" xmlns:sec=\"https://www.thymeleaf.org/thymeleaf-extras-springsecurity3\"> \n <head> \n <title>Spring Security Example</title> \n </head> \n <body> \n <div th:if=\"${param.error}\"> \n <p th:text=\"${session.error}\" th:unless=\"${session == null}\">[...]</p> \n </div> \n <div th:if=\"${param.logout}\">You have been logged out.</div> \n <form th:action=\"@{/login}\" method=\"post>\n <div> \n <label> User Name : <input type=\"text\" name=\"username\" /> </label> \n </div> \n <div> \n <label> Password: <input type=\"password\" name=\"password\" /> </label> \n </div> \n <div> \n <input type=\"submit\" value=\"Sign In\" /> </div> \n </form> \n </body>\n</html>" }, { "code": null, "e": 41941, "s": 41728, "text": "Moving, we create our required view, the register view. This view will let users register themselves with the application. This user data will be stored in the database which will then be used for authentication." }, { "code": null, "e": 42750, "s": 41941, "text": "<!DOCTYPE html> \n<html> \n <head> \n <meta charset=\"ISO-8859-1\"> \n <title>Insert title here</title>\n </head> \n <body> \n <form action=\"/register\" method=\"post\"> \n <div class=\"container\"> \n <h1>Register</h1> \n <p>Please fill in this form to create an account.</p> \n <hr> \n\n <label for=\"username\">\n <b>Username</b>\n </label> \n <input type=\"text\" placeholder=\"Enter Username\" name=\"username\" id=\"username\" required> \n\n <label for=\"password\"><b>Password</b></label> \n <input type=\"password\" placeholder=\"Enter Password\" name=\"password\" id=\"password\" required> \n\n <button type=\"submit\" class=\"registerbtn\">Register</button> \n </div> \n\n </form> \n </body> \n</html>" }, { "code": null, "e": 42817, "s": 42750, "text": "Our final project structure should look something similar to this." }, { "code": null, "e": 42841, "s": 42817, "text": "Running the Application" }, { "code": null, "e": 42978, "s": 42841, "text": "We can then run the application as a SpringBootApp. When we go localhost:8080 on our browser it will redirect us back to the login page." }, { "code": null, "e": 43055, "s": 42978, "text": "On successful authentication it will take us the index view with a greeting." }, { "code": null, "e": 43239, "s": 43055, "text": "Since, we have allowed only three failed attempts before the account gets locked, so on the third failed authentication the user get locked and the message is displayed on the screen." }, { "code": null, "e": 43306, "s": 43239, "text": "On hitting the /register endpoint we can also register a new user." }, { "code": null, "e": 43317, "s": 43306, "text": "Conclusion" }, { "code": null, "e": 43679, "s": 43317, "text": "From today’s article, we have learned how to use a custom form for login using a database using an annotation-based configuration. We have also learned how to prevent multiple failed login attempts. While doing we have seen how we can implement our own AuthenticationProvider and UserDetailsService to authenticate users using our custom authentication process." }, { "code": null, "e": 43705, "s": 43679, "text": "Introduction and Overview" }, { "code": null, "e": 43739, "s": 43705, "text": "Getting Started (Practical Guide)" }, { "code": null, "e": 43914, "s": 43739, "text": "Spring Security comes with a ton of built-in features and tools for our convenience. In this example, we are going to discuss three of those interesting and useful features −" }, { "code": null, "e": 43925, "s": 43914, "text": "Form-login" }, { "code": null, "e": 43937, "s": 43925, "text": "Remember Me" }, { "code": null, "e": 43944, "s": 43937, "text": "Logout" }, { "code": null, "e": 44091, "s": 43944, "text": "Form-based login is one form of Username/password authentication that Spring Security provides support for. This is provided through an Html form." }, { "code": null, "e": 44408, "s": 44091, "text": "Whenever a user requests a protected resource, Spring Security checks for the authentication of the request. If the request is not authenticated/authorized, the user will be redirected to the login page. The login page must be somehow rendered by the application. Spring Security provides that login form by default." }, { "code": null, "e": 44499, "s": 44408, "text": "Moreover, any other configuration, if needed, must be explicitly provided as given below −" }, { "code": null, "e": 44670, "s": 44499, "text": "protected void configure(HttpSecurity http) throws Exception {\nhttp \n // ... \n .formLogin(\n form -> form .loginPage(\"/login\") \n .permitAll() \n ); \n}" }, { "code": null, "e": 45068, "s": 44670, "text": "This code requires a login.html file to be present in the templates folder which would be returned on hitting the /login. This HTML file should contain a login form. Furthermore, the request should be a post request to /login. The parameter names should be “username” and “password” for username and password respectively. In addition to this, a CSRF Token also needs to be included with the form." }, { "code": null, "e": 45144, "s": 45068, "text": "The above code snippet will be clearer once we are done with code exercise." }, { "code": null, "e": 45661, "s": 45144, "text": "This type of authentication requires a remember-me cookie to be sent to the browser. This cookie stores user information/authentication principal and it is stored in the browser. So, the website can remember the identity of the user next time when the session is started. Spring Security has the necessary implementations in place for this operation. One uses hashing to preserve the security of cookie-based tokens while the other uses a database or other persistent storage mechanism to store the generated tokens." }, { "code": null, "e": 45707, "s": 45661, "text": "The default URL /logout logs the user out by−" }, { "code": null, "e": 45737, "s": 45707, "text": "Invalidating the HTTP Session" }, { "code": null, "e": 45799, "s": 45737, "text": "Cleaning up any RememberMe authentication that was configured" }, { "code": null, "e": 45834, "s": 45799, "text": "Clearing the SecurityContextHolder" }, { "code": null, "e": 45860, "s": 45834, "text": "Redirect to /login?logout" }, { "code": null, "e": 45963, "s": 45860, "text": "WebSecurityConfigurerAdapter automatically applies logout capabilities to the Spring Boot application." }, { "code": null, "e": 46241, "s": 45963, "text": "Getting Started (Practical Guide) As usual, we shall start by going to start.spring.io. Here we choose a maven project. We name the project “formlogin” and choose the desired Java version. I am choosing Java 8 for this example. We also go on to add the following dependencies −" }, { "code": null, "e": 46252, "s": 46241, "text": "Spring Web" }, { "code": null, "e": 46268, "s": 46252, "text": "Spring Security" }, { "code": null, "e": 46278, "s": 46268, "text": "Thymeleaf" }, { "code": null, "e": 46299, "s": 46278, "text": "Spring Boot DevTools" }, { "code": null, "e": 46623, "s": 46299, "text": "Thymeleaf is a templating engine for Java. It allows us to quickly develop static or dynamic web pages for rendering in the browser. It is extremely extensible and allows us to define and customize the processing of our templates in fine detail. In addition to this, we can learn more about Thymeleaf by clicking this link." }, { "code": null, "e": 46910, "s": 46623, "text": "Let’s move on to generate our project and download it. We then extract it to a folder of our choice and use any IDE to open it. I shall be using Spring Tools Suite 4. It is available for free downloading from the https://spring.io/tools website and is optimized for spring applications." }, { "code": null, "e": 46992, "s": 46910, "text": "Let’s take a look at our pom.xml file. It should look something similar to this −" }, { "code": null, "e": 49201, "s": 46992, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion> \n <parent> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-starter-parent</artifactId> \n <version>2.3.1.RELEASE</version> \n <relativePath /> \n <!-- lookup parent from repository --> \n </parent> \n <groupId> com.spring.security</groupId> \n <artifactId>formlogin</artifactId> \n <version>0.0.1-SNAPSHOT</version> \n <name>formlogin</name> \n <description>Demo project for Spring Boot</description> \n \n <properties> \n <java.version>1.8</java.version> \n </properties> \n \n <dependencies> \n <dependency> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-starter-security</artifactId>\n </dependency> \n <dependency> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-starter-web</artifactId> \n </dependency> \n <dependency> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-starter-thymeleaf</artifactId> \n </dependency> \n <dependency> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-devtools</artifactId> \n </dependency> \n <dependency> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-starter-test</artifactId> \n <scope>test</scope> \n <exclusions> \n <exclusion> \n <groupId>org.junit.vintage</groupId>\n <artifactId>junit-vintage-engine</artifactId> \n </exclusion> \n </exclusions> \n </dependency> \n <dependency> \n <groupId>org.springframework.security</groupId> \n <artifactId>spring-security-test</artifactId> \n <scope>test</scope> \n </dependency> \n </dependencies> \n\n <build> \n <plugins> \n <plugin> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-maven-plugin</artifactId> \n </plugin> \n </plugins> \n </build>\n</project>" }, { "code": null, "e": 49466, "s": 49201, "text": "Let’s create a package in our folder /src/main/java under the default package. We shall be naming it as config as we would place all our configuration classes here. So, the name should look something similar to this – com.tutorial.spring.security.formlogin.config." }, { "code": null, "e": 51617, "s": 49466, "text": "package com.tutorial.spring.security.formlogin.config; \n\nimport java.util.List; \nimport org.springframework.beans.factory.annotation.Autowired; \nimport org.springframework.context.annotation.Bean; \nimport org.springframework.context.annotation.Configuration; \nimport org.springframework.security.config.annotation.web.builders.HttpSecurity; \nimport org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; \nimport org.springframework.security.core.userdetails.User; \nimport org.springframework.security.core.userdetails.UserDetails; \nimport org.springframework.security.core.userdetails.UserDetailsService; \nimport org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; \nimport org.springframework.security.crypto.password.NoOpPasswordEncoder; \nimport org.springframework.security.crypto.password.PasswordEncoder; \nimport org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.provisioning.UserDetailsManager;\nimport org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; \nimport org.springframework.security.web.util.matcher.AntPathRequestMatcher; \n\nimport com.spring.security.formlogin.AuthFilter;\n \n@Configuration \npublic class WebSecurityConfig extends WebSecurityConfigurerAdapter { \n \n @Bean \n protected UserDetailsService userDetailsService() {\n UserDetailsManager userDetailsManager = new InMemoryUserDetailsManager(); \n UserDetails user = User.withUsername(\"abby\") \n .password(passwordEncoder().encode(\"12345\")) \n .authorities(\"read\") .build(); \n userDetailsManager.createUser(user); \n return userDetailsManager; \n \n }\n @Bean \n public PasswordEncoder passwordEncoder() { \n return new BCryptPasswordEncoder(); }; \n @Override \n protected void configure(HttpSecurity http) throws Exception { \n http.csrf().disable() .authorizeRequests().anyRequest()\n .authenticated() .and() \n .formLogin() \n .and() \n .rememberMe() \n .and() .logout() .logoutUrl(\"/logout\") \n .logoutSuccessUrl(\"/login\") .deleteCookies(\"remember-me\"); \n } \n}" }, { "code": null, "e": 52036, "s": 51617, "text": "Inside of our config package, we have created the WebSecurityConfig class. This class extends the WebSecurityConfigurerAdapter of Spring Security. We shall be using this class for our security configurations, so let’s annotate it with an @Configuration annotation. As a result, Spring Security knows to treat this class a configuration class. As we can see, configuring applications have been made very easy by Spring." }, { "code": null, "e": 52082, "s": 52036, "text": "Let’s take a look at our configuration class." }, { "code": null, "e": 52453, "s": 52082, "text": "First, we shall create a bean of our UserDetailsService class by using the userDetailsService() method. We shall be using this bean for managing our users for this application. Here, to keep things simple, we shall use an InMemoryUserDetailsManager instance to create a user. This user, along with our given username and password, will contain a simple “read” authority." }, { "code": null, "e": 52665, "s": 52453, "text": "Now, let’s look at our PasswordEncoder. We shall be using a BCryptPasswordEncoder instance for this example. Hence, while creating the user, we used the passwordEncoder to encode our plaintext password like this" }, { "code": null, "e": 52711, "s": 52665, "text": ".password(passwordEncoder().encode(\"12345\"))\n" }, { "code": null, "e": 52995, "s": 52711, "text": "After the above steps, we move on to our next configuration. Here, we override the configure method of WebSecurityConfigurerAdapter class. This method takes HttpSecurity as a parameter. We shall be configuring this to use our form login and logout, as well as a remember-me function." }, { "code": null, "e": 53023, "s": 52995, "text": "Http Security Configuration" }, { "code": null, "e": 53145, "s": 53023, "text": "We can observe that all these functionalities are available in Spring Security. Let’s study the below section in detail −" }, { "code": null, "e": 53395, "s": 53145, "text": "http.csrf().disable() \n .authorizeRequests().anyRequest().authenticated() \n .and() \n .formLogin() \n .and() \n .rememberMe() \n .and() \n .logout()\n .logoutUrl(\"/logout\") .logoutSuccessUrl(\"/login\") .deleteCookies(\"remember-me\");" }, { "code": null, "e": 53433, "s": 53395, "text": "There are a few points to note here −" }, { "code": null, "e": 53597, "s": 53433, "text": "We have disabled csrf or Cross-Site Request Forgery protection As this is a simple application only for demonstration purposes, we can safely disable this for now." }, { "code": null, "e": 53786, "s": 53597, "text": "Then we add configuration which requires all requests to be authenticated. As we shall see later, we will have a single “/” endpoint for the index page of this application, for simplicity." }, { "code": null, "e": 53921, "s": 53786, "text": "After that, we shall be using the formLogin() functionality of Spring Security as mentioned above. This generates a simple login page." }, { "code": null, "e": 54015, "s": 53921, "text": "Then, we use the rememberMe() functionality of Spring Security. This will perform two things." }, { "code": null, "e": 54124, "s": 54015, "text": "Firstly, it will add a “Remember Me” checkbox to our default login form that we generated using formLogin()." }, { "code": null, "e": 54341, "s": 54124, "text": "And, secondly, ticking the checkbox generates the remember-me cookie. The cookie stores the identity of the user and the browser stores it. Spring Security detects the cookie in future sessions to automate the login." }, { "code": null, "e": 54422, "s": 54341, "text": "As a result, the user can access the application again without logging in again." }, { "code": null, "e": 54589, "s": 54422, "text": "And lastly, we have the logout() functionality. For this too, a default functionality has been provided by Spring security. Here it performs two important functions −" }, { "code": null, "e": 54661, "s": 54589, "text": "Invalidates the Http session, and unbinds objects bound to the session." }, { "code": null, "e": 54695, "s": 54661, "text": "It clears the remember-me cookie." }, { "code": null, "e": 54754, "s": 54695, "text": "Removes the authentication from Spring’s Security context." }, { "code": null, "e": 54907, "s": 54754, "text": "We also, provided a logoutSuccessUrl(), so that the application comes back to the login page after logout. This completes our application configuration." }, { "code": null, "e": 55026, "s": 54907, "text": "We shall now create a dummy index page now for the user to view when he logs in. It will also contain a logout button." }, { "code": null, "e": 55123, "s": 55026, "text": "In our /src/main/resources/templates, we add a index.html file.Then add some Html content to it." }, { "code": null, "e": 56425, "s": 55123, "text": "<!doctype html> \n<html lang=\"en\"> \n <head> \n <!-- Required meta tags -->\n <meta charset=\"utf-8\"> \n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> \n <!-- Bootstrap CSS --> \n <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css\" integrity=\"sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk\" crossorigin=\"anonymous\"> \n <title>Hello, world!</title> \n </head> \n <body> \n <h1>Hello, world!</h1> <a href=\"logout\">logout</a> \n <!-- Optional JavaScript --> \n <!-- jQuery first, then Popper.js, then Bootstrap JS --> \n <script src=\"https://code.jquery.com/jquery-3.5.1.slim.min.js\" integrity=\"sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj\" crossorigin=\"anonymous\"></script> \n <script src=\"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> \n <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js\"\n integrity=\"sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI\" crossorigin=\"anonymous\"></script> \n </body> \n</html>" }, { "code": null, "e": 56484, "s": 56425, "text": "This content is from Bootstrap 4 getting started template." }, { "code": null, "e": 56496, "s": 56484, "text": "We also add" }, { "code": null, "e": 56525, "s": 56496, "text": "<a href=\"logout\">logout</a>\n" }, { "code": null, "e": 56601, "s": 56525, "text": "to our file, so as the user can log out of the application using this link." }, { "code": null, "e": 56625, "s": 56601, "text": "The Resource Controller" }, { "code": null, "e": 56715, "s": 56625, "text": "We have created the protected resource, we now add the controller to serve this resource." }, { "code": null, "e": 56993, "s": 56715, "text": "package com.tutorial.spring.security.formlogin.controllers; \nimport org.springframework.stereotype.Controller; \nimport org.springframework.web.bind.annotation.GetMapping; \n@Controller public class AuthController { \n @GetMapping(\"/\") public String home() { return \"index\"; }\n}" }, { "code": null, "e": 57132, "s": 56993, "text": "As we can see, it is a very simple controller. It only has a get endpoint which serves our index.html file when the start our application." }, { "code": null, "e": 57380, "s": 57132, "text": "Let’s run the application as a Spring Boot Application. We can go to http://localhost:8080 on our browser when the application starts. It should ask us for username and password. Additionally, we shall also be able to see the remember-me checkbox." }, { "code": null, "e": 57633, "s": 57380, "text": "Now, if we provide the user information as we had configured in our WebSecurity config file, we shall be able to log in. Also, if we tick the remember-me checkbox, we shall be able to see the remember-me cookie in our browser’s developer tools section." }, { "code": null, "e": 57696, "s": 57633, "text": "As we can see the cookie is sent along with our login request." }, { "code": null, "e": 57847, "s": 57696, "text": "Also, included in the web page is a link for log out. On clicking the link, we shall be logged out of our application and sent back to our login page." }, { "code": null, "e": 57873, "s": 57847, "text": "Introduction and Overview" }, { "code": null, "e": 57894, "s": 57873, "text": "Spring Security Tags" }, { "code": null, "e": 57912, "s": 57894, "text": "The authorize Tag" }, { "code": null, "e": 57935, "s": 57912, "text": "The authentication tag" }, { "code": null, "e": 57953, "s": 57935, "text": "The csrfInput Tag" }, { "code": null, "e": 57974, "s": 57953, "text": "The csrfMetaTags Tag" }, { "code": null, "e": 58008, "s": 57974, "text": "Getting Started (Practical Guide)" }, { "code": null, "e": 58400, "s": 58008, "text": "In Spring MVC applications using JSP, we can use the Spring Security tags for applying security constraints as well as for accessing security information. Spring Security Tag library provides basic support for such operations. Using such tags, we can control the information displayed to the user based on his roles or permissions. Also, we can include CSRF protection features in our forms." }, { "code": null, "e": 58488, "s": 58400, "text": "To use Spring security tags, we must have the security taglib declared in our JSP file." }, { "code": null, "e": 58567, "s": 58488, "text": "<%@ taglib prefix=\"sec\" uri=\"http://www.springframework.org/security/tags\" %>\n" }, { "code": null, "e": 58664, "s": 58567, "text": "Now, we can use Spring Security tags with the “sec” prefix. Let’s now see the usage of the tags." }, { "code": null, "e": 58682, "s": 58664, "text": "The authorize Tag" }, { "code": null, "e": 58777, "s": 58682, "text": "The first tag we will be discussing is the authorize tag. Let’s check out some usage examples." }, { "code": null, "e": 58986, "s": 58777, "text": "<sec:authorize access=\"!isAuthenticated()\"> Login </sec:authorize> \n<sec:authorize access=\"isAuthenticated()\"> Logout </sec:authorize> \n<sec:authorize access=\"hasRole('ADMIN')\"> Hello Admin. </sec:authorize>\n" }, { "code": null, "e": 59171, "s": 58986, "text": "As we can see, we can use this tag to hide or show sections of information based on access or roles. To evaluate roles or access we also use the following Spring Security Expressions −" }, { "code": null, "e": 59248, "s": 59171, "text": "hasRole(“ADMIN”) − evaluates to true if the current user has the admin role." }, { "code": null, "e": 59325, "s": 59248, "text": "hasRole(“ADMIN”) − evaluates to true if the current user has the admin role." }, { "code": null, "e": 59420, "s": 59325, "text": "hasAnyRole(‘ADMIN’,’USER’) − evaluates to true if the current user has any of the listed roles" }, { "code": null, "e": 59515, "s": 59420, "text": "hasAnyRole(‘ADMIN’,’USER’) − evaluates to true if the current user has any of the listed roles" }, { "code": null, "e": 59590, "s": 59515, "text": "isAnonymous() − evaluates to true if the current user is an anonymous user" }, { "code": null, "e": 59665, "s": 59590, "text": "isAnonymous() − evaluates to true if the current user is an anonymous user" }, { "code": null, "e": 59742, "s": 59665, "text": "isRememberMe() − evaluates to true if the current user is a remember-me user" }, { "code": null, "e": 59819, "s": 59742, "text": "isRememberMe() − evaluates to true if the current user is a remember-me user" }, { "code": null, "e": 59939, "s": 59819, "text": "isFullyAuthenticated() − evaluates to true if the user is authenticated and is neither anonymous nor a remember-me user" }, { "code": null, "e": 60059, "s": 59939, "text": "isFullyAuthenticated() − evaluates to true if the user is authenticated and is neither anonymous nor a remember-me user" }, { "code": null, "e": 60415, "s": 60059, "text": "As we can see, the access attribute is where the web-security expression is specified. Then, Spring Security evaluates the expression The evaluation is generally delegated to SecurityExpressionHandler<FilterInvocation>, which is defined in the application context. If it returns true, then the user can get access to the information given in that section." }, { "code": null, "e": 60541, "s": 60415, "text": "If we use the authorize tag with Spring Security ‘s Permission Evaluator, we can also check user permissions as given below −" }, { "code": null, "e": 60719, "s": 60541, "text": "<sec:authorize access=\"hasPermission(#domain,'read') or hasPermission(#domain,'write')\">\n This content is visible to users who have read or write permission.\n</sec:authorize>\n" }, { "code": null, "e": 60809, "s": 60719, "text": "We can also allow or restrict the user from clicking on certain links within our content." }, { "code": null, "e": 60960, "s": 60809, "text": "<sec:authorize url=\"/admin\">\n This content will only be visible to users who are authorized to send requests to the \"/admin\" URL. \n</sec:authorize>\n" }, { "code": null, "e": 60983, "s": 60960, "text": "The authentication tag" }, { "code": null, "e": 61319, "s": 60983, "text": "When we want access to the current Authentication object stored in the Spring Security Context, we can use the authentication tag. Then we can use it to render properties of the object directly in our JSP page. For example, if we want to render the principal property of the Authentication object in our page, we can do it as follows −" }, { "code": null, "e": 61373, "s": 61319, "text": "<sec:authentication property=\"principal.username\" />\n" }, { "code": null, "e": 61391, "s": 61373, "text": "The csrfInput Tag" }, { "code": null, "e": 61598, "s": 61391, "text": "We can use the csrfInput tag to insert a hidden form field with the correct values for the CSRF protection token when CSRF protection is enabled. If CSRF protection is not enabled, this tag outputs nothing." }, { "code": null, "e": 61890, "s": 61598, "text": "We can place the tag within the HTML <form></form> block along with other input fields. However, we must not place the tag within the <form:form></form:form> block as Spring Security automatically inserts a CSRF form field within those tags and also takes care of Spring forms automatically." }, { "code": null, "e": 62040, "s": 61890, "text": "<form method=\"post\" action=\"/do/something\"> \n <sec:csrfInput /> \n Username:<br /> \n <input type=\"text\" username=\"username\" /> \n ... \n</form>\n" }, { "code": null, "e": 62061, "s": 62040, "text": "The csrfMetaTags Tag" }, { "code": null, "e": 62423, "s": 62061, "text": "We can use this tag to insert meta tags which contain the CSRF protection token form field and header names and CSRF protection token value. These meta tags can be useful for employing CSRF protection within Javascript in our application. However, this tag only works when we have enabled CSRF protection in our application, otherwise, this tag outputs nothing." }, { "code": null, "e": 62793, "s": 62423, "text": "<html> \n <head> \n <title>CSRF Protection in Javascript</title> \n <sec:csrfMetaTags /> \n <script type=\"text/javascript\" language=\"javascript\"> \n var csrfParam = $(\"meta[name='_csrf_param']\").attr(\"content\"); \n var csrfToken = $(\"meta[name='_csrf']\").attr(\"content\");\n </script> \n </head> \n <body> \n ... \n </body> \n</html>" }, { "code": null, "e": 62827, "s": 62793, "text": "Getting Started (Practical Guide)" }, { "code": null, "e": 63085, "s": 62827, "text": "Now that we have discussed the tags, let’s build an application to demonstrate the usage of the tags. We shall be using Spring Tool Suite 4 as our IDE. Additionally, we shall be using the Apache Tomcat server to serve our application. So, let’s get started." }, { "code": null, "e": 63112, "s": 63085, "text": "Setting up the Application" }, { "code": null, "e": 63231, "s": 63112, "text": "Let’s create a simple Maven Project in STS. We can name our application as taglibsdemo, and package it as a .war file." }, { "code": null, "e": 63324, "s": 63231, "text": "When we have finished setting up our application it should have a structure similar to this." }, { "code": null, "e": 63341, "s": 63324, "text": "The pom.xml file" }, { "code": null, "e": 63404, "s": 63341, "text": "We shall add these following dependencies to our application −" }, { "code": null, "e": 63419, "s": 63404, "text": "Spring Web MVC" }, { "code": null, "e": 63439, "s": 63419, "text": "Spring-Security-Web" }, { "code": null, "e": 63460, "s": 63439, "text": "Spring-Security-Core" }, { "code": null, "e": 63484, "s": 63460, "text": "Spring-Security-Taglibs" }, { "code": null, "e": 63507, "s": 63484, "text": "Spring-Security-Config" }, { "code": null, "e": 63525, "s": 63507, "text": "Javax Servlet Api" }, { "code": null, "e": 63530, "s": 63525, "text": "JSTL" }, { "code": null, "e": 63605, "s": 63530, "text": "After adding these dependencies, our pom.xml should look similar to this −" }, { "code": null, "e": 65926, "s": 63605, "text": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 \n https://maven.apache.org/xsd/maven-4.0.0.xsd\"> \n <modelVersion>4.0.0</modelVersion> \n <groupId>com.tutorial.spring.security</groupId> \n <artifactId>taglibsdemo</artifactId> \n <version>0.0.1-SNAPSHOT</version> \n <packaging>war</packaging> \n <properties> \n <maven.compiler.target>1.8</maven.compiler.target> \n <maven.compiler.source>1.8</maven.compiler.source> \n </properties> \n <dependencies> \n <dependency> \n <groupId>org.springframework</groupId> \n <artifactId>spring-webmvc</artifactId>\n <version>5.0.2.RELEASE</version> \n </dependency>\n <dependency> \n <groupId>org.springframework.security</groupId> \n <artifactId>spring-security-web</artifactId> \n <version>5.0.0.RELEASE</version>\n </dependency> \n <dependency> \n <groupId>org.springframework.security</groupId> \n <artifactId>spring-security-core</artifactId> \n <version>5.0.4.RELEASE</version> \n </dependency> \n <dependency> \n <groupId>org.springframework.security</groupId> \n <artifactId>spring-security-taglibs</artifactId> \n <version>5.0.4.RELEASE</version> \n </dependency> \n <dependency> \n <groupId>org.springframework.security</groupId> \n <artifactId>spring-security-config</artifactId> \n <version>5.0.4.RELEASE</version> \n </dependency>\n <dependency> \n <groupId>javax.servlet</groupId> \n <artifactId>javax.servlet-api</artifactId> \n <version>3.1.0</version> \n <scope>provided</scope> \n </dependency> <dependency> \n <groupId>javax.servlet</groupId> \n <artifactId>jstl</artifactId> \n <version>1.2</version> \n </dependency> \n </dependencies> \n <build> \n <plugins> \n <plugin> \n <groupId>org.apache.maven.plugins</groupId> \n <artifactId>maven-war-plugin</artifactId> \n <version>2.6</version> \n <configuration> \n <failOnMissingWebXml>false</failOnMissingWebXml> \n </configuration>\n </plugin> \n </plugins> \n </build> \n</project>" }, { "code": null, "e": 66161, "s": 65926, "text": "Let’s create our base package for the application. We can name it com.taglibsdemo. Within the package, let’s create another package for our configuration files. Since, it will be holding the configuration files, we can name it config." }, { "code": null, "e": 66184, "s": 66161, "text": "ApplicationConfig.java" }, { "code": null, "e": 66251, "s": 66184, "text": "Let’s create our first configuration class ApplicationConfig.java." }, { "code": null, "e": 67108, "s": 66251, "text": "package com.taglibsdemo.config; \n\nimport org.springframework.context.annotation.Bean; \nimport org.springframework.context.annotation.ComponentScan; \nimport org.springframework.context.annotation.Configuration; \nimport org.springframework.web.servlet.config.annotation.EnableWebMvc; \nimport org.springframework.web.servlet.view.InternalResourceViewResolver; \nimport org.springframework.web.servlet.view.JstlView; \n\n@EnableWebMvc \n@Configuration @ComponentScan({ \"com.taglibsdemo.controller\"} ) \npublic class ApplicationConfig { \n @Bean\n public InternalResourceViewResolver viewResolver() { \n InternalResourceViewResolver \n viewResolver = new InternalResourceViewResolver(); \n viewResolver.setViewClass(JstlView.class); \n viewResolver.setPrefix(\"/WEB-INF/views/\"); \n viewResolver.setSuffix(\".jsp\"); return viewResolver; \n }\n}" }, { "code": null, "e": 67141, "s": 67108, "text": "Let’s break down the code here −" }, { "code": null, "e": 67840, "s": 67141, "text": "@EnableWebMvc − We use @EnableWebMvc to enable Spring MVC. So, we add this annotation to an @Configuration class to import the Spring MVC configuration from WebMvcConfigurationSupport. WebMvcConfigurationSupport is the main class that provides the configuration for the MVC Java config. Not using this annotation may result in things like content-type and accept header, generally content negotiation not working. @EnableWebMvc registers a RequestMappingHandlerMapping, a RequestMappingHandlerAdapter, and an ExceptionHandlerExceptionResolver among others in support of processing requests with annotated controller methods using annotations such as @RequestMapping , @ExceptionHandler, and others." }, { "code": null, "e": 68224, "s": 67840, "text": "@Configuration − This annotation indicates that the class declares one or more @Bean methods and may be processed by the Spring IoC container to generate bean definitions and service requests for those beans at runtime. A @Configuration class is typically bootstrapped using either AnnotationConfigApplicationContext or its web-capable variant, AnnotationConfigWebApplicationContext." }, { "code": null, "e": 68486, "s": 68224, "text": "@ComponentScan − @ComponentScan annotation is used to tell Spring the packages to scan for annotated components. @ComponentScan also used to specify base packages and base package classes using thebasePackageClasses or basePackages attributes of @ComponentScan." }, { "code": null, "e": 68605, "s": 68486, "text": "InternalResourceViewResolver − To resolve the provided URI to the actual URI in the format prefix + viewname + suffix." }, { "code": null, "e": 68681, "s": 68605, "text": "setViewClass() − To set the view class that should be used to create views." }, { "code": null, "e": 68768, "s": 68681, "text": "setPrefix() − To set the prefix that gets prepended to view names when building a URL." }, { "code": null, "e": 68854, "s": 68768, "text": "setSuffix() − To set the suffix that gets appended to view names when building a URL." }, { "code": null, "e": 68877, "s": 68854, "text": "WebSecurityConfig.java" }, { "code": null, "e": 69012, "s": 68877, "text": "Next we shall create our WebSecurityConfig class which will extend the familiar WebSecurityConfigurerAdapter class of Spring Security." }, { "code": null, "e": 70709, "s": 69012, "text": "package com.taglibsdemo.config; \n\nimport org.springframework.context.annotation.Bean; \nimport org.springframework.context.annotation.ComponentScan; \nimport org.springframework.security.config.annotation.web.builders.HttpSecurity; \nimport org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; \nimport org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; \nimport org.springframework.security.core.userdetails.UserDetailsService; \nimport org.springframework.security.provisioning.InMemoryUserDetailsManager; \nimport org.springframework.security.web.util.matcher.AntPathRequestMatcher; \nimport org.springframework.security.core.userdetails.User; \nimport org.springframework.security.core.userdetails.User.UserBuilder;\n@EnableWebSecurity @ComponentScan(\"com.taglibsdemo\") \npublic class WebSecurityConfig extends WebSecurityConfigurerAdapter { \n @SuppressWarnings(\"deprecation\") @Bean \n public UserDetailsService userdetailsService() { \n UserBuilder users = User.withDefaultPasswordEncoder(); \n InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();\n manager.createUser(users.username(\"rony\").password(\"rony123\").roles(\"USER\").build()); \n manager.createUser(users.username(\"admin\").password(\"admin123\").roles(\"ADMIN\").build()); \n return manager; \n } \n @Override protected void configure(HttpSecurity http) throws Exception { \n http.authorizeRequests() .antMatchers(\"/index\", \"/\").permitAll()\n .antMatchers(\"/admin\", \"/user\").authenticated() .and() .formLogin() \n .and() .logout() .logoutRequestMatcher(\n new AntPathRequestMatcher(\"/logout\")\n ); \n }\n}" }, { "code": null, "e": 70742, "s": 70709, "text": "Let’s break the code down here −" }, { "code": null, "e": 70915, "s": 70742, "text": "WebSecurityConfigurerAdapter − The abstract class that implements WebSecurityConfigurer WebSecurityConfigurer and allows us to override methods for security configuration." }, { "code": null, "e": 71038, "s": 70915, "text": "@EnableWebSecurity − It enables Spring to automatically find and apply the @Configuration class to the global WebSecurity." }, { "code": null, "e": 71265, "s": 71038, "text": "We then create a UserDetailsService Bean using the method to create users using the InMemoryUserDetailsManager instance. We create two users – one with role “USER” and another with role “ADMIN” and add them to Spring Security." }, { "code": null, "e": 71514, "s": 71265, "text": "After that, we override the configure method with HttpSecurity as a parameter. We make our home page or index page accessible to all and admin page to be accessible when the user is authenticated. Next, we add Spring Security form login and logout." }, { "code": null, "e": 71622, "s": 71514, "text": "So, with those steps our security configuration is complete. Now, we are ready to move on to the next step." }, { "code": null, "e": 71664, "s": 71622, "text": "SpringSecurityApplicationInitializer.java" }, { "code": null, "e": 71833, "s": 71664, "text": "Moving on, now we shall create the SpringSecurityApplicationInitializer.java class which extends the AbstractSecurityWebApplicationInitializer class of Spring Security." }, { "code": null, "e": 72062, "s": 71833, "text": "package com.taglibsdemo.config;\nimport org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;\npublic class SpringSecurityApplicationInitializer extends \nAbstractSecurityWebApplicationInitializer { }\n" }, { "code": null, "e": 72319, "s": 72062, "text": "AbstractSecurityWebApplicationInitializer is an abstract class that implements Spring’s WebApplicationInitializer. So, SpringServletContainerInitializer will initialize the concrete implementations of this class if the classpath contains spring-web module." }, { "code": null, "e": 72353, "s": 72319, "text": "MvcWebApplicationInitializer.java" }, { "code": null, "e": 72901, "s": 72353, "text": "package com.taglibsdemo.config; \nimport org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; \npublic class MvcWebApplicationInitializer extends \nAbstractAnnotationConfigDispatcherServletInitializer { \n @Override protected Class</?>[] getRootConfigClasses() { \n return new Class[] {WebSecurityConfig.class}; \n }\n @Override protected Class</?>[] getServletConfigClasses() { \n return null; \n } \n @Override protected String[] getServletMappings() { \n return new String[] {\"/\"}; \n }\n}" }, { "code": null, "e": 73308, "s": 72901, "text": "AbstractAnnotationConfigDispatcherServletInitializer − This class extends WebApplicationInitializer. We need this class as a base class for initializing a Spring application in Servlet container environment.As a result, the subclass of AbstractAnnotationConfigDispatcherServletInitializer will provide the classes annotated with @Configuration, Servlet config classes and DispatcherServlet mapping pattern." }, { "code": null, "e": 73496, "s": 73308, "text": "getRootConfigClasses() − This method must be implemented by the class extending AbstractAnnotationConfigDispatcherServletInitializer. It provides “root” application context configuration." }, { "code": null, "e": 73625, "s": 73496, "text": "getServletConfigClasses() − This method too, must be implemented to provide DispatcherServlet application context configuration." }, { "code": null, "e": 73726, "s": 73625, "text": "getServletMappings() − This method is used specify the servlet mapping(s) for the DispatcherServlet." }, { "code": null, "e": 73829, "s": 73726, "text": "We have set up the configuration classes. Now , we shall create our controller to serve the JSP pages." }, { "code": null, "e": 73850, "s": 73829, "text": "HelloController.java" }, { "code": null, "e": 74249, "s": 73850, "text": "package com.taglibsdemo.controller;\nimport org.springframework.stereotype.Controller; \nimport org.springframework.web.bind.annotation.GetMapping; \n@Controller public class HelloController { \n@GetMapping(\"/\") \n public String index() { return \"index\"; } \n @GetMapping(\"/user\") \n public String user() { return \"admin\"; } \n @GetMapping(\"/admin\") \n public String admin() { return \"admin\"; } \n}" }, { "code": null, "e": 74415, "s": 74249, "text": "Here, we have created three endpoints – “/”, “/user”, and “/admin”. As specified in our configuration previously, we will allow unauthorized access to the index page" }, { "code": null, "e": 74507, "s": 74415, "text": "“/”. On the other hand, the “/user” and “/admin” endpoints would be authorized only access." }, { "code": null, "e": 74531, "s": 74507, "text": "Secure Content to serve" }, { "code": null, "e": 74634, "s": 74531, "text": "Moving on, we shall now create the JSP pages which are to be served on hitting the specific endpoints." }, { "code": null, "e": 74877, "s": 74634, "text": "For this, inside our src/main folder we create a folder called webapp. Inside this folder, we create our WEB-INF folder and further as in ApplicationConfig.java class we add the views folder. Here, in this folder we shall be adding the views." }, { "code": null, "e": 74925, "s": 74877, "text": "Let’s add our home page, i.e., index.jsp first." }, { "code": null, "e": 75287, "s": 74925, "text": "<%@ page language=\"java\" contentType=\"text/html;\n charset=ISO-8859-1\" pageEncoding=\"ISO-8859-1\"%> \n<!DOCTYPE html> \n<html> \n <head> \n <meta charset=\"ISO-8859-1\"> \n <title>Home Page</title> \n </head>\n <body> \n <a href=\"user\">User</a> \n <a href=\"admin\">Admin</a> \n <br> \n <br> Welcome to the Application! \n </body> \n</html>" }, { "code": null, "e": 75342, "s": 75287, "text": "Then we shall create our admin.jsp file. Let’s add it." }, { "code": null, "e": 75929, "s": 75342, "text": "<%@ page language=\"java\" contentType=\"text/html; \n charset=ISO-8859-1\" pageEncoding=\"ISO-8859-1\"%> \n<%@ taglib uri=\"http://www.springframework.org/security/tags\" prefix=\"security\"%> \n<!DOCTYPE html> \n<html> \n <head> \n <meta charset=\"ISO-8859-1\"> \n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"> \n <title>Insert title here</title> \n </head> \n <body> Welcome to Admin Page! <a href=\"logout\"> Logout </a> \n <br> \n <br> \n <security:authorize access=\"hasRole('ADMIN')\"> Hello Admin! \n </security:authorize> \n </body> \n</html>" }, { "code": null, "e": 76307, "s": 75929, "text": "here, we have added <%@ taglib uri=\"http://www.springframework.org/security/tags\" prefix=\"security\"%>. This is going to let us the Spring security tag libs as discussed before. As we can see, we have the added the “authorize” tag around the content. This content is will be only accessible by our admin. Any other user accessing this page will not be able to view this content." }, { "code": null, "e": 76331, "s": 76307, "text": "Running the application" }, { "code": null, "e": 76519, "s": 76331, "text": "We now right click on the project and choose Run On Server. When the server starts and our application is running we can go to localhost:8080/taglibsdemo/ on our browser to view the page." }, { "code": null, "e": 76530, "s": 76519, "text": "Login page" }, { "code": null, "e": 76613, "s": 76530, "text": "Now, if we click on the User link in our application, we shall be asked to log in." }, { "code": null, "e": 76820, "s": 76613, "text": "Here, as we can see in our controller, we are serving the admin page for bothe the user and admin links. But our user, if he is not an admin cannot view the content which is protected by our “authorize”tag." }, { "code": null, "e": 76852, "s": 76820, "text": "Let’s log in as the user first." }, { "code": null, "e": 76979, "s": 76852, "text": "We can see that the “Hello Admin!” content is not visible to us. This is because the current user doesn’t have the admin role." }, { "code": null, "e": 77017, "s": 76979, "text": "Let’s logout and log in as admin now." }, { "code": null, "e": 77117, "s": 77017, "text": "We are now able to see the protected content “Hello Admin!” as the current user has the admin role." }, { "code": null, "e": 77128, "s": 77117, "text": "Conclusion" }, { "code": null, "e": 77297, "s": 77128, "text": "We have learnt how we can use the Spring Security tag library to protect our content and get access to the current Authentication object in Our Spring Security Context." }, { "code": null, "e": 77310, "s": 77297, "text": "Fundamentals" }, { "code": null, "e": 77344, "s": 77310, "text": "Getting started (Practical Guide)" }, { "code": null, "e": 77589, "s": 77344, "text": "In this we are going to discuss how to configure Spring Security with XML configuration. We shall be developing a simple Spring application with Spring Security. While doing so, we will discuss in details about each component that we are using." }, { "code": null, "e": 77858, "s": 77589, "text": "Authentication − Authentication is ensuring the user or the client is who they claim to be. There are many ways in which Spring Security enables us to perform authentication. Spring Security supports Basic Authentication, LDAP authentication, JDBC authentication, etc." }, { "code": null, "e": 78312, "s": 77858, "text": "Authorization − Ensuring if the user has permission for the action. If our application is a complex one, with different kinds of users such as admins, regular users, other less privileged users, we need to maintain access control in our application. For example, a guest user should not be able to access admin content. So, to control access to various resources within our application, we need to check if a user has permission to access that resource." }, { "code": null, "e": 78756, "s": 78312, "text": "The above topics are the two main components of Spring Security. Spring security provided us with various in-built features to implement authentication and authorization in our application. We can use these features with our changes to secure an application very quickly. In addition to this, Spring Security also allows plenty of customizations to the features mentioned before to implement our own complex authentications and authorizations." }, { "code": null, "e": 79125, "s": 78756, "text": "Let’s look at a basic example using in-built Spring Security features. In this example, we shall be securing our application with options provided out-of-box by Spring security. This is will give us an idea of the various components of Spring Security and how we can use them for our application. We shall be using XML to configure our application’s Security features." }, { "code": null, "e": 79282, "s": 79125, "text": "The tools we shall be using for our application will be Spring Tool Suite 4 and Apache Tomcat Server 9.0. They are both available for free download and use." }, { "code": null, "e": 79540, "s": 79282, "text": "First, let’s start a new simple Maven Project in STS. We can choose group id, artifact id as per our choice. After that, we click on Finish. As a result, we have added our project to our workspace. Let’s give STS some time to build and validate our project." }, { "code": null, "e": 79598, "s": 79540, "text": "Our project structure would finally look similar to this." }, { "code": null, "e": 79683, "s": 79598, "text": "Next, let’s add the dependencies. We are going to choose the following dependencies." }, { "code": null, "e": 79698, "s": 79683, "text": "Spring Web MVC" }, { "code": null, "e": 79718, "s": 79698, "text": "Spring-Security-Web" }, { "code": null, "e": 79739, "s": 79718, "text": "Spring-Security-Core" }, { "code": null, "e": 79762, "s": 79739, "text": "Spring-Security-Config" }, { "code": null, "e": 79780, "s": 79762, "text": "Javax Servlet API" }, { "code": null, "e": 79788, "s": 79780, "text": "pom.xml" }, { "code": null, "e": 79897, "s": 79788, "text": "With these dependencies added, we are ready to configure our project. Let’s take a look at our pom.xml file." }, { "code": null, "e": 82010, "s": 79897, "text": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 \n https://maven.apache.org/xsd/maven-4.0.0.xsd> \n <modelVersion>4.0.0</modelVersion>\n <groupId>com.tutorial.spring.security</groupId> \n <artifactId>xmlconfigurationdemo</artifactId> \n <version>0.0.1-SNAPSHOT</version> \n <packaging>war</packaging> \n <name>Spring Security with XML configuration</name> <description>Spring Security with XML configuration</description> \n <properties> \n <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.source>1.8</maven.compiler.source> </properties> \n <dependencies> \n <dependency> \n <groupId>org.springframework</groupId> \n <artifactId>spring-webmvc</artifactId> \n <version>5.0.2.RELEASE<version> \n </dependency> <dependency> \n <groupId>org.springframework.security</groupId> \n <artifactId>spring-security-web</artifactId> \n <version>5.0.0.RELEASE</version> \n </dependency>\n <dependency> \n <groupId>org.springframework.security</groupId> \n <artifactId>spring-security-core</artifactId> \n <version>5.0.0.RELEASE</version> \n </dependency> \n <dependency> \n <groupId>org.springframework.security</groupId> \n <artifactId>spring-security-config</artifactId> \n <version>5.0.0.RELEASE</version> \n </dependency> \n <dependency> \n <groupId>javax.servlet</groupId> \n <artifactId>javax.servlet-api</artifactId> \n <version>3.1.0</version> \n <scope>provided</scope> \n </dependency> \n </dependencies> \n <build> \n <plugins> \n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-war-plugin</artifactId>\n <version>2.6</version> \n <configuration>\n <failOnMissingWebXml>false</failOnMissingWebXml> \n </configuration> \n </plugin> \n </plugins> \n </build> \n</project>" }, { "code": null, "e": 82031, "s": 82010, "text": "Controller and views" }, { "code": null, "e": 82171, "s": 82031, "text": "First, We are going to create our controller. So, let’s create a package called controller and add our HomeController class to the package." }, { "code": null, "e": 82589, "s": 82171, "text": "package com.tutorial.spring.security.xmlconfigurationdemo.controller; \nimport org.springframework.stereotype.Controller; \nimport org.springframework.web.bind.annotation.RequestMapping; \nimport org.springframework.web.bind.annotation.RequestMethod; \n@Controller public class HomeController { @GetMapping(\"/\")\npublic String index() { return \"index\"; } \n@GetMapping(\"/admin\") \npublic String admin() { return \"admin\"; } }" }, { "code": null, "e": 82725, "s": 82589, "text": "Here, we have two endpoints – “index” and “admin”. While the index page is will be accessible to all, we will protect our “admin” page." }, { "code": null, "e": 82786, "s": 82725, "text": "Since, we have created the routes, let’s also add the pages." }, { "code": null, "e": 82941, "s": 82786, "text": "In our /src/main/webapp folder, let’s create a folder called WEB-INF. Then inside it, we will create a folder called views where we will create our views." }, { "code": null, "e": 82970, "s": 82941, "text": "Let’s create our first view−" }, { "code": null, "e": 83259, "s": 82970, "text": "<%@ page language=\"java\" contentType=\"text/html; \ncharset=ISO-8859-1\" pageEncoding=\"ISO-8859-1\"%> \n<!DOCTYPE html> \n<html> \n <head> \n <meta charset=\"ISO-8859-1\"> <title>Insert title here</title> \n </head> \n <body> \n <h2>Welcome to Spring Security!</h2>\n </body> \n</html>" }, { "code": null, "e": 83290, "s": 83259, "text": "Then we create our admin view." }, { "code": null, "e": 83553, "s": 83290, "text": "<%@ page language=\"java\" contentType=\"text/html; charset=ISO-8859-1\" pageEncoding=\"ISO-8859-1\"%> \n<DOCTYPE html> \n<html> \n <head> \n <meta charset=\"ISO-8859-1\"> <title>Insert title here</title> \n </head> \n <body> \n Hello Admin \n </body> \n</html>" }, { "code": null, "e": 83597, "s": 83553, "text": "Moving on, let’s configure our application." }, { "code": null, "e": 83613, "s": 83597, "text": "Configurations." }, { "code": null, "e": 83621, "s": 83613, "text": "web.xml" }, { "code": null, "e": 83675, "s": 83621, "text": "Now, let’s add our first xml file – the web.xml file." }, { "code": null, "e": 85038, "s": 83675, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n<!DOCTYPE xml> \n<web-app xmlns=\"http://xmlns.jcp.org/xml/ns/javaee\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation=\"http://xmlns.jcp.org/xml/ns/javaee \n http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd\" version=\"3.1\"> <servlet> \n <servlet-name>spring</servlet-name> \n <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> \n <init-param> \n <param-name>contextConfigLocation</param-name> \n <param-value>/WEB-INF/app-config.xml</param-value> \n </init-param> \n <load-on-startup>1</load-on-startup> \n </servlet> \n <servlet-mapping> \n <servlet-name>spring</servlet-name> \n <url-pattern>/</url-pattern> \n </servlet-mapping> \n <listener> \n <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>\n </listener> \n <context-param> \n <param-name>contextConfigLocation</param-name> \n <param-value> /WEB-INF/security-config.xml </param-value> \n </context-param> \n <filter> \n <filter-name>springSecurityFilterChain</filter-name> \n <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> \n </filter> \n <filter-mapping> \n <filter-name>springSecurityFilterChain</filter-name> \n <url-pattern>/*</url-pattern> \n </filter-mapping> \n</web-app>" }, { "code": null, "e": 85053, "s": 85038, "text": "Code breakdown" }, { "code": null, "e": 85623, "s": 85053, "text": "Dispatcher Servlet − The first servlet we have declared here is the Dispatcher servlet. The dispatcher servlet is the entry point of any Spring MVC application and is at the core of the entire Spring MVC framework design. It intercepts all HTTP requests and dispatches them to registered handlers for processing a web request. It also provides convenient mapping and exception handling facilities. The order in which servlets are loaded depends on “load-on-startup” value. Servlets with a lower value of “load-on-startup” are loaded before the ones with a higher value." }, { "code": null, "e": 85788, "s": 85623, "text": "contextConfigLocation − It is a string that indicates where context(s) can be found. This string represents a path to a file where our configurations can be loaded." }, { "code": null, "e": 85976, "s": 85788, "text": "servlet-mapping − We use Servlet Mapping to tell Spring Container which request to route to which servlet. In our case, we are routing all our requests to our “spring” Dispatcher servlet." }, { "code": null, "e": 86356, "s": 85976, "text": "listener − The classes that listen to certain types of events, and trigger an appropriate functionality when that event occurs. Each listener is bound to an event. In our case, we will create a root web-application context for the web-application with the ContextLoaderListener. This is then put in the ServletContext that can be used to load and unload the spring-managed beans." }, { "code": null, "e": 86900, "s": 86356, "text": "filter − Spring uses Filters to process requests before handing them over to the Dispatcher Servlet and also used to process responses after they are dispatched. The DelegatingFilterProxy links the application context to the web.xml file. The requests that are coming to this application will pass through our filter which we named “spring SecurityFilterChain” before they reach their controllers. This is where Spring Security can take over the request and perform operations on it before passing it on to the next set of filters or handlers." }, { "code": null, "e": 86920, "s": 86900, "text": "security-config.xml" }, { "code": null, "e": 86970, "s": 86920, "text": "Next we will create our security-config.xml file." }, { "code": null, "e": 87953, "s": 86970, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n<beans:beans xmlns=\"http://www.springframework.org/schema/security\" \nxmlns:beans=\"http://www.springframework.org/schema/beans\" \nxmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \nxsi:schemaLocation=\"http://www.springframework.org/schema/beans \nhttp://www.springframework.org/schema/beans/spring-beans.xsd \nhttp://www.springframework.org/schema/security \nhttp://www.springframework.org/schema/security/spring-security.xsd\"> \n<http auto-config=\"true\"> \n<intercept-url pattern=\"/admin\"\naccess=\"hasRole('ROLE_ADMIN')\" /> </http> \n<authentication-manager> \n<authentication-provider> \n <user-service> \n <user name=\"admin\" password=\"{noop}1234\" authorities=\"ROLE_ADMIN\" /> \n </user-service> \n </authentication-provider> </authentication-manager> \n <beans:bean id =\"passwordEncoder\" \n class = \"org.springframework.security.crypto.password.NoOpPasswordEncoder\" \n factory-method = \"getInstance\">\n </beans:bean> \n</beans:beans>" }, { "code": null, "e": 87968, "s": 87953, "text": "Code breakdown" }, { "code": null, "e": 88173, "s": 87968, "text": "http element − The parent of all web-related namespace functionality. Here, we can configure which URLs to intercept, what permissions are required, which type of login to use, and all such configuration." }, { "code": null, "e": 88375, "s": 88173, "text": "auto-config − Setting this attribute to true automatically sets up form-login, basic login, and logout functionalities. Spring Security generates them by using standard values and the features enabled." }, { "code": null, "e": 88477, "s": 88375, "text": "intercept-url − It sets the pattern of the URLs that we want to protecte, using the access attribute." }, { "code": null, "e": 88680, "s": 88477, "text": "access − It specifies which users are permitted to access the URL specified by the pattern attribute. It is done on the basis of the roles and permissions of a user. We can use SPEL with this attribute." }, { "code": null, "e": 89214, "s": 88680, "text": "authentication-manager − The <authentication-manager> is used to configure users, their passwords, and roles in the application. These users will be one who can access the protected parts of the application given they have the appropriate roles. A DaoAuthenticationProvider bean will be created by the <authentication-provider< and the <user-service< element will create an InMemoryDaoImpl. All authentication-provider elements will allow the users to be authenticated by providing the user information to the authentication-manager." }, { "code": null, "e": 89342, "s": 89214, "text": "password-encoder − This will register a password encoder bean. To keep things simple here we have used the NoOpPasswordEncoder." }, { "code": null, "e": 89490, "s": 89342, "text": "Moving on we create out last configuration file – the app-config file. Here we are going to add our view resolver code and define our base package." }, { "code": null, "e": 89505, "s": 89490, "text": "app-config.xml" }, { "code": null, "e": 90613, "s": 89505, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n<beans xmlns=\"http://www.springframework.org/schema/beans\" \n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n xmlns:mvc=\"http://www.springframework.org/schema/mvc\" \n xmlns:context=\"http://www.springframework.org/schema/context\" xsi:schemaLocation=\" \n http://www.springframework.org/schema/mvc \n http://www.springframework.org/schema/mvc/spring-mvc.xsd \n http://www.springframework.org/schema/beans \n http://www.springframework.org/schema/beans/spring-beans.xsd \n http://www.springframework.org/schema/context \n http://www.springframework.org/schema/context/spring-context.xsd\"> \n <mvc:annotation-driven /> \n <context:component-scan\n base-package=\"com.tutorial.spring.security.xmlconfigurationdemo.controller\"> \n </context:component-scan> \n <context:annotation-config>\n </context:annotation-config> \n <bean class=\"org.springframework.web.servlet.view.InternalResourceViewResolver\"> \n <property name=\"prefix\" value=\"/WEB-INF/views/\"></property> \n <property name=\"suffix\" value=\".jsp\"></property> \n </bean> \n</beans>" }, { "code": null, "e": 90800, "s": 90613, "text": "Here, as we can see we are registering our views that we created earlier. For this, we are using the InternalResourceViewResolver class which will map the provided URI to the actual URI." }, { "code": null, "e": 90926, "s": 90800, "text": "For example, using the above configuration, if we request the URI “/admin“, DispatcherServlet will forward the request to the" }, { "code": null, "e": 90986, "s": 90926, "text": "prefix + viewname + suffix = /WEB-INF/views/admin.jsp view." }, { "code": null, "e": 91010, "s": 90986, "text": "Running the application" }, { "code": null, "e": 91286, "s": 91010, "text": "With this simple configuration, we have our application ready to be served. We can right-click on the project and choose Run on Server. We can choose our Tomcat server. When the server starts, we can go to localhost:8080/xmlconfigurationdemo to interact with our application." }, { "code": null, "e": 91378, "s": 91286, "text": "If, we enter the correct credentials we shall be able to login and see our desired content." }, { "code": null, "e": 91400, "s": 91378, "text": "OAuth2.0 Fundamentals" }, { "code": null, "e": 91442, "s": 91400, "text": "OAuth2.0 Getting started(Practical Guide)" }, { "code": null, "e": 92035, "s": 91442, "text": "OAuth 2.0 was developed by IETF OAuth Working Group and published in October of 2012. It serves as an open authorization protocol for enabling a third party application to get limited access to an HTTP service on behalf of the resource owner. It can do so while not revealing the identity or the long-term credentials of the user. A third-party application itself can also use it on its behalf. The working principle of OAuth consists of the delegation of user authentication to a service hosting the user account and authorizing the third-party application access to the account of the user." }, { "code": null, "e": 92651, "s": 92035, "text": "Let us consider an example. Let us say we want to login to a website “clientsite.com”. We can sign in via Facebook, Github, Google or Microsoft. We select any options of the options given above, and we are redirected to the respective website for login. If login is successful, we are asked if we want to give clientsite.com access to the specific data requested by it. We select our desired option and we are redirected to clientsite.com with an authorization code or error code and our login is successful or not depending on our action in the third-party resource. This is the basic working principle of OAuth 2." }, { "code": null, "e": 92728, "s": 92651, "text": "There are five key actors involved in an OAuth system. Let’s list them out −" }, { "code": null, "e": 92870, "s": 92728, "text": "User / Resource Owner − The end-user, who is responsible for the authentication and for providing consent to share resources with the client." }, { "code": null, "e": 93012, "s": 92870, "text": "User / Resource Owner − The end-user, who is responsible for the authentication and for providing consent to share resources with the client." }, { "code": null, "e": 93055, "s": 93012, "text": "User-Agent − The browser used by the User." }, { "code": null, "e": 93098, "s": 93055, "text": "User-Agent − The browser used by the User." }, { "code": null, "e": 93151, "s": 93098, "text": "Client − The application requesting an access token." }, { "code": null, "e": 93204, "s": 93151, "text": "Client − The application requesting an access token." }, { "code": null, "e": 93351, "s": 93204, "text": "Authorization Server − The server that is used to authenticate the user/client. It issues access tokens and tracks them throughout their lifetime." }, { "code": null, "e": 93498, "s": 93351, "text": "Authorization Server − The server that is used to authenticate the user/client. It issues access tokens and tracks them throughout their lifetime." }, { "code": null, "e": 93631, "s": 93498, "text": "Resource Server − The API that provides access to the requested resource. It validates the access tokens and provides authorization." }, { "code": null, "e": 93764, "s": 93631, "text": "Resource Server − The API that provides access to the requested resource. It validates the access tokens and provides authorization." }, { "code": null, "e": 94075, "s": 93764, "text": "We will be developing a Spring Boot Application with Spring Security and OAuth 2.0 to illustrate the above. We will be developing a basic application with an in-memory database to store user credentials now. The application will make it easy for us to understand the workings of OAuth 2.0 with Spring Security." }, { "code": null, "e": 94246, "s": 94075, "text": "Let’s use the Spring initializer to create a maven project in Java 8. Let’s start by going to start.spring.io. We generate an application with the following dependencies−" }, { "code": null, "e": 94257, "s": 94246, "text": "Spring Web" }, { "code": null, "e": 94273, "s": 94257, "text": "Spring Security" }, { "code": null, "e": 94286, "s": 94273, "text": "Cloud OAuth2" }, { "code": null, "e": 94307, "s": 94286, "text": "Spring Boot Devtools" }, { "code": null, "e": 94656, "s": 94307, "text": "With the above configuration, we click on the Generate button to generate a project. The project will be downloaded in a zip file. We extract the zip to a folder. We can then open the project in an IDE of our choice. I am using Spring Tools Suite here as it is optimized for spring applications. We can also use Eclipse or IntelliJ Idea as we wish." }, { "code": null, "e": 94836, "s": 94656, "text": "So, we open the project in STS, let the dependencies get downloaded. Then we can see the project structure in our package explorer window. It should resemble the screenshot below." }, { "code": null, "e": 94971, "s": 94836, "text": "If we open the pom.xml file we can view the dependencies and other details related to the project. It should look something like this." }, { "code": null, "e": 97724, "s": 94971, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 \n https://maven.apache.org/xsd/maven-4.0.0.xsd\"> \n <modelVersion>4.0.0</modelVersion> \n <parent> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-starter-parent</artifactId> \n <version>2.3.1.RELEASE</version> \n <relativePath/> <!-- lookup parent from repository -->\n </parent> \n <groupId>com.tutorial</groupId> \n <artifactId>spring.security.oauth2</artifactId> \n <version>0.0.1-SNAPSHOT</version> \n <name>spring.security.oauth2</name> \n <description>Demo project for Spring Boot</description> \n <properties> \n <java.version>1.8</java.version> \n <spring-cloud.version>Hoxton.SR6</spring-cloud.version> \n </properties> \n <dependencies> \n <dependency> \n <groupId>org.springframework.boot<groupId> \n <artifactId>spring-boot-starter-security</artifactId> \n </dependency> \n <dependency> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-starter-web</artifactId> \n </dependency> \n <dependency>\n <groupId>org.springframework.cloud</groupId> \n <artifactId>spring-cloud-starter-oauth2</artifactId> \n </dependency> \n <dependency> \n <groupId>org.springframework.boot<groupId> \n <artifactId>spring-boot-devtools</artifactId>\n <scope>runtime</scope> \n <optional>true</optional> \n </dependency> \n <dependency> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-starter-test</artifactId> \n <scope>test</scope> <exclusions> <exclusion> \n <groupId>org.junit.vintage</groupId> \n <artifactId>junit-vintage-engine</artifactId> \n </exclusion> \n </exclusions> \n <dependency> \n <dependency>\n <groupId>org.springframework.security</groupId> \n <artifactId>spring-security-test</artifactId> \n <scope>test</scope> \n </dependency> \n </dependencies> \n <dependencyManagement> \n <dependencies> \n <dependency> \n <groupId>org.springframework.cloud</groupId> \n <artifactId>spring-cloud-dependencies</artifactId> \n <version>${spring-cloud.version}</version> \n <type>pom</type> \n <scope>import</scope> \n </dependency> \n </dependencies> \n </dependencyManagement><build> \n <plugins> \n <plugin>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-maven-plugin</artifactId> \n </plugin> \n </plugins> \n </build> \n</project>" }, { "code": null, "e": 97895, "s": 97724, "text": "Now, to the base package of our application, i.e., com.tutorial.spring.security.oauth2, let’s add a new package named config where we shall add our configuration classes." }, { "code": null, "e": 98171, "s": 97895, "text": "Let’s create our first configuration class, UserConfig which extends the WebSecurityConfigurerAdapter class of Spring Security to manage the users of the client application. We annotate the class with @Configuration annotation to tell Spring that it is a configuration class." }, { "code": null, "e": 99774, "s": 98171, "text": "package com.tutorial.spring.security.oauth2.config; \nimport org.springframework.context.annotation.Bean; \nimport org.springframework.context.annotation.Configuration; \nimport org.springframework.security.authentication.AuthenticationManager; \nimport org.springframework.security.config.annotation.web.builders.HttpSecurity; \nimport org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; \nimport org.springframework.security.core.userdetails.User; \nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.security.core.userdetails.UserDetailsService; \nimport org.springframework.security.crypto.password.NoOpPasswordEncoder; \nimport org.springframework.security.crypto.password.PasswordEncoder; \nimport org.springframework.security.provisioning.InMemoryUserDetailsManager; \nimport org.springframework.security.provisioning.UserDetailsManager; \n@Configuration public class UserConfig extends WebSecurityConfigurerAdapter { \n @Bean \n public UserDetailsService userDetailsService() {\n UserDetailsManager userDetailsManager = new InMemoryUserDetailsManager(); \n UserDetails user = User.withUsername(\"john\") \n .password(\"12345\") .authorities(\"read\") \n .build(); userDetailsManager.createUser(user); return userDetailsManager; \n } \n @Bean\n public PasswordEncoder passwordEncoder() { \n return NoOpPasswordEncoder.getInstance(); \n } \n @Override \n @Bean \n public AuthenticationManager authenticationManagerBean() throws Exception { \n return super.authenticationManagerBean(); \n } \n}" }, { "code": null, "e": 100624, "s": 99774, "text": "We then add a bean of the UserDetailsService to retrieve the user details for authentication and authorization. To put it in the Spring context we annotate it with @Bean. To keep this tutorial simple and easy to understand, we use an InMemoryUserDetailsManager instance. For a real-world application, we can use other implementations like JdbcUserDetailsManager to connect to a database and so on. To be able to create users easily for this example we use the UserDetailsManager interface which extends the UserDetailsService and has methods like createUser(), updateUser() and so on. Then, we create a user using the builder class. We give him a username, password and a “read” authority for now. Then, using the createUser() method, we add the newly created user and return the instance of UserDetailsManager thus putting it in the Spring context." }, { "code": null, "e": 101323, "s": 100624, "text": "To be able to use the UserDetailsService defined by us, it is necessary to provide a PasswordEncoder bean in the Spring context. Again, to keep it simple for now we use the NoOpPasswordEncoder. The NoOpPasswordEncoder should not be used otherwise for real-world applications for production as it is not secure. NoOpPasswordEncoder does not encode the password and is only useful for developing or testing scenarios or proof of concepts. We should always use the other highly secure options provided by Spring Security, the most popular of which is the BCryptPasswordEncoder, which we will be using later in our series of tutorials. To put it in the Spring context we annotate the method with @Bean." }, { "code": null, "e": 101514, "s": 101323, "text": "We then override the AuthenticationManager bean method of WebSecurityConfigurerAdapter, which returns the authenticationManagerBean to put the authentication manager into the Spring context." }, { "code": null, "e": 102061, "s": 101514, "text": "Now, to add the client configurations we add a new configuration class named AuthorizationServerConfig which extends AuthorizationServerConfigurerAdapter class of Spring Security. The AuthorizationServerConfigurerAdapter class is used to configure the authorization server using the spring security oauth2 module. We annotate this class with @Configuration as well. To add the authorization server functionality to this class we need to add the @EnableAuthorizationServer annotation so that the application can behave as an authorization server." }, { "code": null, "e": 103369, "s": 102061, "text": "package com.tutorial.spring.security.oauth2.config; \nimport org.springframework.beans.factory.annotation.Autowired; \nimport org.springframework.context.annotation.Configuration; \nimport org.springframework.security.authentication.AuthenticationManager; \nimport org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; \nimport org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; \nimport org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; \nimport org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; @Configuration @EnableAuthorizationServer \npublic class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {\n @Autowired private AuthenticationManager authenticationManager; \n @Override \n public void configure(ClientDetailsServiceConfigurer clients) throws Exception { \n clients.inMemory() .withClient(\"oauthclient1\") .secret(\"oauthsecret1\") .scopes(\"read\") .authorizedGrantTypes(\"password\") } \n @Override \n public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { \n endpoints.authenticationManager(authenticationManager); \n } \n}" }, { "code": null, "e": 103620, "s": 103369, "text": "For checking oauth tokens, Spring Security oauth exposes two endpoints – /oauth/check_token and /oauth/token_key. These endpoints are protected by default behind denyAll(). tokenKeyAccess() and checkTokenAccess() methods open these endpoints for use." }, { "code": null, "e": 103753, "s": 103620, "text": "We autowire the AuthenticationManager bean we configured in the UserConfig class as a dependency here which we shall be using later." }, { "code": null, "e": 104375, "s": 103753, "text": "We then override two of the configure() methods of the AuthorizationServerConfigurerAdapter to provide an in-memory implementation of the client details service. The first method which uses the ClientDetailsServiceConfigurer as a parameter, as the name suggests, allows us to configure the clients for the authorization server. These clients represent the applications that will be able to use the functionality of this authorization server. Since this is a basic application for learning the implementation of OAuth2, we will keep things simple for now and use an in-memory implementation with the following attributes −" }, { "code": null, "e": 104418, "s": 104375, "text": "clientId − the id of the client. Required." }, { "code": null, "e": 104461, "s": 104418, "text": "clientId − the id of the client. Required." }, { "code": null, "e": 104518, "s": 104461, "text": "secret − the client secret, required for trusted clients" }, { "code": null, "e": 104575, "s": 104518, "text": "secret − the client secret, required for trusted clients" }, { "code": null, "e": 104721, "s": 104575, "text": "scope − the limiting scope of the client, in other words, client permissions. If left empty or undefined, the client is not limited by any scope." }, { "code": null, "e": 104867, "s": 104721, "text": "scope − the limiting scope of the client, in other words, client permissions. If left empty or undefined, the client is not limited by any scope." }, { "code": null, "e": 105176, "s": 104867, "text": "authorizedGrantTypes − the grant types that the client is authorized to use. The grant type denotes the way by which the client obtains the token from the authorization server. We will be using the “password” grant type as it is the simplest. Later, we shall be using another grant type for another use-case." }, { "code": null, "e": 105485, "s": 105176, "text": "authorizedGrantTypes − the grant types that the client is authorized to use. The grant type denotes the way by which the client obtains the token from the authorization server. We will be using the “password” grant type as it is the simplest. Later, we shall be using another grant type for another use-case." }, { "code": null, "e": 105730, "s": 105485, "text": "In “password” authorization grant type, the user needs to provide his/her username, password and scope to our client application, which then uses those credentials along with its credentials for the authorization server we want the tokens from." }, { "code": null, "e": 105920, "s": 105730, "text": "The other configure() method that we overrode, uses AuthorizationServerEndpointsConfigurer as a parameter, is used to attach the AuthenticationManager to authorization server configuration." }, { "code": null, "e": 106124, "s": 105920, "text": "With these basic configurations, our Authorization server is ready to use. Let’s go ahead and start it and use it. We will be using Postman ( https://www.postman.com/downloads/ ) for making our requests." }, { "code": null, "e": 106398, "s": 106124, "text": "When using STS, we can launch our application and start seeing see the logs in our console. When the application starts, we can find the oauth2 endpoints exposed by our application in the console. Of those endpoints, we will be using the following the below token for now −" }, { "code": null, "e": 106438, "s": 106398, "text": "/oauth/token – for obtaining the token." }, { "code": null, "e": 106533, "s": 106438, "text": "If we check the postman snapshot here, we can notice a few things. Let’s list them down below." }, { "code": null, "e": 106774, "s": 106533, "text": "The URL − Our Spring Boot Application is running at port 8080 of our local machine, so the request is pointed to http://localhost:8080. The next part is /oauth/token, which we know, is the endpoint exposed by OAuth for generating the token." }, { "code": null, "e": 107049, "s": 106774, "text": "The query params− Since this is a “password” authorization grant type, the user needs to provide his/her username, password and scope to our client application, which then uses those credentials along with its credentials to the authorization server we want the tokens from." }, { "code": null, "e": 107316, "s": 107049, "text": "Client Authorization − The Oauth system requires the client to be authorized to be able to provide the token. Hence, under the Authorization header, we provide the client authentication information, namely username and password that we configured in our application." }, { "code": null, "e": 107392, "s": 107316, "text": "Let’s take a closer look at the query params and the authorization header −" }, { "code": null, "e": 107409, "s": 107392, "text": "The query params" }, { "code": null, "e": 107428, "s": 107409, "text": "Client credentials" }, { "code": null, "e": 107542, "s": 107428, "text": "If everything is correct, we shall be able to see our generated token in the response along with a 200 ok status." }, { "code": null, "e": 107555, "s": 107542, "text": "The response" }, { "code": null, "e": 107725, "s": 107555, "text": "We can test our server, by putting wrong credentials or no credentials, and we will get back an error which would say the request is unauthorized or has bad credentials." }, { "code": null, "e": 107841, "s": 107725, "text": "This is our basic oauth authorization server, that uses the password grant type to generate and provide a password." }, { "code": null, "e": 108039, "s": 107841, "text": "Next, let’s implement a more secure, and a more common application of the oauth2 authentication, i.e. with an authorization code grant type. We will update our current application for this purpose." }, { "code": null, "e": 108611, "s": 108039, "text": "The authorization grant type is different from the password grant type in the sense that the user doesn’t have to share his credentials with the client application. He shares them with the authorization server only and in return authorization code is sent to the client which it uses to authenticate the client. It is more secure than the password grant type as user credentials are not shared with the client application and hence the user’s information stays safe. The client application doesn’t get access to any important user information unless approved by the user." }, { "code": null, "e": 108737, "s": 108611, "text": "In a few simple steps, we can set up a basic oauth server with an authorization grant type in our application. Let’s see how." }, { "code": null, "e": 110252, "s": 108737, "text": "package com.tutorial.spring.security.oauth2.config; \nimport org.springframework.beans.factory.annotation.Autowired; \nimport org.springframework.context.annotation.Configuration; \nimport org.springframework.security.authentication.AuthenticationManager;\nimport org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; \nimport org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; \nimport org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; \nimport org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; \n@Configuration \n@EnableAuthorizationServer \npublic class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { \n @Autowired private AuthenticationManager authenticationManager; \n @Override \n public void configure(ClientDetailsServiceConfigurer clients) throws Exception {\n clients.inMemory() \n .withClient(\"oauthclient1\") \n .secret(\"oauthsecret1\")\n .scopes(\"read\") .authorizedGrantTypes(\"password\") \n .and() .withClient(\"oauthclient2\") .secret(\"oauthsecret2\") \n .scopes(\"read\") .authorizedGrantTypes(\"authorization_code\") \n .redirectUris(\"http://locahost:9090\"); \n }\n @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { \n endpoints.authenticationManager(authenticationManager); \n } \n}" }, { "code": null, "e": 110582, "s": 110252, "text": "Let’s add a second client for this operation oauthclient2 for this operation with a new secret and read scope. Here we have changed the grant type to authorization code for this client. We also added a redirect URI so that the authorization server can callback the client. So, basically the redirect URI is the URI of the client." }, { "code": null, "e": 110940, "s": 110582, "text": "Now, we have to establish a connection between the user and the authorization server. We have to set an interface for the authorization server where the user can provide the credentials. We use the formLogin() implementation of Spring Security to achieve that functionality while keeping things simple. We also make sure that all requests are authenticated." }, { "code": null, "e": 112734, "s": 110940, "text": "package com.tutorial.spring.security.oauth2.config; \nimport org.springframework.context.annotation.Bean; \nimport org.springframework.context.annotation.Configuration; \nimport org.springframework.security.authentication.AuthenticationManager; \nimport org.springframework.security.config.annotation.web.builders.HttpSecurity; \nimport org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; \nimport org.springframework.security.core.userdetails.User; \nimport org.springframework.security.core.userdetails.UserDetails; \nimport org.springframework.security.core.userdetails.UserDetailsService; \nimport org.springframework.security.crypto.password.NoOpPasswordEncoder; \nimport org.springframework.security.crypto.password.PasswordEncoder; \nimport org.springframework.security.provisioning.InMemoryUserDetailsManager; \nimport org.springframework.security.provisioning.UserDetailsManager; \n@SuppressWarnings(\"deprecation\") @Configuration \npublic class UserConfig extends WebSecurityConfigurerAdapter {\n @Bean\n public UserDetailsService userDetailsService() {\n UserDetailsManager userDetailsManager = new InMemoryUserDetailsManager(); \n UserDetails user = User.withUsername(\"john\") \n .password(\"12345\") .authorities(\"read\") .build(); \n userDetailsManager.createUser(user); return userDetailsManager; \n } \n @Bean public PasswordEncoder passwordEncoder() { \n return NoOpPasswordEncoder.getInstance(); \n } \n @Override \n @Bean \n public AuthenticationManager authenticationManagerBean() throws Exception {\n return super.authenticationManagerBean(); \n }\n @Override protected void configure(HttpSecurity http) throws Exception {\n http.formLogin(); http.authorizeRequests().anyRequest().authenticated(); \n } \n}" }, { "code": null, "e": 113031, "s": 112734, "text": "This completes our setup for the authorization grant type. Now to test our setup and launch our application. We launch our browser at http://localhost:8080/oauth/authorize?response_type=code&client_id=oauthclient2&scope=read. We will redirected to the default form login page of Spring Security." }, { "code": null, "e": 113311, "s": 113031, "text": "Here, the response type code implies that the authorization server will return an access code which will be used by the client to log in. When we use the user credentials we will be asked if I want to grant the permissions asked by the client, in a similar screen as shown below." }, { "code": null, "e": 113623, "s": 113311, "text": "If we approve and click Authorize we shall see we are redirected to our given redirect url along with the access code. In our case the we are redirected to http://locahost:9090/?code=7Hibnw, as we specified in the application. We can use the code now as a client in Postman to login to the authorization server." }, { "code": null, "e": 113950, "s": 113623, "text": "As we can see here, we have used the code received from the authorization server in our URL, and the grant_type as authorization_code and scope as read. We acted as the client and provided the client credentials as configured in our application. When we make this request we get back our access_token which we can use further." }, { "code": null, "e": 114261, "s": 113950, "text": "So, we have seen how we can configure Spring Security with OAuth 2.0. The application is pretty simple and easy to understand and helps us understand the process fairly easily. We have used two kinds of authorization grant types and seen how we can use them to acquire access tokens for our client application." }, { "code": null, "e": 114291, "s": 114261, "text": "JWT Introduction and overview" }, { "code": null, "e": 114355, "s": 114291, "text": "Getting started with Spring Security using JWT(Practical Guide)" }, { "code": null, "e": 114916, "s": 114355, "text": "JSON Web Token or JWT, as it is more commonly called, is an open Internet standard (RFC 7519) for securely transmitting trusted information between parties in a compact way. The tokens contain claims that are encoded as a JSON object and are digitally signed using a private secret or a public key/private key pair. They are self-contained and verifiable as they are digitally signed. JWT’s can be signed and/or encrypted. The signed tokens verify the integrity of the claims contained in the token, while the encrypted ones hide the claims from other parties." }, { "code": null, "e": 115227, "s": 114916, "text": "JWT’s can also be used for the exchange of information though they more commonly used for authorization as they offer a lot of advantages over session management using in-memory random tokens. The biggest of them being the enabling the delegation of authentication logic to a third-party server like AuthO etc." }, { "code": null, "e": 115320, "s": 115227, "text": "A JWT token is divided into 3 parts namely – header, payload, and signature in the format of" }, { "code": null, "e": 115352, "s": 115320, "text": "[Header].[Payload].[Signature]\n" }, { "code": null, "e": 115665, "s": 115352, "text": "Header − The Header of a JWT token contains the list cryptographic operations that are applied to the JWT. This can be the signing technique, metadata information about the content-type and so on. The header is presented as a JSON object which is encoded to a base64URL. An example of a valid JWT header would be" }, { "code": null, "e": 115978, "s": 115665, "text": "Header − The Header of a JWT token contains the list cryptographic operations that are applied to the JWT. This can be the signing technique, metadata information about the content-type and so on. The header is presented as a JSON object which is encoded to a base64URL. An example of a valid JWT header would be" }, { "code": null, "e": 116012, "s": 115978, "text": "{ \"alg\": \"HS256\", \"typ\": \"JWT\" }\n" }, { "code": null, "e": 116125, "s": 116012, "text": "Here, “alg” gives us information about the type of algorithm used and “typ gives us the type of the information." }, { "code": null, "e": 116349, "s": 116125, "text": "Payload − The payload part of JWT contains the actual data to be transferred using the token. This part is also known as the “claims” part of the JWT token. The claims can be of three types – registered, public and private." }, { "code": null, "e": 116573, "s": 116349, "text": "Payload − The payload part of JWT contains the actual data to be transferred using the token. This part is also known as the “claims” part of the JWT token. The claims can be of three types – registered, public and private." }, { "code": null, "e": 116716, "s": 116573, "text": "The registered claims are the ones which are recommended but not mandatory claims such as iss(issuer), sub(subject), aud(audience) and others." }, { "code": null, "e": 116859, "s": 116716, "text": "The registered claims are the ones which are recommended but not mandatory claims such as iss(issuer), sub(subject), aud(audience) and others." }, { "code": null, "e": 116925, "s": 116859, "text": "Public claims are those that are defined by those using the JWTs." }, { "code": null, "e": 116991, "s": 116925, "text": "Public claims are those that are defined by those using the JWTs." }, { "code": null, "e": 117129, "s": 116991, "text": "Private claims or custom claims are user-defined claims created for the purpose of sharing the information between the concerned parties." }, { "code": null, "e": 117267, "s": 117129, "text": "Private claims or custom claims are user-defined claims created for the purpose of sharing the information between the concerned parties." }, { "code": null, "e": 117305, "s": 117267, "text": "Example of a payload object could be." }, { "code": null, "e": 117364, "s": 117305, "text": "{ \"sub\": \"12345\", \"name\": \"Johnny Hill\", \"admin\": false }\n" }, { "code": null, "e": 117486, "s": 117364, "text": "The payload object, like the header object is base64Url encoded as well and this string forms the second part of the JWT." }, { "code": null, "e": 117846, "s": 117486, "text": "Signature− The signature part of the JWT is used for the verification that the message wasn’t changed along the way. If the tokens are signed with private key, it also verifies that the sender is who it says it is. It is created using the encoded header, encoded payload, a secret and the algorithm specified in the header. An example of a signature would be." }, { "code": null, "e": 118206, "s": 117846, "text": "Signature− The signature part of the JWT is used for the verification that the message wasn’t changed along the way. If the tokens are signed with private key, it also verifies that the sender is who it says it is. It is created using the encoded header, encoded payload, a secret and the algorithm specified in the header. An example of a signature would be." }, { "code": null, "e": 118285, "s": 118206, "text": "HMACSHA256( base64UrlEncode(header) + \".\" + base64UrlEncode(payload), secret)\n" }, { "code": null, "e": 118360, "s": 118285, "text": "If we put the header, payload and signature we get a token as given below." }, { "code": null, "e": 118816, "s": 118360, "text": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6I\nkpvaG4gRG9lIiwiYWRtaW4iOmZhbHNlfQ.gWDlJdpCTIHVYKkJSfAVNUn0ZkAjMxskDDm-5Fhe\nWJ7xXgW8k5CllcGk4C9qPrfa1GdqfBrbX_1x1E39JY8BYLobAfAg1fs_Ky8Z7U1oCl6HL63yJq_\nwVNBHp49hWzg3-ERxkqiuTv0tIuDOasIdZ5FtBdtIP5LM9Oc1tsuMXQXCGR8GqGf1Hl2qv8MCyn\nNZJuVdJKO_L3WGBJouaTpK1u2SEleVFGI2HFvrX_jS2ySzDxoO9KjbydK0LNv_zOI7kWv-gAmA\nj-v0mHdJrLbxD7LcZJEGRScCSyITzo6Z59_jG_97oNLFgBKJbh12nvvPibHpUYWmZuHkoGvuy5RLUA" }, { "code": null, "e": 118900, "s": 118816, "text": "Now, this token can be used in the Authorization header using the Bearer schema as." }, { "code": null, "e": 118931, "s": 118900, "text": "Authorization − Bearer <token>" }, { "code": null, "e": 119305, "s": 118931, "text": "The use of JWT token for authorization is the most common of its applications. The token is usually generated in the server and sent to the client where it is stored in the session storage or local storage. To access a protected resource the client would send the JWT in the header as given above. We will see the JWT implementation in Spring Security in the section below." }, { "code": null, "e": 119533, "s": 119305, "text": "The application we are going to develop will handle basic user authentication and authorization with JWT’s. Let’s get started by going to start.spring.io where we will create a Maven application with the following dependencies." }, { "code": null, "e": 119544, "s": 119533, "text": "Spring Web" }, { "code": null, "e": 119560, "s": 119544, "text": "Spring Security" }, { "code": null, "e": 119779, "s": 119560, "text": "We generate the project and when it is downloaded, we extract it to a folder of our choice. We can then use any IDE of our choice. I am going to use Spring Tools Suite 4 as it is most optimized for Spring applications." }, { "code": null, "e": 120101, "s": 119779, "text": "Apart from the above-mentioned dependencies we are also going to include the jwt dependency from io.jsonwebtoken from the Maven central repository as it is not included in the spring initializer. This dependency takes care of all operations involving the JWT including building the token, parsing it for claims and so on." }, { "code": null, "e": 120192, "s": 120101, "text": "<dependency> \n <artifactId>jjwt</artifactId> \n <version>0.9.1</version> \n</dependency>" }, { "code": null, "e": 120242, "s": 120192, "text": "Our pom.xml file should now look similar to this." }, { "code": null, "e": 122479, "s": 120242, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 \n https://maven.apache.org/xsd/maven-4.0.0.xsd\"> \n <modelVersion>4.0.0</modelVersion> \n <parent> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-starter-parent</artifactId> \n <version>2.3.1.RELEASE<version> \n <relativePath /> \n <!-- lookup parent from repository --> \n </parent> \n <groupId>com.spring.security</groupId> \n <artifactId>jwtbasic</artifactId>\n <version>0.0.1-SNAPSHOT</version> \n <name>jwtbasic</name> \n <description>Demo project for Spring Boot</description> \n <properties> \n <java.version>1.8</java.version> \n </properties> \n <dependencies> \n <dependency> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-starter-security</artifactId> \n </dependency> \n <dependency>\n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-starter-web</artifactId> \n </dependency> \n <dependency> \n <groupId>io.jsonwebtoken</groupId> \n <artifactId>jjwt</artifactId> \n <version>0.9.1</version> \n </dependency>\n <dependency> \n <groupId>javax.xml.bind</groupId> \n <artifactId>jaxb-api</artifactId> \n </dependency> \n <dependency> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-starter-test</artifactId> \n <scope>test</scope> \n <exclusions> \n <exclusion> \n <groupId>org.junit.vintage</groupId> \n <artifactId>junit-vintage-engine</artifactId> \n </exclusion> \n </exclusions> \n </dependency> \n <dependency> \n <groupId>org.springframework.security</groupId> \n <artifactId>spring-security-test</artifactId> \n <scope>test<scope>\n <dependency> \n </dependencies> \n <build> \n <plugins> \n <plugin> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-maven-plugin</artifactId> \n </plugin> \n </plugins> \n </build> \n</project>" }, { "code": null, "e": 122601, "s": 122479, "text": "Now that our project is set up we are going to create our controller class Hello Controller which exposes a Get endpoint." }, { "code": null, "e": 122909, "s": 122601, "text": "package com.spring.security.jwtbasic.controllers; \nimport org.springframework.web.bind.annotation.GetMapping; \nimport org.springframework.web.bind.annotation.RestController; \n@RestController \npublic class HelloController {\n @GetMapping(\"/hello\") \n public String hello() { \n return \"hello\"; \n } \n}" }, { "code": null, "e": 123366, "s": 122909, "text": "Now we are going to create a package called config where we add the configuration class that extends the WebSecurityConfigurerAdapter class of Spring Security. This will provide us with all the required functions and definitions for project configuration and security of our application. For now, we provide the BcryptPasswordEncoder instance by implementing a method that generates the same. We annotate the method with @Bean to add to our Spring Context." }, { "code": null, "e": 124669, "s": 123366, "text": "package com.spring.security.jwtbasic.config; \nimport org.springframework.beans.factory.annotation.Autowired; \nimport org.springframework.context.annotation.Bean; \nimport org.springframework.context.annotation.Configuration; \nimport org.springframework.security.authentication.AuthenticationManager; \nimport org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; \nimport org.springframework.security.config.annotation.web.builders.HttpSecurity; \nimport org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; \nimport org.springframework.security.config.http.SessionCreationPolicy;\nimport org.springframework.security.core.userdetails.UserDetailsService; \nimport org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; \nimport org.springframework.security.crypto.password.PasswordEncoder; \nimport org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; \nimport com.spring.security.jwtbasic.jwtutils.JwtAuthenticationEntryPoint; \nimport com.spring.security.jwtbasic.jwtutils.JwtFilter; \n@Configuration \npublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {\n @Bean \n public PasswordEncoder passwordEncoder() { \n return new BCryptPasswordEncoder(); \n } \n}" }, { "code": null, "e": 124767, "s": 124669, "text": "The JWT includes a secret which we will define in our application.properties file as given below." }, { "code": null, "e": 124792, "s": 124767, "text": "secret=somerandomsecret\n" }, { "code": null, "e": 124942, "s": 124792, "text": "Now let’s create a package called jwtutils. This package is going to contain all classes and interface related to JWT operations, which will include." }, { "code": null, "e": 124959, "s": 124942, "text": "Generating token" }, { "code": null, "e": 124976, "s": 124959, "text": "Validating token" }, { "code": null, "e": 124999, "s": 124976, "text": "Checking the signature" }, { "code": null, "e": 125032, "s": 124999, "text": "Verifying claims and permissions" }, { "code": null, "e": 125198, "s": 125032, "text": "In this package, we create our first class called Token Manager. This class will be responsible for the creation and validation of tokens using io.jsonwebtoken.Jwts." }, { "code": null, "e": 126924, "s": 125198, "text": "package com.spring.security.jwtbasic.jwtutils; \nimport java.io.Serializable; \nimport java.util.Base64; \nimport java.util.Date; \nimport java.util.HashMap; \nimport java.util.Map; \nimport org.springframework.beans.factory.annotation.Value; \nimport org.springframework.security.core.userdetails.UserDetails; \nimport org.springframework.stereotype.Component; \nimport io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; \nimport io.jsonwebtoken.SignatureAlgorithm; \n@Component \npublic class TokenManager implements Serializable {\n /** \n *\n */ \n private static final long serialVersionUID = 7008375124389347049L; public static final long TOKEN_VALIDITY = 10 * 60 * 60; @Value(\"${secret}\") \n private String jwtSecret; \n public String generateJwtToken(UserDetails userDetails) { \n Map<String, Object> claims = new HashMap<>(); \n return Jwts.builder().setClaims(claims).setSubject(userDetails.getUsername()) \n .setIssuedAt(new Date(System.currentTimeMillis())) \n .setExpiration(new Date(System.currentTimeMillis() + TOKEN_VALIDITY * 1000)) \n .signWith(SignatureAlgorithm.HS512, jwtSecret).compact(); \n } \n public Boolean validateJwtToken(String token, UserDetails userDetails) { \n String username = getUsernameFromToken(token); \n Claims claims = Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody();\n Boolean isTokenExpired = claims.getExpiration().before(new Date()); \n return (username.equals(userDetails.getUsername()) && !isTokenExpired); \n } \n public String getUsernameFromToken(String token) {\n final Claims claims = Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody(); \n return claims.getSubject(); \n } \n}" }, { "code": null, "e": 127273, "s": 126924, "text": "Here, as all tokens should have an expiration date, we start with a token validity constant. Here, we want our token to be valid for 10 minutes after generation. We will use this value when we generate our token. Then we extract the value of our singing key from the application.properties file into our jwtSecret field using the @Value annotation." }, { "code": null, "e": 127300, "s": 127273, "text": "We have two methods here −" }, { "code": null, "e": 127755, "s": 127300, "text": "generateJwtToken() − This method is used to generate a token on successful authentication by the user. To create the token here we use the username, issue date of token and the expiration date of the token. This will form the payload part of the token or claims as we had discussed earlier. To generate the token we use the builder() method of Jwts. This method returns a new JwtBuilder instance that can be used to create compact JWT serialized strings." }, { "code": null, "e": 128063, "s": 127755, "text": "To set the claims we use the setClaims() method and then set each of the claims. For this token we have setSubject(username), issue date and expiration date. We can also put our custom claims as we had discussed above. This can be any value we want which might include user role, user authorities and so on." }, { "code": null, "e": 128366, "s": 128063, "text": "Then we set the signature part of the token. This is done using the signWith() method, we set the hashing algorithm we prefer to use and the secret key. Then we use thecompact() method that builds the JWT and serializes it to a compact, URL-safe string according to the JWT Compact Serialization rules." }, { "code": null, "e": 128789, "s": 128366, "text": "validateJwtToken() − Now that the generation of the token is taken care of, we should focus on the process of validation of the token when it comes as a part of requests. To validate the token means to verify the request is an authenticated one and that the token is the one that was generated and sent to the user. Here, we need to parse the token for the claims such as username, roles, authorities, validity period etc." }, { "code": null, "e": 129212, "s": 128789, "text": "validateJwtToken() − Now that the generation of the token is taken care of, we should focus on the process of validation of the token when it comes as a part of requests. To validate the token means to verify the request is an authenticated one and that the token is the one that was generated and sent to the user. Here, we need to parse the token for the claims such as username, roles, authorities, validity period etc." }, { "code": null, "e": 129676, "s": 129212, "text": "To validate the token we need to parse it first. This is done using the parser() method of Jwts. We then need to set the signing key that we used to generate the token and then use parseClaimsJws() method on the token to parse the compact serialized JWS string based on the builder’s current configuration state and return the resulting Claims JWS instance. The getBody() method is then used to return the claims instance that was used while generating the token." }, { "code": null, "e": 129968, "s": 129676, "text": "From this obtained claims instance, we extract the subject and the expiry date to verify the validity of the token. The username should be the username of the user and the token should not be expired. If both these conditions are met, we return true, which signifies that the token is valid." }, { "code": null, "e": 130170, "s": 129968, "text": "The next class we would be creating is the JwtUserDetailsService. This class will extend the UserDetailsService of Spring security and we will implement the loadUserByUsername() method as given below −" }, { "code": null, "e": 131086, "s": 130170, "text": "package com.spring.security.jwtbasic.jwtutils; \nimport java.util.ArrayList; \nimport org.springframework.security.core.userdetails.User; \nimport org.springframework.security.core.userdetails.UserDetails; \nimport org.springframework.security.core.userdetails.UserDetailsService; \nimport org.springframework.security.core.userdetails.UsernameNotFoundException; \nimport org.springframework.stereotype.Service; \n@Service\npublic class JwtUserDetailsService implements UserDetailsService { \n @Override \n public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {\n if (\"randomuser123\".equals(username)) { \n return new User(\"randomuser123\", \n \"$2a$10$slYQmyNdGzTn7ZLBXBChFOC9f6kFjAqPhccnP6DxlWXx2lPk1C3G6\", \n new ArrayList<>()); \n } else { \n throw new UsernameNotFoundException(\"User not found with username: \" + username); \n } \n } \n}" }, { "code": null, "e": 131446, "s": 131086, "text": "Here, since this is a basic application for the sole purpose of the demonstration of JWT authentication, we have resorted to a set of our user details, instead of using a database. We have given the username as “randomuser123” and encoded the password, which is “password” as “$2a$10$slYQmyNdGzTn7ZLBXBChFOC9f6kFjAqPhccnP6DxlWXx2lPk1C3G6” for our convenience." }, { "code": null, "e": 131741, "s": 131446, "text": "Next, we create classes for our Request and Response models. These models determine how our request and response formats would be for authentication. The first snapshot given below is the request model. As we can see, we shall be accepting two properties – username and password in our request." }, { "code": null, "e": 132513, "s": 131741, "text": "package com.spring.security.jwtbasic.jwtutils.models;\nimport java.io.Serializable; \npublic class JwtRequestModel implements Serializable { \n /** \n * \n */ \n private static final long serialVersionUID = 2636936156391265891L; \n private String username; \n private String password; \n public JwtRequestModel() { \n } \n public JwtRequestModel(String username, String password) { \n super(); \n this.username = username; this.password = password; \n } \n public String getUsername() { \n return username;\n } \n public void setUsername(String username) { \n this.username = username; \n } \n public String getPassword() { \n return password; \n } \n public void setPassword(String password) { \n this.password = password; \n } \n}" }, { "code": null, "e": 132671, "s": 132513, "text": "Below is the code for response model on successful authentication. As we can see, we will be sending the token back to the user on successful authentication." }, { "code": null, "e": 133044, "s": 132671, "text": "package com.spring.security.jwtbasic.jwtutils.models; \nimport java.io.Serializable; \npublic class JwtResponseModel implements Serializable {\n /**\n *\n */\n private static final long serialVersionUID = 1L;\n private final String token;\n public JwtResponseModel(String token) {\n this.token = token;\n }\n public String getToken() {\n return token;\n }\n}" }, { "code": null, "e": 133110, "s": 133044, "text": "For authentication now, let’s create a controller as given below." }, { "code": null, "e": 135028, "s": 133110, "text": "package com.spring.security.jwtbasic.jwtutils;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.security.authentication.AuthenticationManager;\nimport org.springframework.security.authentication.BadCredentialsException;\nimport org.springframework.security.authentication.DisabledException;\nimport org.springframework.security.authentication.UsernamePasswordAuthenticationToken;\nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.web.bind.annotation.CrossOrigin;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RestController;\nimport com.spring.security.jwtbasic.jwtutils.models.JwtRequestModel;\nimport com.spring.security.jwtbasic.jwtutils.models.JwtResponseModel;\n@RestController\n@CrossOrigin\npublic class JwtController {\n @Autowired\n private JwtUserDetailsService userDetailsService;\n @Autowired\n private AuthenticationManager authenticationManager;\n @Autowired\n private TokenManager tokenManager;\n @PostMapping(\"/login\")\n public ResponseEntity<> createToken(@RequestBody JwtRequestModel\n request) throws Exception {\n try {\n authenticationManager.authenticate(\n new\n UsernamePasswordAuthenticationToken(request.getUsername(),\n request.getPassword())\n );\n } catch (DisabledException e) {\n throw new Exception(\"USER_DISABLED\", e);\n } catch (BadCredentialsException e) {\n throw new Exception(\"INVALID_CREDENTIALS\", e);\n }\n final UserDetails userDetails = userDetailsService.loadUserByUsername(request.getUsername());\n final String jwtToken = tokenManager.generateJwtToken(userDetails);\n return ResponseEntity.ok(new JwtResponseModel(jwtToken));\n }\n}" }, { "code": null, "e": 135374, "s": 135028, "text": "If we go through the code we can see that, we have autowired three dependencies namely, JwtUserDetailsService, AuthenticationManager and TokenManager. While we have already seen the implementation of JwtUserDetailsService and TokenManager classes above, the authentication manager bean is one we shall be creating in our WebSecurityConfig class." }, { "code": null, "e": 135698, "s": 135374, "text": "AuthenticationManager class will take care of our authentication. We shall be using the UsernamePasswordAuthenticationToken model for authentication of the request. If authentication succeeds we shall generate a JWT for the user, which can be sent in the Authorization header of the subsequent requests to get any resource." }, { "code": null, "e": 135845, "s": 135698, "text": "As we can see, we are using the loadUserByUsername() method of our JwtUserDetailsService class and the generateJwtToken() from TokenManager class." }, { "code": null, "e": 135947, "s": 135845, "text": "This generated JWT is sent to the user as a response on successful authentication as mentioned above." }, { "code": null, "e": 136189, "s": 135947, "text": "Now it’s time we created our Filter. The filter class will be used to track our requests and detect if they contain the valid token in the header. If the token is valid we let the request proceed otherwise we send a 401 error (Unauthorized)." }, { "code": null, "e": 138669, "s": 136189, "text": "package com.spring.security.jwtbasic.jwtutils;\nimport java.io.IOException;\nimport javax.servlet.FilterChain;\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.authentication.UsernamePasswordAuthenticationToken;\nimport org.springframework.security.core.context.SecurityContextHolder;\nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.security.web.authentication.WebAuthenticationDetailsSource;\nimport org.springframework.stereotype.Component;\nimport org.springframework.web.filter.OncePerRequestFilter;\nimport io.jsonwebtoken.ExpiredJwtException;\n@Component\npublic class JwtFilter extends OncePerRequestFilter {\n @Autowired\n private JwtUserDetailsService userDetailsService;\n @Autowired\n private TokenManager tokenManager;\n @Override\n protected void doFilterInternal(HttpServletRequest request,\n HttpServletResponse response, FilterChain filterChain)\n throws ServletException, IOException {\n \n String tokenHeader = request.getHeader(\"Authorization\");\n String username = null;\n String token = null;\n if (tokenHeader != null && tokenHeader.startsWith(\"Bearer \")) {\n token = tokenHeader.substring(7);\n try {\n username = tokenManager.getUsernameFromToken(token);\n } catch (IllegalArgumentException e) {\n System.out.println(\"Unable to get JWT Token\");\n } catch (ExpiredJwtException e) {\n System.out.println(\"JWT Token has expired\");\n }\n } else {\n System.out.println(\"Bearer String not found in token\");\n }\n if (null != username &&SecurityContextHolder.getContext().getAuthentication() == null) {\n UserDetails userDetails = userDetailsService.loadUserByUsername(username);\n if (tokenManager.validateJwtToken(token, userDetails)) {\n UsernamePasswordAuthenticationToken\n authenticationToken = new UsernamePasswordAuthenticationToken(\n userDetails, null,\n userDetails.getAuthorities());\n authenticationToken.setDetails(new\n WebAuthenticationDetailsSource().buildDetails(request));\n SecurityContextHolder.getContext().setAuthentication(authenticationToken);\n }\n }\n filterChain.doFilter(request, response);\n }\n}" }, { "code": null, "e": 139002, "s": 138669, "text": "As we can see above, we have autowired the JwtUserDetailsService and TokenManager classes here as well. We have extended the OncePerRequestFilter of SpringSecurity which makes sure the filter is run for every request. We have provided our implementation to the overridden method doFilterInternal() of the OncePerRequestFilter class." }, { "code": null, "e": 139580, "s": 139002, "text": "The method here extracts the token from the header and validates it with the help of validateJwtToken() method of our TokenManager class. During validation, it checks for the username and the expiration date. If both the values are valid, we save the authentication in our Spring Security context and let the code proceed to the next filter in our filter chain. If any of the validation fails or there is an issue with the token or if the token is not found we throw the appropriate exceptions and send back an appropriate response while blocking the request from moving ahead." }, { "code": null, "e": 139912, "s": 139580, "text": "Having created the filter for our requests, we now create the JwtAutheticationEntryPoint class. This class extends Spring’s AuthenticationEntryPoint class and rejects every unauthenticated request with an error code 401 sent back to the client. We have overridden the commence() method of AuthenticationEntryPoint class to do that." }, { "code": null, "e": 140707, "s": 139912, "text": "package com.spring.security.jwtbasic.jwtutils;\nimport java.io.IOException;\nimport java.io.Serializable;\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport org.springframework.security.core.AuthenticationException;\nimport org.springframework.security.web.AuthenticationEntryPoint;\nimport org.springframework.stereotype.Component;\n@Component\npublic class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint,\nSerializable {\n @Override\n public void commence(HttpServletRequest request, HttpServletResponse\n response,\n AuthenticationException authException) throws\n IOException, ServletException {\n response.sendError(HttpServletResponse.SC_UNAUTHORIZED,\n \"Unauthorized\");\n }\n}" }, { "code": null, "e": 141260, "s": 140707, "text": "Now, let’s get back to our WebSecurityConfig class and finish the rest of our configuration. If we remember, we are going to require our AuthenticationManager bean for our Jwt controller class and add the filter we just created to our configuration. We are also going to configure which requests are to be authenticated and which are not to be. We shall also add the AuthenticationEntryPoint to our requests to send back the 401 error response. Since, we also do not need to maintain session variables while using jwt we can make our session STATELESS." }, { "code": null, "e": 143549, "s": 141260, "text": "package com.spring.security.jwtbasic.config;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.security.authentication.AuthenticationManager;\nimport org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;\nimport org.springframework.security.config.annotation.web.builders.HttpSecurity;\nimport org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;\nimport org.springframework.security.config.http.SessionCreationPolicy;\nimport org.springframework.security.core.userdetails.UserDetailsService;\nimport org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;\nimport org.springframework.security.crypto.password.PasswordEncoder;\nimport org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;\nimport com.spring.security.jwtbasic.jwtutils.JwtAuthenticationEntryPoint;\nimport com.spring.security.jwtbasic.jwtutils.JwtFilter;\n@Configuration\npublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {\n @Autowired\n private JwtAuthenticationEntryPoint authenticationEntryPoint;\n @Autowired\n private UserDetailsService userDetailsService;\n @Autowired\n private JwtFilter filter;\n @Bean\n public PasswordEncoder passwordEncoder() {\n return new BCryptPasswordEncoder();\n }\n @Override\n protected void configure(AuthenticationManagerBuilder auth) throws Exception {\n auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());\n }\n @Bean\n @Override\n public AuthenticationManager authenticationManagerBean() throws\n Exception {\n return super.authenticationManagerBean();\n }\n @Override\n protected void configure(HttpSecurity http) throws Exception {\n http.csrf().disable()\n .authorizeRequests().antMatchers(\"/login\").permitAll()\n .anyRequest().authenticated()\n .and()\n .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint)\n .and()\n .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);\n http.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class);\n }\n}" }, { "code": null, "e": 143699, "s": 143549, "text": "As we can see, we have done all of that, and now our application is ready to go. Let’s start the application and use postman for making our requests." }, { "code": null, "e": 143849, "s": 143699, "text": "Here we have made our first request to get the token, and as we can see on providing the correct username/password combination we get back our token." }, { "code": null, "e": 143917, "s": 143849, "text": "Now using that token in our header, let’s call the /hello endpoint." }, { "code": null, "e": 144194, "s": 143917, "text": "As we can see, since the request is authenticated, we get the desired response back. Now, if we tamper with the token or do not send the Authorization header, we will get a 401 error as configured in our application. This ensures that the protection our request using the JWT." }, { "code": null, "e": 144228, "s": 144194, "text": "\n 102 Lectures \n 8 hours \n" }, { "code": null, "e": 144242, "s": 144228, "text": " Karthikeya T" }, { "code": null, "e": 144275, "s": 144242, "text": "\n 39 Lectures \n 5 hours \n" }, { "code": null, "e": 144290, "s": 144275, "text": " Chaand Sheikh" }, { "code": null, "e": 144325, "s": 144290, "text": "\n 73 Lectures \n 5.5 hours \n" }, { "code": null, "e": 144337, "s": 144325, "text": " Senol Atac" }, { "code": null, "e": 144372, "s": 144337, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 144384, "s": 144372, "text": " Senol Atac" }, { "code": null, "e": 144419, "s": 144384, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 144431, "s": 144419, "text": " Senol Atac" }, { "code": null, "e": 144464, "s": 144431, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 144476, "s": 144464, "text": " Senol Atac" }, { "code": null, "e": 144483, "s": 144476, "text": " Print" }, { "code": null, "e": 144494, "s": 144483, "text": " Add Notes" } ]
C# | foreach Loop - GeeksforGeeks
06 Aug, 2019 Prerequisite: Loops in C# Looping in a programming language is a way to execute a statement or a set of statements multiple numbers of times depending on the result of a condition to be evaluated. The resulting condition should be true to execute statements within loops. The foreach loop is used to iterate over the elements of the collection. The collection may be an array or a list. It executes for each element present in the array. It is necessary to enclose the statements of foreach loop in curly braces {}. Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name. In the loop body, you can use the loop variable you created rather than using an indexed array element. Syntax: foreach(data_type var_name in collection_variable) { // statements to be executed } Flowchart: Example 1: // C# program to illustrate the// use of foreach loopusing System; class GFG { // Main Method static public void Main() { Console.WriteLine("Print array:"); // creating an array int[] a_array = new int[] { 1, 2, 3, 4, 5, 6, 7 }; // foreach loop begin // it will run till the // last element of the array foreach(int items in a_array) { Console.WriteLine(items); } }} Print array: 1 2 3 4 5 6 7 Explanation: foreach loop in above program is equivalent to: for(int items = 0; items < a_array.Length; items++) { Console.WriteLine(a_array[items]); } Example 2: // C# program to illustrate // foreach loop using System; class For_Each { // Main Method public static void Main(String[] arg) { { int[] marks = { 125, 132, 95, 116, 110 }; int highest_marks = maximum(marks); Console.WriteLine("The highest score is " + highest_marks); } } // method to find maximum public static int maximum(int[] numbers) { int maxSoFar = numbers[0]; // for each loop foreach (int num in numbers) { if (num > maxSoFar) { maxSoFar = num; } } return maxSoFar; } } The highest score is 132 Limitations of foreach loop: Foreach loops are not appropriate when you want to modify the array:foreach(int num in marks) { // only changes num not // the array element num = num * 2; } Foreach loops do not keep track of index. So we can not obtain array index using ForEach loopforeach (int num in numbers) { if (num == target) { return ???; // do not know the index of num } } Foreach only iterates forward over the array in single steps// cannot be converted to a foreach loop for (int i = numbers.Length - 1; i > 0; i--) { Console.WriteLine(numbers[i]); } Foreach loops are not appropriate when you want to modify the array:foreach(int num in marks) { // only changes num not // the array element num = num * 2; } foreach(int num in marks) { // only changes num not // the array element num = num * 2; } Foreach loops do not keep track of index. So we can not obtain array index using ForEach loopforeach (int num in numbers) { if (num == target) { return ???; // do not know the index of num } } foreach (int num in numbers) { if (num == target) { return ???; // do not know the index of num } } Foreach only iterates forward over the array in single steps// cannot be converted to a foreach loop for (int i = numbers.Length - 1; i > 0; i--) { Console.WriteLine(numbers[i]); } // cannot be converted to a foreach loop for (int i = numbers.Length - 1; i > 0; i--) { Console.WriteLine(numbers[i]); } Difference between for loop and foreach loop: for loop executes a statement or a block of statement until the given condition is false. Whereas foreach loop executes a statement or a block of statements for each element present in the array and there is no need to define the minimum or maximum limit. In for loop, we iterate the array in both forward and backward directions, e.g from index 0 to 9 and from index 9 to 0. But in the foreach loop, we iterate an array only in the forward direction, not in a backward direction. In terms of a variable declaration, foreach loop has five variable declarations whereas for loop only have three variable declarations. The foreach loop copies the array and put this copy into the new array for operation. Whereas for loop doesn’t do. GautamNitt CSharp-Basics CSharp-Decision Making C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Destructors in C# C# | Delegates C# | String.IndexOf( ) Method | Set - 1 Extension Method in C# Introduction to .NET Framework C# | Abstract Classes C# | Data Types HashSet in C# with Examples Top 50 C# Interview Questions & Answers C# | Replace() Method
[ { "code": null, "e": 24252, "s": 24224, "text": "\n06 Aug, 2019" }, { "code": null, "e": 24278, "s": 24252, "text": "Prerequisite: Loops in C#" }, { "code": null, "e": 24690, "s": 24278, "text": "Looping in a programming language is a way to execute a statement or a set of statements multiple numbers of times depending on the result of a condition to be evaluated. The resulting condition should be true to execute statements within loops. The foreach loop is used to iterate over the elements of the collection. The collection may be an array or a list. It executes for each element present in the array." }, { "code": null, "e": 24768, "s": 24690, "text": "It is necessary to enclose the statements of foreach loop in curly braces {}." }, { "code": null, "e": 24970, "s": 24768, "text": "Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name." }, { "code": null, "e": 25074, "s": 24970, "text": "In the loop body, you can use the loop variable you created rather than using an indexed array element." }, { "code": null, "e": 25082, "s": 25074, "text": "Syntax:" }, { "code": null, "e": 25172, "s": 25082, "text": "foreach(data_type var_name in collection_variable)\n{\n // statements to be executed\n}\n" }, { "code": null, "e": 25183, "s": 25172, "text": "Flowchart:" }, { "code": null, "e": 25194, "s": 25183, "text": "Example 1:" }, { "code": "// C# program to illustrate the// use of foreach loopusing System; class GFG { // Main Method static public void Main() { Console.WriteLine(\"Print array:\"); // creating an array int[] a_array = new int[] { 1, 2, 3, 4, 5, 6, 7 }; // foreach loop begin // it will run till the // last element of the array foreach(int items in a_array) { Console.WriteLine(items); } }}", "e": 25656, "s": 25194, "text": null }, { "code": null, "e": 25684, "s": 25656, "text": "Print array:\n1\n2\n3\n4\n5\n6\n7\n" }, { "code": null, "e": 25745, "s": 25684, "text": "Explanation: foreach loop in above program is equivalent to:" }, { "code": null, "e": 25841, "s": 25745, "text": "for(int items = 0; items < a_array.Length; items++)\n{\n Console.WriteLine(a_array[items]);\n}\n" }, { "code": null, "e": 25852, "s": 25841, "text": "Example 2:" }, { "code": "// C# program to illustrate // foreach loop using System; class For_Each { // Main Method public static void Main(String[] arg) { { int[] marks = { 125, 132, 95, 116, 110 }; int highest_marks = maximum(marks); Console.WriteLine(\"The highest score is \" + highest_marks); } } // method to find maximum public static int maximum(int[] numbers) { int maxSoFar = numbers[0]; // for each loop foreach (int num in numbers) { if (num > maxSoFar) { maxSoFar = num; } } return maxSoFar; } } ", "e": 26566, "s": 25852, "text": null }, { "code": null, "e": 26592, "s": 26566, "text": "The highest score is 132\n" }, { "code": null, "e": 26621, "s": 26592, "text": "Limitations of foreach loop:" }, { "code": null, "e": 27199, "s": 26621, "text": "Foreach loops are not appropriate when you want to modify the array:foreach(int num in marks) \n{\n // only changes num not\n // the array element\n num = num * 2; \n}\nForeach loops do not keep track of index. So we can not obtain array index using ForEach loopforeach (int num in numbers) \n{ \n if (num == target) \n {\n return ???; // do not know the index of num\n }\n}\nForeach only iterates forward over the array in single steps// cannot be converted to a foreach loop\nfor (int i = numbers.Length - 1; i > 0; i--) \n{\n Console.WriteLine(numbers[i]);\n}\n" }, { "code": null, "e": 27372, "s": 27199, "text": "Foreach loops are not appropriate when you want to modify the array:foreach(int num in marks) \n{\n // only changes num not\n // the array element\n num = num * 2; \n}\n" }, { "code": null, "e": 27477, "s": 27372, "text": "foreach(int num in marks) \n{\n // only changes num not\n // the array element\n num = num * 2; \n}\n" }, { "code": null, "e": 27696, "s": 27477, "text": "Foreach loops do not keep track of index. So we can not obtain array index using ForEach loopforeach (int num in numbers) \n{ \n if (num == target) \n {\n return ???; // do not know the index of num\n }\n}\n" }, { "code": null, "e": 27822, "s": 27696, "text": "foreach (int num in numbers) \n{ \n if (num == target) \n {\n return ???; // do not know the index of num\n }\n}\n" }, { "code": null, "e": 28010, "s": 27822, "text": "Foreach only iterates forward over the array in single steps// cannot be converted to a foreach loop\nfor (int i = numbers.Length - 1; i > 0; i--) \n{\n Console.WriteLine(numbers[i]);\n}\n" }, { "code": null, "e": 28138, "s": 28010, "text": "// cannot be converted to a foreach loop\nfor (int i = numbers.Length - 1; i > 0; i--) \n{\n Console.WriteLine(numbers[i]);\n}\n" }, { "code": null, "e": 28184, "s": 28138, "text": "Difference between for loop and foreach loop:" }, { "code": null, "e": 28440, "s": 28184, "text": "for loop executes a statement or a block of statement until the given condition is false. Whereas foreach loop executes a statement or a block of statements for each element present in the array and there is no need to define the minimum or maximum limit." }, { "code": null, "e": 28665, "s": 28440, "text": "In for loop, we iterate the array in both forward and backward directions, e.g from index 0 to 9 and from index 9 to 0. But in the foreach loop, we iterate an array only in the forward direction, not in a backward direction." }, { "code": null, "e": 28801, "s": 28665, "text": "In terms of a variable declaration, foreach loop has five variable declarations whereas for loop only have three variable declarations." }, { "code": null, "e": 28916, "s": 28801, "text": "The foreach loop copies the array and put this copy into the new array for operation. Whereas for loop doesn’t do." }, { "code": null, "e": 28927, "s": 28916, "text": "GautamNitt" }, { "code": null, "e": 28941, "s": 28927, "text": "CSharp-Basics" }, { "code": null, "e": 28964, "s": 28941, "text": "CSharp-Decision Making" }, { "code": null, "e": 28967, "s": 28964, "text": "C#" }, { "code": null, "e": 29065, "s": 28967, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29083, "s": 29065, "text": "Destructors in C#" }, { "code": null, "e": 29098, "s": 29083, "text": "C# | Delegates" }, { "code": null, "e": 29138, "s": 29098, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 29161, "s": 29138, "text": "Extension Method in C#" }, { "code": null, "e": 29192, "s": 29161, "text": "Introduction to .NET Framework" }, { "code": null, "e": 29214, "s": 29192, "text": "C# | Abstract Classes" }, { "code": null, "e": 29230, "s": 29214, "text": "C# | Data Types" }, { "code": null, "e": 29258, "s": 29230, "text": "HashSet in C# with Examples" }, { "code": null, "e": 29298, "s": 29258, "text": "Top 50 C# Interview Questions & Answers" } ]
How to set the Margin of the Buttons in C#? - GeeksforGeeks
26 Jun, 2019 A Button is an essential part of an application, or software, or webpage. It allows the user to interact with the application or software. In Button, you are allowed to set the space between two or more Button controls using Margin Property. You can use this property in two different methods: 1. Design-Time: It is the easiest method to set the margin between two button controls. Using the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Drag the Button control from the ToolBox and Drop it on the windows form. You are allowed to place a Button control anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the Button control to set the Margin property of the Button.Output: Output: Run-Time: It is a little bit trickier than the above method. In this method, you can set the Margin property of the Button programmatically with the help of given syntax: public System.Windows.Forms.Padding Margin { get; set; } Here, the Padding is used to represent the space between controls. Following steps are used to set the Margin property of the Button: Step 1: Create a button using the Button() constructor is provided by the Button class.// Creating Button using Button class Button MyButton = new Button(); // Creating Button using Button class Button MyButton = new Button(); Step 2: After creating Button, set the Margin property of the Button provided by the Button class.// Set the margin of the button Mybutton.Margin = new Padding(5, 5, 5, 5); // Set the margin of the button Mybutton.Margin = new Padding(5, 5, 5, 5); Step 3: And last add this button control to form using Add() method.// Add this Button to form this.Controls.Add(Mybutton); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp8 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.AutoSize = true; l.Text = "Do you want to submit this form?"; l.Location = new Point(222, 145); l.Font = new Font("French Script MT", 18); // Adding this label to form this.Controls.Add(l); // Creating and setting the properties of Button Button Mybutton = new Button(); Mybutton.Location = new Point(225, 198); Mybutton.Text = "Submit"; Mybutton.AutoSize = true; Mybutton.BackColor = Color.LightBlue; Mybutton.Padding = new Padding(6); Mybutton.Font = new Font("French Script MT", 18); Mybutton.Margin = new Padding(5, 5, 5, 5); // Adding this button to form this.Controls.Add(Mybutton); // Creating and setting the properties of Button Button Mybutton1 = new Button(); Mybutton1.Location = new Point(360, 198); Mybutton1.Text = "Cancel"; Mybutton1.AutoSize = true; Mybutton1.BackColor = Color.LightPink; Mybutton1.Padding = new Padding(6); Mybutton1.Font = new Font("French Script MT", 18); Mybutton1.Margin = new Padding(5, 5, 5, 5); // Adding this button to form this.Controls.Add(Mybutton1); }}}Output: // Add this Button to form this.Controls.Add(Mybutton); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp8 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.AutoSize = true; l.Text = "Do you want to submit this form?"; l.Location = new Point(222, 145); l.Font = new Font("French Script MT", 18); // Adding this label to form this.Controls.Add(l); // Creating and setting the properties of Button Button Mybutton = new Button(); Mybutton.Location = new Point(225, 198); Mybutton.Text = "Submit"; Mybutton.AutoSize = true; Mybutton.BackColor = Color.LightBlue; Mybutton.Padding = new Padding(6); Mybutton.Font = new Font("French Script MT", 18); Mybutton.Margin = new Padding(5, 5, 5, 5); // Adding this button to form this.Controls.Add(Mybutton); // Creating and setting the properties of Button Button Mybutton1 = new Button(); Mybutton1.Location = new Point(360, 198); Mybutton1.Text = "Cancel"; Mybutton1.AutoSize = true; Mybutton1.BackColor = Color.LightPink; Mybutton1.Padding = new Padding(6); Mybutton1.Font = new Font("French Script MT", 18); Mybutton1.Margin = new Padding(5, 5, 5, 5); // Adding this button to form this.Controls.Add(Mybutton1); }}} Output: C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Method Overriding C# Dictionary with examples C# | Delegates Difference between Ref and Out keywords in C# Destructors in C# Extension Method in C# C# | Constructors C# | Abstract Classes C# | String.IndexOf( ) Method | Set - 1 Introduction to .NET Framework
[ { "code": null, "e": 24192, "s": 24164, "text": "\n26 Jun, 2019" }, { "code": null, "e": 24486, "s": 24192, "text": "A Button is an essential part of an application, or software, or webpage. It allows the user to interact with the application or software. In Button, you are allowed to set the space between two or more Button controls using Margin Property. You can use this property in two different methods:" }, { "code": null, "e": 24601, "s": 24486, "text": "1. Design-Time: It is the easiest method to set the margin between two button controls. Using the following steps:" }, { "code": null, "e": 24717, "s": 24601, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 24894, "s": 24717, "text": "Step 2: Drag the Button control from the ToolBox and Drop it on the windows form. You are allowed to place a Button control anywhere on the windows form according to your need." }, { "code": null, "e": 25023, "s": 24894, "text": "Step 3: After drag and drop you will go to the properties of the Button control to set the Margin property of the Button.Output:" }, { "code": null, "e": 25031, "s": 25023, "text": "Output:" }, { "code": null, "e": 25202, "s": 25031, "text": "Run-Time: It is a little bit trickier than the above method. In this method, you can set the Margin property of the Button programmatically with the help of given syntax:" }, { "code": null, "e": 25259, "s": 25202, "text": "public System.Windows.Forms.Padding Margin { get; set; }" }, { "code": null, "e": 25393, "s": 25259, "text": "Here, the Padding is used to represent the space between controls. Following steps are used to set the Margin property of the Button:" }, { "code": null, "e": 25551, "s": 25393, "text": "Step 1: Create a button using the Button() constructor is provided by the Button class.// Creating Button using Button class\nButton MyButton = new Button();\n" }, { "code": null, "e": 25622, "s": 25551, "text": "// Creating Button using Button class\nButton MyButton = new Button();\n" }, { "code": null, "e": 25796, "s": 25622, "text": "Step 2: After creating Button, set the Margin property of the Button provided by the Button class.// Set the margin of the button\nMybutton.Margin = new Padding(5, 5, 5, 5);\n" }, { "code": null, "e": 25872, "s": 25796, "text": "// Set the margin of the button\nMybutton.Margin = new Padding(5, 5, 5, 5);\n" }, { "code": null, "e": 27699, "s": 25872, "text": "Step 3: And last add this button control to form using Add() method.// Add this Button to form\nthis.Controls.Add(Mybutton);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp8 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.AutoSize = true; l.Text = \"Do you want to submit this form?\"; l.Location = new Point(222, 145); l.Font = new Font(\"French Script MT\", 18); // Adding this label to form this.Controls.Add(l); // Creating and setting the properties of Button Button Mybutton = new Button(); Mybutton.Location = new Point(225, 198); Mybutton.Text = \"Submit\"; Mybutton.AutoSize = true; Mybutton.BackColor = Color.LightBlue; Mybutton.Padding = new Padding(6); Mybutton.Font = new Font(\"French Script MT\", 18); Mybutton.Margin = new Padding(5, 5, 5, 5); // Adding this button to form this.Controls.Add(Mybutton); // Creating and setting the properties of Button Button Mybutton1 = new Button(); Mybutton1.Location = new Point(360, 198); Mybutton1.Text = \"Cancel\"; Mybutton1.AutoSize = true; Mybutton1.BackColor = Color.LightPink; Mybutton1.Padding = new Padding(6); Mybutton1.Font = new Font(\"French Script MT\", 18); Mybutton1.Margin = new Padding(5, 5, 5, 5); // Adding this button to form this.Controls.Add(Mybutton1); }}}Output:" }, { "code": null, "e": 27756, "s": 27699, "text": "// Add this Button to form\nthis.Controls.Add(Mybutton);\n" }, { "code": null, "e": 27765, "s": 27756, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp8 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.AutoSize = true; l.Text = \"Do you want to submit this form?\"; l.Location = new Point(222, 145); l.Font = new Font(\"French Script MT\", 18); // Adding this label to form this.Controls.Add(l); // Creating and setting the properties of Button Button Mybutton = new Button(); Mybutton.Location = new Point(225, 198); Mybutton.Text = \"Submit\"; Mybutton.AutoSize = true; Mybutton.BackColor = Color.LightBlue; Mybutton.Padding = new Padding(6); Mybutton.Font = new Font(\"French Script MT\", 18); Mybutton.Margin = new Padding(5, 5, 5, 5); // Adding this button to form this.Controls.Add(Mybutton); // Creating and setting the properties of Button Button Mybutton1 = new Button(); Mybutton1.Location = new Point(360, 198); Mybutton1.Text = \"Cancel\"; Mybutton1.AutoSize = true; Mybutton1.BackColor = Color.LightPink; Mybutton1.Padding = new Padding(6); Mybutton1.Font = new Font(\"French Script MT\", 18); Mybutton1.Margin = new Padding(5, 5, 5, 5); // Adding this button to form this.Controls.Add(Mybutton1); }}}", "e": 29453, "s": 27765, "text": null }, { "code": null, "e": 29461, "s": 29453, "text": "Output:" }, { "code": null, "e": 29464, "s": 29461, "text": "C#" }, { "code": null, "e": 29562, "s": 29464, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29585, "s": 29562, "text": "C# | Method Overriding" }, { "code": null, "e": 29613, "s": 29585, "text": "C# Dictionary with examples" }, { "code": null, "e": 29628, "s": 29613, "text": "C# | Delegates" }, { "code": null, "e": 29674, "s": 29628, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 29692, "s": 29674, "text": "Destructors in C#" }, { "code": null, "e": 29715, "s": 29692, "text": "Extension Method in C#" }, { "code": null, "e": 29733, "s": 29715, "text": "C# | Constructors" }, { "code": null, "e": 29755, "s": 29733, "text": "C# | Abstract Classes" }, { "code": null, "e": 29795, "s": 29755, "text": "C# | String.IndexOf( ) Method | Set - 1" } ]
How to Use Terminal in Sublime Text Editor ? - GeeksforGeeks
06 Jun, 2021 Well in Visual Studio Code we get a direct Option for opening Terminal, Unlike Sublime Text editor. Sublime is Simple and free to use, Light on memory, and can easily work with multiple projects. In this article, we will see how to use the terminal in a sublime text editor. Step 1: Open Sublime Text, Step 2: Open Command Palette using command Ctrl+shift+p Type the below until the option appears and select it. Package Control: Install Package Note: You’ll need to install package control if you are using it for the first time. Type ‘Terminus’ and select it. Wait for it to Complete installation and Restart sublime text. Step 3: Now go to Preferences >Package Settings > Terminus > Command Palette Now paste this code in the Default sublime Commands Section [ { "caption": "Terminal (panel)", "command": "terminus_open", "args" : { "cmd": "bash", "cwd": "${file_path:${folder}}", "title": "Command Prompt", "panel_name": "Terminus" } }, ] And save it. Note: The above code is for Linux users for Windows users you have to enter “cmd.exe” in place of “bash” Step 4: Now go to Preferences >Package Settings > Terminus > Key Bindings Now paste this code in the Default sublime Keymap Section and save it: [ { "keys": ["alt+1"], "command": "terminus_open", "args" : { "cmd": "bash", "cwd": "${file_path:${folder}}", "panel_name": "Terminus" } } ] Note: The above code is for Linux users for Windows users you have to enter “cmd.exe” in place of “bash”, also here we kept the shortcut key as “alt+1” you can use your own key. Step 5: So whenever you want to use terminal press alt+1 and to close terminal type exit in the terminal and hit enter. How To Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install FFmpeg on Windows? How to Set Git Username and Password in GitBash? How to Add External JAR File to an IntelliJ IDEA Project? How to Create and Setup Spring Boot Project in Eclipse IDE? How to Install Jupyter Notebook on MacOS? Sed Command in Linux/Unix with examples AWK command in Unix/Linux with examples grep command in Unix/Linux cut command in Linux with examples TCP Server-Client implementation in C
[ { "code": null, "e": 24976, "s": 24948, "text": "\n06 Jun, 2021" }, { "code": null, "e": 25251, "s": 24976, "text": "Well in Visual Studio Code we get a direct Option for opening Terminal, Unlike Sublime Text editor. Sublime is Simple and free to use, Light on memory, and can easily work with multiple projects. In this article, we will see how to use the terminal in a sublime text editor." }, { "code": null, "e": 25278, "s": 25251, "text": "Step 1: Open Sublime Text," }, { "code": null, "e": 25334, "s": 25278, "text": "Step 2: Open Command Palette using command Ctrl+shift+p" }, { "code": null, "e": 25389, "s": 25334, "text": "Type the below until the option appears and select it." }, { "code": null, "e": 25422, "s": 25389, "text": "Package Control: Install Package" }, { "code": null, "e": 25507, "s": 25422, "text": "Note: You’ll need to install package control if you are using it for the first time." }, { "code": null, "e": 25601, "s": 25507, "text": "Type ‘Terminus’ and select it. Wait for it to Complete installation and Restart sublime text." }, { "code": null, "e": 25678, "s": 25601, "text": "Step 3: Now go to Preferences >Package Settings > Terminus > Command Palette" }, { "code": null, "e": 25738, "s": 25678, "text": "Now paste this code in the Default sublime Commands Section" }, { "code": null, "e": 26005, "s": 25738, "text": "[\n {\n \"caption\": \"Terminal (panel)\",\n \"command\": \"terminus_open\",\n \"args\" : {\n \"cmd\": \"bash\",\n \"cwd\": \"${file_path:${folder}}\",\n \"title\": \"Command Prompt\",\n \"panel_name\": \"Terminus\"\n }\n },\n] " }, { "code": null, "e": 26018, "s": 26005, "text": "And save it." }, { "code": null, "e": 26123, "s": 26018, "text": "Note: The above code is for Linux users for Windows users you have to enter “cmd.exe” in place of “bash”" }, { "code": null, "e": 26197, "s": 26123, "text": "Step 4: Now go to Preferences >Package Settings > Terminus > Key Bindings" }, { "code": null, "e": 26268, "s": 26197, "text": "Now paste this code in the Default sublime Keymap Section and save it:" }, { "code": null, "e": 26477, "s": 26268, "text": "[\n {\n \"keys\": [\"alt+1\"],\n \"command\": \"terminus_open\",\n \"args\" : {\n \"cmd\": \"bash\",\n \"cwd\": \"${file_path:${folder}}\",\n \"panel_name\": \"Terminus\"\n }\n }\n] " }, { "code": null, "e": 26655, "s": 26477, "text": "Note: The above code is for Linux users for Windows users you have to enter “cmd.exe” in place of “bash”, also here we kept the shortcut key as “alt+1” you can use your own key." }, { "code": null, "e": 26775, "s": 26655, "text": "Step 5: So whenever you want to use terminal press alt+1 and to close terminal type exit in the terminal and hit enter." }, { "code": null, "e": 26782, "s": 26775, "text": "How To" }, { "code": null, "e": 26793, "s": 26782, "text": "Linux-Unix" }, { "code": null, "e": 26891, "s": 26793, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26900, "s": 26891, "text": "Comments" }, { "code": null, "e": 26913, "s": 26900, "text": "Old Comments" }, { "code": null, "e": 26947, "s": 26913, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 26996, "s": 26947, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 27054, "s": 26996, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 27114, "s": 27054, "text": "How to Create and Setup Spring Boot Project in Eclipse IDE?" }, { "code": null, "e": 27156, "s": 27114, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 27196, "s": 27156, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 27236, "s": 27196, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 27263, "s": 27236, "text": "grep command in Unix/Linux" }, { "code": null, "e": 27298, "s": 27263, "text": "cut command in Linux with examples" } ]
How to declare a constructor in Java?
While declaring the constructors you should keep the following points in mind. A constructor does not have a return type. The name of the constructor is same as the name of the class. A class can have more than one constructor. public class Sample { int num; public Sample() { num = 30; } public Sample(int value) { num = value; } }
[ { "code": null, "e": 1141, "s": 1062, "text": "While declaring the constructors you should keep the following points in mind." }, { "code": null, "e": 1184, "s": 1141, "text": "A constructor does not have a return type." }, { "code": null, "e": 1246, "s": 1184, "text": "The name of the constructor is same as the name of the class." }, { "code": null, "e": 1291, "s": 1246, "text": " A class can have more than one constructor." }, { "code": null, "e": 1423, "s": 1291, "text": "public class Sample {\n int num;\n public Sample() {\n num = 30;\n }\n public Sample(int value) {\n num = value;\n }\n}" } ]
Responsive grid with Bootstrap
To create a responsive grid in Bootstrap, use the .col-*-* class in Bootstrap. In the below example, we have 4 divs − Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet"> <script src = "/scripts/jquery.min.js"></script> <script src = "/bootstrap/js/bootstrap.min.js"></script> </head> <body> <div class = "container-fluid"> <div class = "row"> <div class = "col-sm-3 col-md-6 col-lg-4" style = "color:white;background-color:orange;"> This is div1. </div> <div class = "col-sm-9 col-md-6 col-lg-8" style = "color:white;background-color:blue;"> This is div2. </div> <div class = "col-sm-3 col-md-6 col-lg-4" style = "color:white;background-color:green;"> This is div3. </div> <div class = "col-sm-9 col-md-6 col-lg-8" style = "color:white;background-color:gray;"> This is div4. </div> </div> </div> </body> </html>
[ { "code": null, "e": 1141, "s": 1062, "text": "To create a responsive grid in Bootstrap, use the .col-*-* class in Bootstrap." }, { "code": null, "e": 1180, "s": 1141, "text": "In the below example, we have 4 divs −" }, { "code": null, "e": 1190, "s": 1180, "text": "Live Demo" }, { "code": null, "e": 2185, "s": 1190, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"container-fluid\">\n <div class = \"row\">\n <div class = \"col-sm-3 col-md-6 col-lg-4\" style = \"color:white;background-color:orange;\">\n This is div1.\n </div>\n <div class = \"col-sm-9 col-md-6 col-lg-8\" style = \"color:white;background-color:blue;\">\n This is div2.\n </div>\n <div class = \"col-sm-3 col-md-6 col-lg-4\" style = \"color:white;background-color:green;\">\n This is div3.\n </div>\n <div class = \"col-sm-9 col-md-6 col-lg-8\" style = \"color:white;background-color:gray;\">\n This is div4.\n </div>\n </div>\n </div>\n </body>\n</html>" } ]
Java Concurrency - Condition Interface
A java.util.concurrent.locks.Condition interface provides a thread ability to suspend its execution, until the given condition is true. A Condition object is necessarily bound to a Lock and to be obtained using the newCondition() method. Following is the list of important methods available in the Condition class. public void await() Causes the current thread to wait until it is signalled or interrupted. public boolean await(long time, TimeUnit unit) Causes the current thread to wait until it is signalled or interrupted, or the specified waiting time elapses. public long awaitNanos(long nanosTimeout) Causes the current thread to wait until it is signalled or interrupted, or the specified waiting time elapses. public long awaitUninterruptibly() Causes the current thread to wait until it is signalled. public long awaitUntil() Causes the current thread to wait until it is signalled or interrupted, or the specified deadline elapses. public void signal() Wakes up one waiting thread. public void signalAll() Wakes up all waiting threads. import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class TestThread { public static void main(String[] args) throws InterruptedException { ItemQueue itemQueue = new ItemQueue(10); //Create a producer and a consumer. Thread producer = new Producer(itemQueue); Thread consumer = new Consumer(itemQueue); //Start both threads. producer.start(); consumer.start(); //Wait for both threads to terminate. producer.join(); consumer.join(); } static class ItemQueue { private Object[] items = null; private int current = 0; private int placeIndex = 0; private int removeIndex = 0; private final Lock lock; private final Condition isEmpty; private final Condition isFull; public ItemQueue(int capacity) { this.items = new Object[capacity]; lock = new ReentrantLock(); isEmpty = lock.newCondition(); isFull = lock.newCondition(); } public void add(Object item) throws InterruptedException { lock.lock(); while(current >= items.length) isFull.await(); items[placeIndex] = item; placeIndex = (placeIndex + 1) % items.length; ++current; //Notify the consumer that there is data available. isEmpty.signal(); lock.unlock(); } public Object remove() throws InterruptedException { Object item = null; lock.lock(); while(current <= 0) { isEmpty.await(); } item = items[removeIndex]; removeIndex = (removeIndex + 1) % items.length; --current; //Notify the producer that there is space available. isFull.signal(); lock.unlock(); return item; } public boolean isEmpty() { return (items.length == 0); } } static class Producer extends Thread { private final ItemQueue queue; public Producer(ItemQueue queue) { this.queue = queue; } @Override public void run() { String[] numbers = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"}; try { for(String number: numbers) { System.out.println("[Producer]: " + number); } queue.add(null); } catch (InterruptedException ex) { ex.printStackTrace(); } } } static class Consumer extends Thread { private final ItemQueue queue; public Consumer(ItemQueue queue) { this.queue = queue; } @Override public void run() { try { do { Object number = queue.remove(); System.out.println("[Consumer]: " + number); if(number == null) { return; } } while(!queue.isEmpty()); } catch (InterruptedException ex) { ex.printStackTrace(); } } } } This will produce the following result. [Producer]: 1 [Producer]: 2 [Producer]: 3 [Producer]: 4 [Producer]: 5 [Producer]: 6 [Producer]: 7 [Producer]: 8 [Producer]: 9 [Producer]: 10 [Producer]: 11 [Producer]: 12 [Consumer]: null 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": 2895, "s": 2657, "text": "A java.util.concurrent.locks.Condition interface provides a thread ability to suspend its execution, until the given condition is true. A Condition object is necessarily bound to a Lock and to be obtained using the newCondition() method." }, { "code": null, "e": 2972, "s": 2895, "text": "Following is the list of important methods available in the Condition class." }, { "code": null, "e": 2992, "s": 2972, "text": "public void await()" }, { "code": null, "e": 3064, "s": 2992, "text": "Causes the current thread to wait until it is signalled or interrupted." }, { "code": null, "e": 3111, "s": 3064, "text": "public boolean await(long time, TimeUnit unit)" }, { "code": null, "e": 3222, "s": 3111, "text": "Causes the current thread to wait until it is signalled or interrupted, or the specified waiting time elapses." }, { "code": null, "e": 3264, "s": 3222, "text": "public long awaitNanos(long nanosTimeout)" }, { "code": null, "e": 3375, "s": 3264, "text": "Causes the current thread to wait until it is signalled or interrupted, or the specified waiting time elapses." }, { "code": null, "e": 3410, "s": 3375, "text": "public long awaitUninterruptibly()" }, { "code": null, "e": 3467, "s": 3410, "text": "Causes the current thread to wait until it is signalled." }, { "code": null, "e": 3492, "s": 3467, "text": "public long awaitUntil()" }, { "code": null, "e": 3599, "s": 3492, "text": "Causes the current thread to wait until it is signalled or interrupted, or the specified deadline elapses." }, { "code": null, "e": 3620, "s": 3599, "text": "public void signal()" }, { "code": null, "e": 3649, "s": 3620, "text": "Wakes up one waiting thread." }, { "code": null, "e": 3673, "s": 3649, "text": "public void signalAll()" }, { "code": null, "e": 3703, "s": 3673, "text": "Wakes up all waiting threads." }, { "code": null, "e": 6880, "s": 3703, "text": "import java.util.concurrent.locks.Condition;\nimport java.util.concurrent.locks.Lock;\nimport java.util.concurrent.locks.ReentrantLock;\n\npublic class TestThread {\n\n public static void main(String[] args) throws InterruptedException {\n ItemQueue itemQueue = new ItemQueue(10);\n\n //Create a producer and a consumer.\n Thread producer = new Producer(itemQueue);\n Thread consumer = new Consumer(itemQueue);\n\n //Start both threads.\n producer.start();\n consumer.start();\n\n //Wait for both threads to terminate.\n producer.join();\n consumer.join();\n }\n\n static class ItemQueue {\n private Object[] items = null;\n private int current = 0;\n private int placeIndex = 0;\n private int removeIndex = 0;\n\n private final Lock lock;\n private final Condition isEmpty;\n private final Condition isFull;\n\n public ItemQueue(int capacity) {\n this.items = new Object[capacity];\n lock = new ReentrantLock();\n isEmpty = lock.newCondition();\n isFull = lock.newCondition();\n }\n\n public void add(Object item) throws InterruptedException {\n lock.lock();\n\n while(current >= items.length)\n isFull.await();\n\n items[placeIndex] = item;\n placeIndex = (placeIndex + 1) % items.length;\n ++current;\n\n //Notify the consumer that there is data available.\n isEmpty.signal();\n lock.unlock();\n }\n\n public Object remove() throws InterruptedException {\n Object item = null;\n\n lock.lock();\n\n while(current <= 0) {\n isEmpty.await();\n }\n item = items[removeIndex];\n removeIndex = (removeIndex + 1) % items.length;\n --current;\n\n //Notify the producer that there is space available.\n isFull.signal();\n lock.unlock();\n\n return item;\n }\n\n public boolean isEmpty() {\n return (items.length == 0);\n }\n }\n\n static class Producer extends Thread {\n private final ItemQueue queue;\n \n public Producer(ItemQueue queue) {\n this.queue = queue;\n }\n\n @Override\n public void run() {\n String[] numbers =\n {\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\", \"12\"};\n\n try {\n \n for(String number: numbers) {\n System.out.println(\"[Producer]: \" + number);\n }\n queue.add(null);\n } catch (InterruptedException ex) {\n ex.printStackTrace();\n } \n }\n }\n\n static class Consumer extends Thread {\n private final ItemQueue queue;\n \n public Consumer(ItemQueue queue) {\n this.queue = queue;\n }\n\n @Override\n public void run() {\n \n try {\n \n do {\n Object number = queue.remove();\n System.out.println(\"[Consumer]: \" + number);\n\n if(number == null) {\n return;\n }\n } while(!queue.isEmpty());\n } catch (InterruptedException ex) {\n ex.printStackTrace();\n }\n }\n }\n}" }, { "code": null, "e": 6920, "s": 6880, "text": "This will produce the following result." }, { "code": null, "e": 7109, "s": 6920, "text": "[Producer]: 1\n[Producer]: 2\n[Producer]: 3\n[Producer]: 4\n[Producer]: 5\n[Producer]: 6\n[Producer]: 7\n[Producer]: 8\n[Producer]: 9\n[Producer]: 10\n[Producer]: 11\n[Producer]: 12\n[Consumer]: null\n" }, { "code": null, "e": 7142, "s": 7109, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 7158, "s": 7142, "text": " Malhar Lathkar" }, { "code": null, "e": 7191, "s": 7158, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 7207, "s": 7191, "text": " Malhar Lathkar" }, { "code": null, "e": 7242, "s": 7207, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7256, "s": 7242, "text": " Anadi Sharma" }, { "code": null, "e": 7290, "s": 7256, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 7304, "s": 7290, "text": " Tushar Kale" }, { "code": null, "e": 7341, "s": 7304, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 7356, "s": 7341, "text": " Monica Mittal" }, { "code": null, "e": 7389, "s": 7356, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 7408, "s": 7389, "text": " Arnab Chakraborty" }, { "code": null, "e": 7415, "s": 7408, "text": " Print" }, { "code": null, "e": 7426, "s": 7415, "text": " Add Notes" } ]
How to compare two DataFrames in Python Pandas with missing values
Pandas uses the NumPy NaN (np.nan) object to represent a missing value. This Numpy NaN value has some interesting mathematical properties. For example, it is not equal to itself. However, Python None object evaluates as True when compared to itself. Let us see some examples to understand how np.nan behaves. import pandas as pd import numpy as np # Python None Object compared against self. print(f"Output \n *** {None == None} ") *** True # Numpy nan compared against self. print(f"Output \n *** {np.nan == np.nan} ") *** False # Is nan > 10 or 1000 ? print(f"Output \n *** {np.nan > 10} ") *** False Traditionally, Series and DataFrames use the equals operator, ==, to make comparisons. The result of the comparsions is an object. Let us first see how to use the equals operator. # create a dataframe with tennis players and their grandslam titles. df = pd.DataFrame(data={"players": ['Federer', 'Nadal', 'Djokovic', 'Murray','Medvedev','Zverev'], "titles": [20, 19, 17, 3,np.nan,np.nan]}) # set the index df.index = df['players'] # sort the index in ascending df.sort_index(inplace=True, ascending=True) # check if the index is set df.index.is_monotonic_increasing # see records print(f"Output \n{df}") players titles players Djokovic Djokovic 17.0 Federer Federer 20.0 Medvedev Medvedev NaN Murray Murray 3.0 Nadal Nadal 19.0 Zverev Zverev NaN 1. To better understand, we will first compare all the players to a scalar value "Federer" and see the results. print(f'Output \n {df == "Federer"}') players titles players Djokovic False False Federer True False Medvedev False False Murray False False Nadal False False Zverev False False C:\Users\sasan\anaconda3\lib\site-packages\pandas\core\ops\array_ops.py:253: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison res_values = method(rvalues) 2. This works as expected but becomes problematic whenever you try to compare DataFrames with missing values. To observer this let us compare the df against self. df_compare = df == df print(f'Output \n {df_compare}') players titles players Djokovic True True Federer True True Medvedev True False Murray True True Nadal True True Zverev True False 3. At first glance, all the values might appear to be correct, as you would expect. However, use the .all method to see if each column contains only True values (as it should be as we are comparing two similar objects right?) yields an unexpected result. print(f'Output \n {df_compare.all()}') players True titles False dtype: bool 4.As mentioned in earlier notes, this happens because missing values do not compare equally with one another. See, we clearly know that medvedev and Zverev have no titles (i.e. NaN) so if we add the number of missing values in each column we should get the value 2 for titles and 0 for players. Let us see what happens. print(f'Output \n {(df_compare == np.nan).sum()}') players 0 titles 0 dtype: int64 5. ABove result is unexpected as nan behaves very differently. 6. The correct way to compare two entire DataFrames with one another is not with the equals operator (==) but with the .equals method. This method treats NaNs that are in the same location as equal. AN important note the .eq method is the equivalent of == not .equals. print(f'Output \n {df_compare.equals(df_compare)}') True 7. There is also another way of doing if you are trying to compare two DataFrames as part of your unit testing. The assert_frame_equal function raises an AssertionError if two DataFrames are not equal. It returns None if the two DataFrames are equal. from pandas.testing import assert_frame_equal print(f'Output \n {assert_frame_equal(df_compare, df_compare) is None}') True
[ { "code": null, "e": 1312, "s": 1062, "text": "Pandas uses the NumPy NaN (np.nan) object to represent a missing value. This Numpy NaN value has some interesting mathematical properties. For example, it is not equal to itself. However, Python None object evaluates as True when compared to itself." }, { "code": null, "e": 1371, "s": 1312, "text": "Let us see some examples to understand how np.nan behaves." }, { "code": null, "e": 1495, "s": 1371, "text": "import pandas as pd\nimport numpy as np\n\n# Python None Object compared against self.\nprint(f\"Output \\n *** {None == None} \")" }, { "code": null, "e": 1504, "s": 1495, "text": "*** True" }, { "code": null, "e": 1583, "s": 1504, "text": "# Numpy nan compared against self.\nprint(f\"Output \\n *** {np.nan == np.nan} \")" }, { "code": null, "e": 1593, "s": 1583, "text": "*** False" }, { "code": null, "e": 1656, "s": 1593, "text": "# Is nan > 10 or 1000 ?\nprint(f\"Output \\n *** {np.nan > 10} \")" }, { "code": null, "e": 1666, "s": 1656, "text": "*** False" }, { "code": null, "e": 1846, "s": 1666, "text": "Traditionally, Series and DataFrames use the equals operator, ==, to make comparisons. The result of the comparsions is an object. Let us first see how to use the equals operator." }, { "code": null, "e": 2273, "s": 1846, "text": "# create a dataframe with tennis players and their grandslam titles.\ndf = pd.DataFrame(data={\"players\": ['Federer', 'Nadal', 'Djokovic', 'Murray','Medvedev','Zverev'],\n\"titles\": [20, 19, 17, 3,np.nan,np.nan]})\n# set the index\ndf.index = df['players']\n\n# sort the index in ascending\ndf.sort_index(inplace=True, ascending=True)\n\n# check if the index is set\ndf.index.is_monotonic_increasing\n\n# see records\nprint(f\"Output \\n{df}\")" }, { "code": null, "e": 2464, "s": 2273, "text": " players titles\nplayers\nDjokovic Djokovic 17.0\nFederer Federer 20.0\nMedvedev Medvedev NaN\nMurray Murray 3.0\nNadal Nadal 19.0\nZverev Zverev NaN" }, { "code": null, "e": 2576, "s": 2464, "text": "1. To better understand, we will first compare all the players to a scalar value \"Federer\" and see the results." }, { "code": null, "e": 2614, "s": 2576, "text": "print(f'Output \\n {df == \"Federer\"}')" }, { "code": null, "e": 2818, "s": 2614, "text": " players titles\nplayers\nDjokovic False False\nFederer True False\nMedvedev False False\nMurray False False\nNadal False False\nZverev False False" }, { "code": null, "e": 3050, "s": 2818, "text": "C:\\Users\\sasan\\anaconda3\\lib\\site-packages\\pandas\\core\\ops\\array_ops.py:253: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison\nres_values = method(rvalues)" }, { "code": null, "e": 3213, "s": 3050, "text": "2. This works as expected but becomes problematic whenever you try to compare DataFrames with missing values. To observer this let us compare the df against self." }, { "code": null, "e": 3268, "s": 3213, "text": "df_compare = df == df\nprint(f'Output \\n {df_compare}')" }, { "code": null, "e": 3399, "s": 3268, "text": "players titles\nplayers\nDjokovic True True\nFederer True True\nMedvedev True False\nMurray True True\nNadal True True\nZverev True False" }, { "code": null, "e": 3654, "s": 3399, "text": "3. At first glance, all the values might appear to be correct, as you would expect. However, use the .all method to see if each column contains only True values (as it should be as we are comparing two similar objects right?) yields an unexpected result." }, { "code": null, "e": 3693, "s": 3654, "text": "print(f'Output \\n {df_compare.all()}')" }, { "code": null, "e": 3731, "s": 3693, "text": "players True\ntitles False\ndtype: bool" }, { "code": null, "e": 4051, "s": 3731, "text": "4.As mentioned in earlier notes, this happens because missing values do not compare equally with one another. See, we clearly know that medvedev and Zverev have no titles (i.e. NaN) so if we add the number of missing values in each column we should get the value 2 for titles and 0 for players. Let us see what happens." }, { "code": null, "e": 4102, "s": 4051, "text": "print(f'Output \\n {(df_compare == np.nan).sum()}')" }, { "code": null, "e": 4134, "s": 4102, "text": "players 0\ntitles 0\ndtype: int64" }, { "code": null, "e": 4197, "s": 4134, "text": "5. ABove result is unexpected as nan behaves very differently." }, { "code": null, "e": 4332, "s": 4197, "text": "6. The correct way to compare two entire DataFrames with one another is not with the equals operator (==) but with the .equals method." }, { "code": null, "e": 4396, "s": 4332, "text": "This method treats NaNs that are in the same location as equal." }, { "code": null, "e": 4466, "s": 4396, "text": "AN important note the .eq method is the equivalent of == not .equals." }, { "code": null, "e": 4518, "s": 4466, "text": "print(f'Output \\n {df_compare.equals(df_compare)}')" }, { "code": null, "e": 4523, "s": 4518, "text": "True" }, { "code": null, "e": 4774, "s": 4523, "text": "7. There is also another way of doing if you are trying to compare two DataFrames as part of your unit testing. The assert_frame_equal function raises an AssertionError if two DataFrames are not equal. It returns None if the two DataFrames are equal." }, { "code": null, "e": 4893, "s": 4774, "text": "from pandas.testing import assert_frame_equal\nprint(f'Output \\n {assert_frame_equal(df_compare, df_compare) is None}')" }, { "code": null, "e": 4898, "s": 4893, "text": "True" } ]
Collections Class in Java - GeeksforGeeks
20 Apr, 2022 Collections class is a member of the Java Collections Framework. The java.util.Collections package is the package that contains the Collections class. Collections class is basically used with the static methods that operate on the collections or return the collection. All the methods of this class throw the NullPointerException if the collection or object passed to the methods is null. Syntax: Declaration public class Collections extends Object Remember: Object is the parent class of all the classes. Collections class fields The collection class basically contains 3 fields as listed below which can be used to return immutable entities. EMPTY_LIST to get an immutable empty List EMPTY_SET to get an immutable empty Set EMPTY_MAP to get an immutable empty Map Now let us do discuss methods that are present inside this class so that we can implement these inbuilt functionalities later on in our program. Below are the methods been listed below in a tabular format as shown below as follows: Methods Description Now, we are done with listing all the methods so by ar we have a faint hint with us in perceiving how important are these methods when thinking about a global programming perspective. The important and frequently widely used methods while writing optimized code as you will see these methods somehow in nearly every java optimized code because of havoc usage of Collections class in java. So here more likely in any class we will not just be implementing the method but will also be discussing operations that can be performed so that one can have conceptual clarity and strong command while implementing the same. The operations that we will be discussing are as follows: Adding elements to the Collections Sorting a Collection Searching in a Collection Copying Elements Disjoint Collection Operation 1: Adding elements to the Collections class object The addAll() method of java.util.Collections class is used to add all the specified elements to the specified collection. Elements to be added may be specified individually or as an array. Example Java // Java Program to Demonstrate Adding Elements// Using addAll() method // Importing required classesimport java.util.ArrayList;import java.util.Collections;import java.util.List; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating a list // Declaring object of string type List<String> items = new ArrayList<>(); // Adding elements (items) to the list items.add("Shoes"); items.add("Toys"); // Add one or more elements Collections.addAll(items, "Fruits", "Bat", "Ball"); // Printing the list contents for (int i = 0; i < items.size(); i++) { System.out.print(items.get(i) + " "); } }} Shoes Toys Fruits Bat Ball Operation 2: Sorting a Collection java.util.Collections.sort() is used to sort the elements present in the specified list of Collection in ascending order. java.util.Collections.reverseOrder() is used to sort in the descending order. Example Java // Java program to demonstrate sorting// a Collections using sort() method import java.util.ArrayList;import java.util.Collections;import java.util.List; // Main Class// SortingCollectionExampleclass GFG { // Main driver method public static void main(String[] args) { // Creating a list // Declaring object of string type List<String> items = new ArrayList<>(); // Adding elements to the list // using add() method items.add("Shoes"); items.add("Toys"); // Adding one or more elements using addAll() Collections.addAll(items, "Fruits", "Bat", "Mouse"); // Sorting according to default ordering // using sort() method Collections.sort(items); // Printing the elements for (int i = 0; i < items.size(); i++) { System.out.print(items.get(i) + " "); } System.out.println(); // Sorting according to reverse ordering Collections.sort(items, Collections.reverseOrder()); // Printing the reverse order for (int i = 0; i < items.size(); i++) { System.out.print(items.get(i) + " "); } }} Bat Fruits Mouse Shoes Toys Toys Shoes Mouse Fruits Bat Operation 3: Searching in a Collection java.util.Collections.binarySearch() method returns the position of an object in a sorted list. To use this method, the list should be sorted in ascending order, otherwise, the result returned from the method will be wrong. If the element exists in the list, the method will return the position of the element in the sorted list, otherwise, the result returned by the method would be the – (insertion point where the element should have been present if exist)-1). Example Java // Java Program to Demonstrate Binary Search// Using Collections.binarySearch() // Importing required classesimport java.util.ArrayList;import java.util.Collections;import java.util.List; // Main class// BinarySearchOnACollectionpublic class GFG { // Main driver method public static void main(String[] args) { // Creating a List // Declaring object of string type List<String> items = new ArrayList<>(); // Adding elements to object // using add() method items.add("Shoes"); items.add("Toys"); items.add("Horse"); items.add("Ball"); items.add("Grapes"); // Sort the List Collections.sort(items); // BinarySearch on the List System.out.println( "The index of Horse is " + Collections.binarySearch(items, "Horse")); // BinarySearch on the List System.out.println( "The index of Dog is " + Collections.binarySearch(items, "Dog")); }} The index of Horse is 2 The index of Dog is -2 Operation 4: Copying Elements The copy() method of java.util.Collections class is used to copy all the elements from one list into another. After the operation, the index of each copied element in the destination list will be identical to its index in the source list. The destination list must be at least as long as the source list. If it is longer, the remaining elements in the destination list are unaffected. Example Java // Java Program to Demonstrate Copying Elements// Using copy() method // Importing required classesimport java.util.ArrayList;import java.util.Collections;import java.util.List; // Main class// CopyOneCollectionToAnotherclass GFG { // Main driver method public static void main(String[] args) { // Create destination list List<String> destination_List = new ArrayList<>(); // Add elements destination_List.add("Shoes"); destination_List.add("Toys"); destination_List.add("Horse"); destination_List.add("Tiger"); // Print the elements System.out.println( "The Original Destination list is "); for (int i = 0; i < destination_List.size(); i++) { System.out.print(destination_List.get(i) + " "); } System.out.println(); // Create source list List<String> source_List = new ArrayList<>(); // Add elements source_List.add("Bat"); source_List.add("Frog"); source_List.add("Lion"); // Copy the elements from source to destination Collections.copy(destination_List, source_List); // Printing the modified list System.out.println( "The Destination List After copying is "); for (int i = 0; i < destination_List.size(); i++) { System.out.print(destination_List.get(i) + " "); } }} The Original Destination list is Shoes Toys Horse Tiger The Destination List After copying is Bat Frog Lion Tiger Operation 5: Disjoint Collection java.util.Collections.disjoint() is used to check whether two specified collections are disjoint or not. More formally, two collections are disjoint if they have no elements in common. It returns true if the two collections do not have any element in common. Example Java // Java Program to Illustrate Working of Disjoint Function // Importing required classesimport java.util.ArrayList;import java.util.Collections;import java.util.List; // Main class// DisjointCollectionsExampleclass GFG { // Main driver method public static void main(String[] args) { // Create list1 List<String> list1 = new ArrayList<>(); // Add elements to list1 list1.add("Shoes"); list1.add("Toys"); list1.add("Horse"); list1.add("Tiger"); // Create list2 List<String> list2 = new ArrayList<>(); // Add elements to list2 list2.add("Bat"); list2.add("Frog"); list2.add("Lion"); // Check if disjoint or not System.out.println( Collections.disjoint(list1, list2)); }} true ayusmanmishra1999 akshaysingh98088 martialcoder rushalichaurasiya Java-Collections Picked Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java Initialize an ArrayList in Java How to iterate any Map in Java Singleton Class in Java Different ways of Reading a text file in Java Initializing a List in Java Stream In Java How to add an element to an Array in Java?
[ { "code": null, "e": 28950, "s": 28922, "text": "\n20 Apr, 2022" }, { "code": null, "e": 29341, "s": 28950, "text": "Collections class is a member of the Java Collections Framework. The java.util.Collections package is the package that contains the Collections class. Collections class is basically used with the static methods that operate on the collections or return the collection. All the methods of this class throw the NullPointerException if the collection or object passed to the methods is null. " }, { "code": null, "e": 29361, "s": 29341, "text": "Syntax: Declaration" }, { "code": null, "e": 29401, "s": 29361, "text": "public class Collections\nextends Object" }, { "code": null, "e": 29458, "s": 29401, "text": "Remember: Object is the parent class of all the classes." }, { "code": null, "e": 29483, "s": 29458, "text": "Collections class fields" }, { "code": null, "e": 29596, "s": 29483, "text": "The collection class basically contains 3 fields as listed below which can be used to return immutable entities." }, { "code": null, "e": 29638, "s": 29596, "text": "EMPTY_LIST to get an immutable empty List" }, { "code": null, "e": 29678, "s": 29638, "text": "EMPTY_SET to get an immutable empty Set" }, { "code": null, "e": 29718, "s": 29678, "text": "EMPTY_MAP to get an immutable empty Map" }, { "code": null, "e": 29950, "s": 29718, "text": "Now let us do discuss methods that are present inside this class so that we can implement these inbuilt functionalities later on in our program. Below are the methods been listed below in a tabular format as shown below as follows:" }, { "code": null, "e": 29958, "s": 29950, "text": "Methods" }, { "code": null, "e": 29970, "s": 29958, "text": "Description" }, { "code": null, "e": 30643, "s": 29970, "text": "Now, we are done with listing all the methods so by ar we have a faint hint with us in perceiving how important are these methods when thinking about a global programming perspective. The important and frequently widely used methods while writing optimized code as you will see these methods somehow in nearly every java optimized code because of havoc usage of Collections class in java. So here more likely in any class we will not just be implementing the method but will also be discussing operations that can be performed so that one can have conceptual clarity and strong command while implementing the same. The operations that we will be discussing are as follows:" }, { "code": null, "e": 30679, "s": 30643, "text": "Adding elements to the Collections " }, { "code": null, "e": 30700, "s": 30679, "text": "Sorting a Collection" }, { "code": null, "e": 30726, "s": 30700, "text": "Searching in a Collection" }, { "code": null, "e": 30743, "s": 30726, "text": "Copying Elements" }, { "code": null, "e": 30763, "s": 30743, "text": "Disjoint Collection" }, { "code": null, "e": 30825, "s": 30763, "text": "Operation 1: Adding elements to the Collections class object " }, { "code": null, "e": 31014, "s": 30825, "text": "The addAll() method of java.util.Collections class is used to add all the specified elements to the specified collection. Elements to be added may be specified individually or as an array." }, { "code": null, "e": 31023, "s": 31014, "text": "Example " }, { "code": null, "e": 31028, "s": 31023, "text": "Java" }, { "code": "// Java Program to Demonstrate Adding Elements// Using addAll() method // Importing required classesimport java.util.ArrayList;import java.util.Collections;import java.util.List; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating a list // Declaring object of string type List<String> items = new ArrayList<>(); // Adding elements (items) to the list items.add(\"Shoes\"); items.add(\"Toys\"); // Add one or more elements Collections.addAll(items, \"Fruits\", \"Bat\", \"Ball\"); // Printing the list contents for (int i = 0; i < items.size(); i++) { System.out.print(items.get(i) + \" \"); } }}", "e": 31765, "s": 31028, "text": null }, { "code": null, "e": 31793, "s": 31765, "text": "Shoes Toys Fruits Bat Ball " }, { "code": null, "e": 31828, "s": 31793, "text": " Operation 2: Sorting a Collection" }, { "code": null, "e": 32029, "s": 31828, "text": "java.util.Collections.sort() is used to sort the elements present in the specified list of Collection in ascending order. java.util.Collections.reverseOrder() is used to sort in the descending order. " }, { "code": null, "e": 32037, "s": 32029, "text": "Example" }, { "code": null, "e": 32042, "s": 32037, "text": "Java" }, { "code": "// Java program to demonstrate sorting// a Collections using sort() method import java.util.ArrayList;import java.util.Collections;import java.util.List; // Main Class// SortingCollectionExampleclass GFG { // Main driver method public static void main(String[] args) { // Creating a list // Declaring object of string type List<String> items = new ArrayList<>(); // Adding elements to the list // using add() method items.add(\"Shoes\"); items.add(\"Toys\"); // Adding one or more elements using addAll() Collections.addAll(items, \"Fruits\", \"Bat\", \"Mouse\"); // Sorting according to default ordering // using sort() method Collections.sort(items); // Printing the elements for (int i = 0; i < items.size(); i++) { System.out.print(items.get(i) + \" \"); } System.out.println(); // Sorting according to reverse ordering Collections.sort(items, Collections.reverseOrder()); // Printing the reverse order for (int i = 0; i < items.size(); i++) { System.out.print(items.get(i) + \" \"); } }}", "e": 33210, "s": 32042, "text": null }, { "code": null, "e": 33268, "s": 33210, "text": "Bat Fruits Mouse Shoes Toys \nToys Shoes Mouse Fruits Bat " }, { "code": null, "e": 33307, "s": 33268, "text": "Operation 3: Searching in a Collection" }, { "code": null, "e": 33772, "s": 33307, "text": "java.util.Collections.binarySearch() method returns the position of an object in a sorted list. To use this method, the list should be sorted in ascending order, otherwise, the result returned from the method will be wrong. If the element exists in the list, the method will return the position of the element in the sorted list, otherwise, the result returned by the method would be the – (insertion point where the element should have been present if exist)-1). " }, { "code": null, "e": 33780, "s": 33772, "text": "Example" }, { "code": null, "e": 33785, "s": 33780, "text": "Java" }, { "code": "// Java Program to Demonstrate Binary Search// Using Collections.binarySearch() // Importing required classesimport java.util.ArrayList;import java.util.Collections;import java.util.List; // Main class// BinarySearchOnACollectionpublic class GFG { // Main driver method public static void main(String[] args) { // Creating a List // Declaring object of string type List<String> items = new ArrayList<>(); // Adding elements to object // using add() method items.add(\"Shoes\"); items.add(\"Toys\"); items.add(\"Horse\"); items.add(\"Ball\"); items.add(\"Grapes\"); // Sort the List Collections.sort(items); // BinarySearch on the List System.out.println( \"The index of Horse is \" + Collections.binarySearch(items, \"Horse\")); // BinarySearch on the List System.out.println( \"The index of Dog is \" + Collections.binarySearch(items, \"Dog\")); }}", "e": 34790, "s": 33785, "text": null }, { "code": null, "e": 34837, "s": 34790, "text": "The index of Horse is 2\nThe index of Dog is -2" }, { "code": null, "e": 34867, "s": 34837, "text": "Operation 4: Copying Elements" }, { "code": null, "e": 35252, "s": 34867, "text": "The copy() method of java.util.Collections class is used to copy all the elements from one list into another. After the operation, the index of each copied element in the destination list will be identical to its index in the source list. The destination list must be at least as long as the source list. If it is longer, the remaining elements in the destination list are unaffected." }, { "code": null, "e": 35260, "s": 35252, "text": "Example" }, { "code": null, "e": 35265, "s": 35260, "text": "Java" }, { "code": "// Java Program to Demonstrate Copying Elements// Using copy() method // Importing required classesimport java.util.ArrayList;import java.util.Collections;import java.util.List; // Main class// CopyOneCollectionToAnotherclass GFG { // Main driver method public static void main(String[] args) { // Create destination list List<String> destination_List = new ArrayList<>(); // Add elements destination_List.add(\"Shoes\"); destination_List.add(\"Toys\"); destination_List.add(\"Horse\"); destination_List.add(\"Tiger\"); // Print the elements System.out.println( \"The Original Destination list is \"); for (int i = 0; i < destination_List.size(); i++) { System.out.print(destination_List.get(i) + \" \"); } System.out.println(); // Create source list List<String> source_List = new ArrayList<>(); // Add elements source_List.add(\"Bat\"); source_List.add(\"Frog\"); source_List.add(\"Lion\"); // Copy the elements from source to destination Collections.copy(destination_List, source_List); // Printing the modified list System.out.println( \"The Destination List After copying is \"); for (int i = 0; i < destination_List.size(); i++) { System.out.print(destination_List.get(i) + \" \"); } }}", "e": 36669, "s": 35265, "text": null }, { "code": null, "e": 36787, "s": 36669, "text": "The Original Destination list is \nShoes Toys Horse Tiger \nThe Destination List After copying is \nBat Frog Lion Tiger " }, { "code": null, "e": 36820, "s": 36787, "text": "Operation 5: Disjoint Collection" }, { "code": null, "e": 37080, "s": 36820, "text": "java.util.Collections.disjoint() is used to check whether two specified collections are disjoint or not. More formally, two collections are disjoint if they have no elements in common. It returns true if the two collections do not have any element in common. " }, { "code": null, "e": 37088, "s": 37080, "text": "Example" }, { "code": null, "e": 37093, "s": 37088, "text": "Java" }, { "code": "// Java Program to Illustrate Working of Disjoint Function // Importing required classesimport java.util.ArrayList;import java.util.Collections;import java.util.List; // Main class// DisjointCollectionsExampleclass GFG { // Main driver method public static void main(String[] args) { // Create list1 List<String> list1 = new ArrayList<>(); // Add elements to list1 list1.add(\"Shoes\"); list1.add(\"Toys\"); list1.add(\"Horse\"); list1.add(\"Tiger\"); // Create list2 List<String> list2 = new ArrayList<>(); // Add elements to list2 list2.add(\"Bat\"); list2.add(\"Frog\"); list2.add(\"Lion\"); // Check if disjoint or not System.out.println( Collections.disjoint(list1, list2)); }}", "e": 37895, "s": 37093, "text": null }, { "code": null, "e": 37900, "s": 37895, "text": "true" }, { "code": null, "e": 37918, "s": 37900, "text": "ayusmanmishra1999" }, { "code": null, "e": 37935, "s": 37918, "text": "akshaysingh98088" }, { "code": null, "e": 37948, "s": 37935, "text": "martialcoder" }, { "code": null, "e": 37966, "s": 37948, "text": "rushalichaurasiya" }, { "code": null, "e": 37983, "s": 37966, "text": "Java-Collections" }, { "code": null, "e": 37990, "s": 37983, "text": "Picked" }, { "code": null, "e": 37995, "s": 37990, "text": "Java" }, { "code": null, "e": 38000, "s": 37995, "text": "Java" }, { "code": null, "e": 38017, "s": 38000, "text": "Java-Collections" }, { "code": null, "e": 38115, "s": 38017, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38124, "s": 38115, "text": "Comments" }, { "code": null, "e": 38137, "s": 38124, "text": "Old Comments" }, { "code": null, "e": 38181, "s": 38137, "text": "Split() String method in Java with examples" }, { "code": null, "e": 38217, "s": 38181, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 38242, "s": 38217, "text": "Reverse a string in Java" }, { "code": null, "e": 38274, "s": 38242, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 38305, "s": 38274, "text": "How to iterate any Map in Java" }, { "code": null, "e": 38329, "s": 38305, "text": "Singleton Class in Java" }, { "code": null, "e": 38375, "s": 38329, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 38403, "s": 38375, "text": "Initializing a List in Java" }, { "code": null, "e": 38418, "s": 38403, "text": "Stream In Java" } ]
Remove Leading whitespaces from a String in R Language - trimws() Function - GeeksforGeeks
23 Dec, 2021 In this article, we are going to see how to remove whitespaces from a String in R Programming Language. trimws() function in R Language is used to trim the leading white spaces. It shrinks an object by removing outermost rows and columns with the same values. Syntax: trimws(x) Parameters: x: Object or character string R # R program to illustrate# Removing of leading whitespaces # Create example character stringmy_text <- " . This is a trim function example " # Apply trimws function in Rprint(trimws(my_text)) Output: ". This is a trim function example" Here in the above code, we have created a character string and have white spaces in it, So we have used the trimws() function to remove the white spaces. R # R program to illustrate# Removing of leading whitespaces # Create example character stringmy_text <- " Geeks_For_Geeks " # Apply trimws function in Rprint(trimws(my_text)) Output: "Geeks_For_Geeks " kumar_satyam Programming Language R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments R - Data Types 7 Highest Paying Programming Languages For Freelancers in 2022 Introduction of Object Oriented Programming R - Matrices R - Charts and Graphs Change column name of a given DataFrame in R How to Replace specific values in column in R DataFrame ? Adding elements in a vector in R programming - append() method How to change Row Names of DataFrame in R ? Filter data by multiple conditions in R using Dplyr
[ { "code": null, "e": 24321, "s": 24293, "text": "\n23 Dec, 2021" }, { "code": null, "e": 24425, "s": 24321, "text": "In this article, we are going to see how to remove whitespaces from a String in R Programming Language." }, { "code": null, "e": 24581, "s": 24425, "text": "trimws() function in R Language is used to trim the leading white spaces. It shrinks an object by removing outermost rows and columns with the same values." }, { "code": null, "e": 24599, "s": 24581, "text": "Syntax: trimws(x)" }, { "code": null, "e": 24612, "s": 24599, "text": "Parameters: " }, { "code": null, "e": 24642, "s": 24612, "text": "x: Object or character string" }, { "code": null, "e": 24644, "s": 24642, "text": "R" }, { "code": "# R program to illustrate# Removing of leading whitespaces # Create example character stringmy_text <- \" . This is a trim function example \" # Apply trimws function in Rprint(trimws(my_text))", "e": 24848, "s": 24644, "text": null }, { "code": null, "e": 24857, "s": 24848, "text": "Output: " }, { "code": null, "e": 24905, "s": 24857, "text": "\". This is a trim function example\"" }, { "code": null, "e": 25059, "s": 24905, "text": "Here in the above code, we have created a character string and have white spaces in it, So we have used the trimws() function to remove the white spaces." }, { "code": null, "e": 25061, "s": 25059, "text": "R" }, { "code": "# R program to illustrate# Removing of leading whitespaces # Create example character stringmy_text <- \" Geeks_For_Geeks \" # Apply trimws function in Rprint(trimws(my_text))", "e": 25243, "s": 25061, "text": null }, { "code": null, "e": 25251, "s": 25243, "text": "Output:" }, { "code": null, "e": 25274, "s": 25251, "text": "\"Geeks_For_Geeks \"" }, { "code": null, "e": 25287, "s": 25274, "text": "kumar_satyam" }, { "code": null, "e": 25308, "s": 25287, "text": "Programming Language" }, { "code": null, "e": 25319, "s": 25308, "text": "R Language" }, { "code": null, "e": 25417, "s": 25319, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25426, "s": 25417, "text": "Comments" }, { "code": null, "e": 25439, "s": 25426, "text": "Old Comments" }, { "code": null, "e": 25454, "s": 25439, "text": "R - Data Types" }, { "code": null, "e": 25517, "s": 25454, "text": "7 Highest Paying Programming Languages For Freelancers in 2022" }, { "code": null, "e": 25561, "s": 25517, "text": "Introduction of Object Oriented Programming" }, { "code": null, "e": 25574, "s": 25561, "text": "R - Matrices" }, { "code": null, "e": 25596, "s": 25574, "text": "R - Charts and Graphs" }, { "code": null, "e": 25641, "s": 25596, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 25699, "s": 25641, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 25762, "s": 25699, "text": "Adding elements in a vector in R programming - append() method" }, { "code": null, "e": 25806, "s": 25762, "text": "How to change Row Names of DataFrame in R ?" } ]
Getting first letter of each word in a String using regex in Java
A word is contiguous series of alphabetic characters. Using regex, we need to search the boundary character to be between A to Z or a to z. Consider the following cases − Input: Hello World Output: H W Input: Welcome to world of Regex Output: W t w o R We'll use the regex as "\\b[a-zA-Z]" where \\b signifies the boundary matchers. See the example − import java.util.regex.Matcher; import java.util.regex.Pattern; public class Tester { public static void main(String[] args) { String input1 = "Hello World"; String input2 = "Welcome to world of Regex"; Pattern p = Pattern.compile("\\b[a-zA-Z]"); Matcher m = p.matcher(input1); System.out.println("Input: " + input1); System.out.print("Output: "); while (m.find()){ System.out.print(m.group() + " "); } System.out.println("\n"); m = p.matcher(input2); System.out.println("Input: " + input2); System.out.print("Output: "); while (m.find()){ System.out.print(m.group() + " "); } System.out.println(); } } Input: Hello World Output: H W Input: Welcome to world of Regex Output: W t w o R
[ { "code": null, "e": 1233, "s": 1062, "text": "A word is contiguous series of alphabetic characters. Using regex, we need to search the boundary character to be between A to Z or a to z. Consider the following cases −" }, { "code": null, "e": 1316, "s": 1233, "text": "Input: Hello World\nOutput: H W\n\nInput: Welcome to world of Regex\nOutput: W t w o R" }, { "code": null, "e": 1414, "s": 1316, "text": "We'll use the regex as \"\\\\b[a-zA-Z]\" where \\\\b signifies the boundary matchers. See the example −" }, { "code": null, "e": 2135, "s": 1414, "text": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class Tester {\n public static void main(String[] args) {\n\n String input1 = \"Hello World\";\n String input2 = \"Welcome to world of Regex\";\n Pattern p = Pattern.compile(\"\\\\b[a-zA-Z]\");\n\n Matcher m = p.matcher(input1);\n System.out.println(\"Input: \" + input1);\n System.out.print(\"Output: \");\n while (m.find()){\n System.out.print(m.group() + \" \");\n }\n System.out.println(\"\\n\");\n\n m = p.matcher(input2);\n System.out.println(\"Input: \" + input2);\n System.out.print(\"Output: \");\n while (m.find()){\n System.out.print(m.group() + \" \");\n }\n System.out.println();\n }\n}" }, { "code": null, "e": 2218, "s": 2135, "text": "Input: Hello World\nOutput: H W\n\nInput: Welcome to world of Regex\nOutput: W t w o R" } ]
Uploading files to Google Drive directly from the Terminal (using Curl) | by Daniel Ellis | Towards Data Science
In many cases, it may be difficult to send data from a new machine to another. Examples of this include HPC facilities which are hidden behind a login portal but do not allow ssh tunnelling or simple headless machines which only have a few core programs installed. In this article, we look at using cURL (a command-line program for transferring data) to push a zipped file (containing log files) onto our google drive account for further analysis. Most machines will come with cURL installed (try typing which curl). If this is not the case we can install it with sudo apt install curl # Linux Debian/Ubuntu or brew install curl # Mac Now we have it installed, we can look at creating the credentials needed to send files. As we are allowing access to our google drive, we want to be able to manage this. This is done by creating a project with user-defined permissions to act as the proxy between our users (in this case us on a different machine) and our account. We start by going to the following page (link below) and creating a new project. console.developers.google.com After this has been done we select the Credentials tab (on the left) and “create credentials” from the top. When asked for the app type, we select TV and other. Finally, this generates a client id and a client seacret . This is your username and password so copy it somewhere secure. To do this we ssh into the machine we wish to upload from and run the following command: curl -d "client_id=<client_id>&scope=https://www.googleapis.com/auth/drive.file" https://oauth2.googleapis.com/device/code Doing so we get a response in the following format {"device_code": "<long string>","user_code": "xxx-xxx-xxx","expires_in": 1800,"interval": 5,"verification_url": "https://www.google.com/device"} Here we need to visit the URL (https://www.google.com/device) and provide the user code to complete our verification. We now continue to select our google account and grant the relevant permissions. When doing this make sure to note down the device code for the next step. When we start uploading, this is the code we shall need to use to identify our account. We get it by using the following: curl -d client_id=<client id> -d client_secret=<client secret> -d device_code=<device code> -d grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code https://accounts.google.com/o/oauth2/token The client id and secret are saved from the first step, and the device code in the previous section. The output should be in the format: {"access_token": ".....","expires_in": 3599,"refresh_token": "....","scope": "https://www.googleapis.com/auth/drive.file","token_type": "Bearer"} Write down the access_token as it will be needed in the upload stage. The command we use to upload files is given below curl -X POST -L \ -H "Authorization: Bearer <enter access token here>" \ -F "metadata={name :'<our.zip>'};type=application/json;charset=UTF-8" \ -F "file=@<our.zip>;type=application/zip" \ "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart" Here you may need to enable the app API before being allowed to upload data. The link to do this is given in the error message if this is the case. Here multipart files are expected to only be a couple of MB in size. However if you are looking at moving larger files resumable may be better suited (see https://developers.google.com/drive/api/v3/manage-uploads ) Now we know our commands work we can create an executable script to do all the work for us. Here we can provide a group of files, it zips them up and then sends them to google drive. We start by creating a new file with nano curlgoogle; and enter the following code — remember to add your own personal auth token! Python 2.7 has been chosen as this is still the default python version on older systems, however the script below should also run for python 3. It should require no new dependencies provided curl already exists on the system. #!/usr/bin/python'''A quick python script to automate curl->googledrive interfacingThis should require nothing more than the system python version and curl. Written for python2.7 (with 3 in mind).Dan Ellis 2020'''import os,sys,jsonif sys.version[0]=='3': raw_input = lambda(x): input(x)###############################Owner information goes here!###############################name = 'curldata'client_id= '<enter your client id>'client_secret='<enter your client secret>'##############################cmd1 = json.loads(os.popen('curl -d "client_id=%s&scope=https://www.googleapis.com/auth/drive.file" https://oauth2.googleapis.com/device/code'%client_id).read())str(raw_input('\n Enter %(user_code)s\n\n at %(verification_url)s \n\n Then hit Enter to continue.'%cmd1))str(raw_input('(twice)'))cmd2 = json.loads(os.popen(('curl -d client_id=%s -d client_secret=%s -d device_code=%s -d grant_type=urn~~3Aietf~~3Aparams~~3Aoauth~~3Agrant-type~~3Adevice_code https://accounts.google.com/o/oauth2/token'%(client_id,client_secret,cmd1['device_code'])).replace('~~','%')).read())print(cmd2)# zip filescmd3 = os.popen('zip -r %s.zip %s'%(name,' '.join(sys.argv[1:]))).readprint(cmd3)cmd4 = os.popen('''curl -X POST -L \ -H "Authorization: Bearer %s" \ -F "metadata={name :\'%s\'};type=application/json;charset=UTF-8" \ -F "file=@%s.zip;type=application/zip" \ "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart" '''%(cmd2["access_token"],name,name)).read()print(cmd4)print('end') We then make it executable chmod a+x curlgoogle allowing us to use it in an executable manner: ./curlgoogle file1 file2.txt file3.jpg etc... And there we have it, an easy way to send multiple log files from a headless machine to a google drive repository, which can be accessed by multiple people for analysis. If you are in need of more information, stack overflow answers by Tanaike and HAKS (amongst others) were particularly helpful in creating this post.
[ { "code": null, "e": 620, "s": 172, "text": "In many cases, it may be difficult to send data from a new machine to another. Examples of this include HPC facilities which are hidden behind a login portal but do not allow ssh tunnelling or simple headless machines which only have a few core programs installed. In this article, we look at using cURL (a command-line program for transferring data) to push a zipped file (containing log files) onto our google drive account for further analysis." }, { "code": null, "e": 736, "s": 620, "text": "Most machines will come with cURL installed (try typing which curl). If this is not the case we can install it with" }, { "code": null, "e": 780, "s": 736, "text": "sudo apt install curl # Linux Debian/Ubuntu" }, { "code": null, "e": 783, "s": 780, "text": "or" }, { "code": null, "e": 811, "s": 783, "text": "brew install curl # Mac" }, { "code": null, "e": 899, "s": 811, "text": "Now we have it installed, we can look at creating the credentials needed to send files." }, { "code": null, "e": 1223, "s": 899, "text": "As we are allowing access to our google drive, we want to be able to manage this. This is done by creating a project with user-defined permissions to act as the proxy between our users (in this case us on a different machine) and our account. We start by going to the following page (link below) and creating a new project." }, { "code": null, "e": 1253, "s": 1223, "text": "console.developers.google.com" }, { "code": null, "e": 1361, "s": 1253, "text": "After this has been done we select the Credentials tab (on the left) and “create credentials” from the top." }, { "code": null, "e": 1414, "s": 1361, "text": "When asked for the app type, we select TV and other." }, { "code": null, "e": 1473, "s": 1414, "text": "Finally, this generates a client id and a client seacret ." }, { "code": null, "e": 1537, "s": 1473, "text": "This is your username and password so copy it somewhere secure." }, { "code": null, "e": 1626, "s": 1537, "text": "To do this we ssh into the machine we wish to upload from and run the following command:" }, { "code": null, "e": 1749, "s": 1626, "text": "curl -d \"client_id=<client_id>&scope=https://www.googleapis.com/auth/drive.file\" https://oauth2.googleapis.com/device/code" }, { "code": null, "e": 1800, "s": 1749, "text": "Doing so we get a response in the following format" }, { "code": null, "e": 1945, "s": 1800, "text": "{\"device_code\": \"<long string>\",\"user_code\": \"xxx-xxx-xxx\",\"expires_in\": 1800,\"interval\": 5,\"verification_url\": \"https://www.google.com/device\"}" }, { "code": null, "e": 2218, "s": 1945, "text": "Here we need to visit the URL (https://www.google.com/device) and provide the user code to complete our verification. We now continue to select our google account and grant the relevant permissions. When doing this make sure to note down the device code for the next step." }, { "code": null, "e": 2340, "s": 2218, "text": "When we start uploading, this is the code we shall need to use to identify our account. We get it by using the following:" }, { "code": null, "e": 2544, "s": 2340, "text": "curl -d client_id=<client id> -d client_secret=<client secret> -d device_code=<device code> -d grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code https://accounts.google.com/o/oauth2/token" }, { "code": null, "e": 2681, "s": 2544, "text": "The client id and secret are saved from the first step, and the device code in the previous section. The output should be in the format:" }, { "code": null, "e": 2827, "s": 2681, "text": "{\"access_token\": \".....\",\"expires_in\": 3599,\"refresh_token\": \"....\",\"scope\": \"https://www.googleapis.com/auth/drive.file\",\"token_type\": \"Bearer\"}" }, { "code": null, "e": 2897, "s": 2827, "text": "Write down the access_token as it will be needed in the upload stage." }, { "code": null, "e": 2947, "s": 2897, "text": "The command we use to upload files is given below" }, { "code": null, "e": 3220, "s": 2947, "text": "curl -X POST -L \\ -H \"Authorization: Bearer <enter access token here>\" \\ -F \"metadata={name :'<our.zip>'};type=application/json;charset=UTF-8\" \\ -F \"file=@<our.zip>;type=application/zip\" \\ \"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart\"" }, { "code": null, "e": 3368, "s": 3220, "text": "Here you may need to enable the app API before being allowed to upload data. The link to do this is given in the error message if this is the case." }, { "code": null, "e": 3583, "s": 3368, "text": "Here multipart files are expected to only be a couple of MB in size. However if you are looking at moving larger files resumable may be better suited (see https://developers.google.com/drive/api/v3/manage-uploads )" }, { "code": null, "e": 3766, "s": 3583, "text": "Now we know our commands work we can create an executable script to do all the work for us. Here we can provide a group of files, it zips them up and then sends them to google drive." }, { "code": null, "e": 4041, "s": 3766, "text": "We start by creating a new file with nano curlgoogle; and enter the following code — remember to add your own personal auth token! Python 2.7 has been chosen as this is still the default python version on older systems, however the script below should also run for python 3." }, { "code": null, "e": 4123, "s": 4041, "text": "It should require no new dependencies provided curl already exists on the system." }, { "code": null, "e": 5630, "s": 4123, "text": "#!/usr/bin/python'''A quick python script to automate curl->googledrive interfacingThis should require nothing more than the system python version and curl. Written for python2.7 (with 3 in mind).Dan Ellis 2020'''import os,sys,jsonif sys.version[0]=='3': raw_input = lambda(x): input(x)###############################Owner information goes here!###############################name = 'curldata'client_id= '<enter your client id>'client_secret='<enter your client secret>'##############################cmd1 = json.loads(os.popen('curl -d \"client_id=%s&scope=https://www.googleapis.com/auth/drive.file\" https://oauth2.googleapis.com/device/code'%client_id).read())str(raw_input('\\n Enter %(user_code)s\\n\\n at %(verification_url)s \\n\\n Then hit Enter to continue.'%cmd1))str(raw_input('(twice)'))cmd2 = json.loads(os.popen(('curl -d client_id=%s -d client_secret=%s -d device_code=%s -d grant_type=urn~~3Aietf~~3Aparams~~3Aoauth~~3Agrant-type~~3Adevice_code https://accounts.google.com/o/oauth2/token'%(client_id,client_secret,cmd1['device_code'])).replace('~~','%')).read())print(cmd2)# zip filescmd3 = os.popen('zip -r %s.zip %s'%(name,' '.join(sys.argv[1:]))).readprint(cmd3)cmd4 = os.popen('''curl -X POST -L \\ -H \"Authorization: Bearer %s\" \\ -F \"metadata={name :\\'%s\\'};type=application/json;charset=UTF-8\" \\ -F \"file=@%s.zip;type=application/zip\" \\ \"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart\" '''%(cmd2[\"access_token\"],name,name)).read()print(cmd4)print('end')" }, { "code": null, "e": 5725, "s": 5630, "text": "We then make it executable chmod a+x curlgoogle allowing us to use it in an executable manner:" }, { "code": null, "e": 5772, "s": 5725, "text": "./curlgoogle file1 file2.txt file3.jpg etc... " }, { "code": null, "e": 5942, "s": 5772, "text": "And there we have it, an easy way to send multiple log files from a headless machine to a google drive repository, which can be accessed by multiple people for analysis." } ]
Java Program to wrap text in a JTextPane and show Scrollbar
Let’s say we have lots of content in our JTextPane component − textPane.setText("This is demo text1. This is demo text2. This is demo text3." + "This is demo text4.This is demo text5. This is demo text6. " + "This is demo text7. This is demo text8. This is demo text9. " + "This is demo text10. This is demo text11. This is demo text12." + "This is demo text13. This is demo text13. This is demo text14." + "This is demo text15. This is demo text13. This is demo text16." + " This is demo text17. This is demo text13. This is demo text18." + " This is demo text19.This is demo text13.This is demo text20."); To wrap it and display the scrollbar, set scrollpane and use the VERTICAL_SCROLLBAR_AS_NEEDED constant − JScrollPane scrollPane = new JScrollPane(textPane); scrollPane.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); package my; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Font; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.text.BadLocationException; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; public class SwingDemo { public static void main(String args[]) throws BadLocationException { JFrame frame = new JFrame("Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container container = frame.getContentPane(); JTextPane textPane = new JTextPane(); textPane.setBackground(Color.BLUE); Font font = new Font("Serif", Font.ITALIC, 22); textPane.setFont(font); SimpleAttributeSet attributeSet = new SimpleAttributeSet(); StyleConstants.setItalic(attributeSet, true); StyleConstants.setForeground(attributeSet, Color.blue); StyleConstants.setBackground(attributeSet, Color.white); textPane.setCharacterAttributes(attributeSet, true); textPane.setText("This is demo text1. This is demo text2. This is demo text3." + "This is demo text4.This is demo text5. This is demo text6. " + "This is demo text7. This is demo text8. This is demo text9. " + "This is demo text10. This is demo text11. This is demo text12." + "This is demo text13. This is demo text13. This is demo text14." + "This is demo text15. This is demo text13. This is demo text16." + " This is demo text17. This is demo text13. This is demo text18." + " This is demo text19.This is demo text13.This is demo text20."); JScrollPane scrollPane = new JScrollPane(textPane); scrollPane.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); container.add(scrollPane, BorderLayout.CENTER); frame.setSize(500, 300); frame.setVisible(true); } }
[ { "code": null, "e": 1125, "s": 1062, "text": "Let’s say we have lots of content in our JTextPane component −" }, { "code": null, "e": 1691, "s": 1125, "text": "textPane.setText(\"This is demo text1. This is demo text2. This is demo text3.\"\n + \"This is demo text4.This is demo text5. This is demo text6. \"\n + \"This is demo text7. This is demo text8. This is demo text9. \"\n + \"This is demo text10. This is demo text11. This is demo text12.\"\n + \"This is demo text13. This is demo text13. This is demo text14.\"\n + \"This is demo text15. This is demo text13. This is demo text16.\"\n + \" This is demo text17. This is demo text13. This is demo text18.\"\n + \" This is demo text19.This is demo text13.This is demo text20.\");" }, { "code": null, "e": 1796, "s": 1691, "text": "To wrap it and display the scrollbar, set scrollpane and use the VERTICAL_SCROLLBAR_AS_NEEDED constant −" }, { "code": null, "e": 1949, "s": 1796, "text": "JScrollPane scrollPane = new JScrollPane(textPane);\nscrollPane.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);" }, { "code": null, "e": 3905, "s": 1949, "text": "package my;\nimport java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.Container;\nimport java.awt.Font;\nimport javax.swing.JFrame;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTextPane;\nimport javax.swing.text.BadLocationException;\nimport javax.swing.text.SimpleAttributeSet;\nimport javax.swing.text.StyleConstants;\npublic class SwingDemo {\n public static void main(String args[]) throws BadLocationException {\n JFrame frame = new JFrame(\"Demo\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n Container container = frame.getContentPane();\n JTextPane textPane = new JTextPane();\n textPane.setBackground(Color.BLUE);\n Font font = new Font(\"Serif\", Font.ITALIC, 22);\n textPane.setFont(font);\n SimpleAttributeSet attributeSet = new SimpleAttributeSet();\n StyleConstants.setItalic(attributeSet, true);\n StyleConstants.setForeground(attributeSet, Color.blue);\n StyleConstants.setBackground(attributeSet, Color.white);\n textPane.setCharacterAttributes(attributeSet, true);\n textPane.setText(\"This is demo text1. This is demo text2. This is demo text3.\"\n + \"This is demo text4.This is demo text5. This is demo text6. \"\n + \"This is demo text7. This is demo text8. This is demo text9. \"\n + \"This is demo text10. This is demo text11. This is demo text12.\"\n + \"This is demo text13. This is demo text13. This is demo text14.\"\n + \"This is demo text15. This is demo text13. This is demo text16.\"\n + \" This is demo text17. This is demo text13. This is demo text18.\"\n + \" This is demo text19.This is demo text13.This is demo text20.\");\n JScrollPane scrollPane = new JScrollPane(textPane);\n scrollPane.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);\n container.add(scrollPane, BorderLayout.CENTER);\n frame.setSize(500, 300);\n frame.setVisible(true);\n }\n}" } ]
String compareTo(String anotherString)
This method compares two strings lexicographically. Here is the syntax of this method − int compareTo(String anotherString) Here is the detail of parameters − anotherString − the String to be compared. anotherString − the String to be compared. The value 0 if the argument is a string lexicographically equal to this string; a value less than 0 if the argument is a string lexicographically greater than this string; and a value greater than 0 if the argument is a string lexicographically less than this string. The value 0 if the argument is a string lexicographically equal to this string; a value less than 0 if the argument is a string lexicographically greater than this string; and a value greater than 0 if the argument is a string lexicographically less than this string. public class Test { public static void main(String args[]) { String str1 = "Strings are immutable"; String str2 = "Strings are immutable"; String str3 = "Integers are not immutable"; int result = str1.compareTo( str2 ); System.out.println(result); result = str2.compareTo( str3 ); System.out.println(result); result = str3.compareTo( str1 ); System.out.println(result); } } This will produce the following result − 0 10 -10 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": 2429, "s": 2377, "text": "This method compares two strings lexicographically." }, { "code": null, "e": 2465, "s": 2429, "text": "Here is the syntax of this method −" }, { "code": null, "e": 2502, "s": 2465, "text": "int compareTo(String anotherString)\n" }, { "code": null, "e": 2537, "s": 2502, "text": "Here is the detail of parameters −" }, { "code": null, "e": 2580, "s": 2537, "text": "anotherString − the String to be compared." }, { "code": null, "e": 2623, "s": 2580, "text": "anotherString − the String to be compared." }, { "code": null, "e": 2891, "s": 2623, "text": "The value 0 if the argument is a string lexicographically equal to this string; a value less than 0 if the argument is a string lexicographically greater than this string; and a value greater than 0 if the argument is a string lexicographically less than this string." }, { "code": null, "e": 3159, "s": 2891, "text": "The value 0 if the argument is a string lexicographically equal to this string; a value less than 0 if the argument is a string lexicographically greater than this string; and a value greater than 0 if the argument is a string lexicographically less than this string." }, { "code": null, "e": 3615, "s": 3159, "text": "public class Test {\n\n public static void main(String args[]) {\n String str1 = \"Strings are immutable\";\n String str2 = \"Strings are immutable\";\n String str3 = \"Integers are not immutable\";\n \n int result = str1.compareTo( str2 );\n System.out.println(result);\n \n result = str2.compareTo( str3 );\n System.out.println(result);\n \n result = str3.compareTo( str1 );\n System.out.println(result);\n }\n}" }, { "code": null, "e": 3656, "s": 3615, "text": "This will produce the following result −" }, { "code": null, "e": 3666, "s": 3656, "text": "0\n10\n-10\n" }, { "code": null, "e": 3699, "s": 3666, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 3715, "s": 3699, "text": " Malhar Lathkar" }, { "code": null, "e": 3748, "s": 3715, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 3764, "s": 3748, "text": " Malhar Lathkar" }, { "code": null, "e": 3799, "s": 3764, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3813, "s": 3799, "text": " Anadi Sharma" }, { "code": null, "e": 3847, "s": 3813, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 3861, "s": 3847, "text": " Tushar Kale" }, { "code": null, "e": 3898, "s": 3861, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3913, "s": 3898, "text": " Monica Mittal" }, { "code": null, "e": 3946, "s": 3913, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 3965, "s": 3946, "text": " Arnab Chakraborty" }, { "code": null, "e": 3972, "s": 3965, "text": " Print" }, { "code": null, "e": 3983, "s": 3972, "text": " Add Notes" } ]
Early binding and Late binding in C++ - GeeksforGeeks
05 Feb, 2018 Binding refers to the process of converting identifiers (such as variable and performance names) into addresses. Binding is done for each variable and functions. For functions, it means that matching the call with the right function definition by the compiler. It takes place either at compile time or at runtime. Early Binding (compile-time time polymorphism) As the name indicates, compiler (or linker) directly associate an address to the function call. It replaces the call with a machine language instruction that tells the mainframe to leap to the address of the function. By default early binding happens in C++. Late binding (discussed below) is achieved with the help of virtual keyword) // CPP Program to illustrate early binding.// Any normal function call (without virtual)// is binded early. Here we have taken base// and derived class example so that readers// can easily compare and see difference in// outputs.#include<iostream>using namespace std; class Base{public: void show() { cout<<" In Base \n"; }}; class Derived: public Base{public: void show() { cout<<"In Derived \n"; }}; int main(void){ Base *bp = new Derived; // The function call decided at // compile time (compiler sees type // of pointer and calls base class // function. bp->show(); return 0;} Output: In Base Late Binding : (Run time polymorphism) In this, the compiler adds code that identifies the kind of object at runtime then matches the call with the right function definition (Refer this for details). This can be achieved by declaring a virtual function. // CPP Program to illustrate late binding#include<iostream>using namespace std; class Base{public: virtual void show() { cout<<" In Base \n"; }}; class Derived: public Base{public: void show() { cout<<"In Derived \n"; }}; int main(void){ Base *bp = new Derived; bp->show(); // RUN-TIME POLYMORPHISM return 0;} Output: In Derived cpp-inheritance cpp-virtual C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Operator Overloading in C++ Sorting a vector in C++ Polymorphism in C++ Friend class and function in C++ List in C++ Standard Template Library (STL) Pair in C++ Standard Template Library (STL) Convert string to char array in C++ new and delete operators in C++ for dynamic memory Destructors in C++ Queue in C++ Standard Template Library (STL)
[ { "code": null, "e": 23733, "s": 23705, "text": "\n05 Feb, 2018" }, { "code": null, "e": 24047, "s": 23733, "text": "Binding refers to the process of converting identifiers (such as variable and performance names) into addresses. Binding is done for each variable and functions. For functions, it means that matching the call with the right function definition by the compiler. It takes place either at compile time or at runtime." }, { "code": null, "e": 24312, "s": 24047, "text": "Early Binding (compile-time time polymorphism) As the name indicates, compiler (or linker) directly associate an address to the function call. It replaces the call with a machine language instruction that tells the mainframe to leap to the address of the function." }, { "code": null, "e": 24430, "s": 24312, "text": "By default early binding happens in C++. Late binding (discussed below) is achieved with the help of virtual keyword)" }, { "code": "// CPP Program to illustrate early binding.// Any normal function call (without virtual)// is binded early. Here we have taken base// and derived class example so that readers// can easily compare and see difference in// outputs.#include<iostream>using namespace std; class Base{public: void show() { cout<<\" In Base \\n\"; }}; class Derived: public Base{public: void show() { cout<<\"In Derived \\n\"; }}; int main(void){ Base *bp = new Derived; // The function call decided at // compile time (compiler sees type // of pointer and calls base class // function. bp->show(); return 0;}", "e": 25054, "s": 24430, "text": null }, { "code": null, "e": 25062, "s": 25054, "text": "Output:" }, { "code": null, "e": 25070, "s": 25062, "text": "In Base" }, { "code": null, "e": 25324, "s": 25070, "text": "Late Binding : (Run time polymorphism) In this, the compiler adds code that identifies the kind of object at runtime then matches the call with the right function definition (Refer this for details). This can be achieved by declaring a virtual function." }, { "code": "// CPP Program to illustrate late binding#include<iostream>using namespace std; class Base{public: virtual void show() { cout<<\" In Base \\n\"; }}; class Derived: public Base{public: void show() { cout<<\"In Derived \\n\"; }}; int main(void){ Base *bp = new Derived; bp->show(); // RUN-TIME POLYMORPHISM return 0;}", "e": 25659, "s": 25324, "text": null }, { "code": null, "e": 25667, "s": 25659, "text": "Output:" }, { "code": null, "e": 25678, "s": 25667, "text": "In Derived" }, { "code": null, "e": 25694, "s": 25678, "text": "cpp-inheritance" }, { "code": null, "e": 25706, "s": 25694, "text": "cpp-virtual" }, { "code": null, "e": 25710, "s": 25706, "text": "C++" }, { "code": null, "e": 25714, "s": 25710, "text": "CPP" }, { "code": null, "e": 25812, "s": 25714, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25821, "s": 25812, "text": "Comments" }, { "code": null, "e": 25834, "s": 25821, "text": "Old Comments" }, { "code": null, "e": 25862, "s": 25834, "text": "Operator Overloading in C++" }, { "code": null, "e": 25886, "s": 25862, "text": "Sorting a vector in C++" }, { "code": null, "e": 25906, "s": 25886, "text": "Polymorphism in C++" }, { "code": null, "e": 25939, "s": 25906, "text": "Friend class and function in C++" }, { "code": null, "e": 25983, "s": 25939, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 26027, "s": 25983, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 26063, "s": 26027, "text": "Convert string to char array in C++" }, { "code": null, "e": 26114, "s": 26063, "text": "new and delete operators in C++ for dynamic memory" }, { "code": null, "e": 26133, "s": 26114, "text": "Destructors in C++" } ]
Python dictionary str() Method
Python dictionary method str() produces a printable string representation of a dictionary. Following is the syntax for str() method − str(dict) dict − This is the dictionary. dict − This is the dictionary. This method returns string representation. The following example shows the usage of str() method. #!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7}; print "Equivalent String : %s" % str (dict) When we run above program, it produces following result − Equivalent String : {'Age': 7, 'Name': 'Zara'} 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2336, "s": 2244, "text": "Python dictionary method str() produces a printable string representation of a dictionary." }, { "code": null, "e": 2379, "s": 2336, "text": "Following is the syntax for str() method −" }, { "code": null, "e": 2390, "s": 2379, "text": "str(dict)\n" }, { "code": null, "e": 2421, "s": 2390, "text": "dict − This is the dictionary." }, { "code": null, "e": 2452, "s": 2421, "text": "dict − This is the dictionary." }, { "code": null, "e": 2495, "s": 2452, "text": "This method returns string representation." }, { "code": null, "e": 2550, "s": 2495, "text": "The following example shows the usage of str() method." }, { "code": null, "e": 2648, "s": 2550, "text": "#!/usr/bin/python\n\ndict = {'Name': 'Zara', 'Age': 7};\nprint \"Equivalent String : %s\" % str (dict)" }, { "code": null, "e": 2706, "s": 2648, "text": "When we run above program, it produces following result −" }, { "code": null, "e": 2754, "s": 2706, "text": "Equivalent String : {'Age': 7, 'Name': 'Zara'}\n" }, { "code": null, "e": 2791, "s": 2754, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 2807, "s": 2791, "text": " Malhar Lathkar" }, { "code": null, "e": 2840, "s": 2807, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 2859, "s": 2840, "text": " Arnab Chakraborty" }, { "code": null, "e": 2894, "s": 2859, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 2916, "s": 2894, "text": " In28Minutes Official" }, { "code": null, "e": 2950, "s": 2916, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 2978, "s": 2950, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3013, "s": 2978, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3027, "s": 3013, "text": " Lets Kode It" }, { "code": null, "e": 3060, "s": 3027, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3077, "s": 3060, "text": " Abhilash Nelson" }, { "code": null, "e": 3084, "s": 3077, "text": " Print" }, { "code": null, "e": 3095, "s": 3084, "text": " Add Notes" } ]
17 Terminal Commands Every Programmer Should Know | by Mahbub Zaman | Towards Data Science
Most computer users interact via a graphical user interface because it’s an easy way to manipulate a machine. Even though GUI applications remain popular among vast users, a command-line interface gives users more control over their computer by running text commands. It’s a powerful way to interact with a computer. For example, you can run text commands to create 100 folders, but it will take more time and effort to achieve the same result via a GUI application. mkdir testcd testfor i in {1..100}do mkdir "$i"done To be able to run these commands, we need to use the Terminal application. This Terminal provides you with the shell. Shell is an environment where we can run our shell commands and shell scripts. It allows us to control command-line tools. The macOS X comes with the bash shell (Bourne Again shell), but you can change your shell to csh (C shell), zsh (Z shell), ksh (Korn Shell), tcsh (TENEX C Shell), etc. Now let’s go through some basic shell commands to see what is happening. List all available shells in macOS X. cat /etc/shells To see which shell you’re running. echo $0 To change to bash shell. chsh -s /bin/bash To change to zsh shell. chsh -s /bin/zsh Depending on which shell you’re using, you’ll get different features. My choice of the shell is zsh. You’ll learn some basic shell commands from this post to improve daily workflow by saving time and effort. The pwd command stands for Print Working Directory. It will print the full path to the current working directory. pwd# /Users/universe/Desktop The shell ignores a word if it starts with # (hash) and any remaining characters on that line. # /Users/universe/Desktop The mkdir command stands for Make Directory. Here we are creating a directory on my Desktop called neptune. mkdir neptune We can create multiple directories using the -p option. mkdir -p space/neptune The above command will create a folder called space and a nested folder or subfolder neptune. If we want to create our third folder naiad under neptune, we can use the following command. We don’t have to provide the -p option for this command because the path space/neptune exists already. mkdir space/neptune/naiad The cd command stands for Change Directory. Let’s use this command to access the space directory we have created previously. cd spacecd neptunecd naiad Or you can use the following command to access the naiad directory. cd space/neptune/naiad Both commands will produce the same result. Now we should be inside the naiad directory. The .. (two periods) represents or points to the directory that contains the current directory, also known as the parent directory. Here the parent directory of naiad is neptune. Let’s use the following command to move one level up in the directory hierarchy. pwd# /Users/universe/Desktop/space/neptune/naiadcd ..pwd# /Users/universe/Desktop/space/neptune Moreover, we can move to multiple levels. In this case, let’s move 2 levels up. cd ../..pwd# /Users/universe/Desktop Now, we are back to the Desktop directory. The . (single periods) represents or points to the current working directory. It’s helpful when we don’t want to write the full path when running a command. For example, if our command-line tool is in the current directory, we can use the following command. ./space-robot The ~ (tilda) or $HOME represents or points to the home directory. For macOS X, the user’s home directory is under the /Users directory. cd ~pwd# /Users/universecd $HOMEpwd# /Users/universe By using this shorthand, you don’t have to type the full path to the home directory. Also, we can see a / (forward-slash) is used to separate the directories in a pathname. By using the following command, we can move to the root directory. cd / Using the touch command, we can create a file. cd ~/Desktop/neptune touch todo.txt The ls command stands for List. We can use it to list all the contents of the specified directory, if no path is specified it will list everything in the current directory. cd ~/Desktop/neptunemkdir todols# todo todo.txt Use -a flag to list hidden files and directories. ls -a Use -l flag to list with detailed information. ls -l Or use it together. ls -al We have been writing commands for a while, so let’s clear the Terminal screen. clear The mv command stands for Move. We can use this command to move files and directories from one place to another. Also, we can use it to rename files and directories. The following command will move the todo.txt file from its current directory to its child directory todo. cd ~/Desktop/neptunemv todo.txt todo/todo.txt Now let’s rename the file. Here we are renaming the todo.txt file to my-todo.txt. cd todomv todo.txt my-todo.txt The cp command stands for Copy. Now, let’s copy our my-todo.txt file to the parent directory. cd ~/Desktop/neptunecp todo/my-todo.txt my-todo-bu.txt We can use the -r flag to copy a directory. The following command will copy everything that is inside the todo folder to a folder called bu. cp -r todo bu The rm command stands for Remove, and rmdir command stands for Remove Directory. The rmdir command can only delete a directory if it is empty. Now let’s remove a file and directory. cd ~/Desktop/neptunerm my-todo-bu.txtmkdir emptyrmdir empty We can use the -r flag to delete a non-empty folder. rm -r burm -r todo The > can be used to redirect stdout (Standard output). Here, we are adding a task to our todo.txt file. The echo command writes its arguments to stdout. This > command will overwrite the todo.txt if exists already. cd ~/Desktop/neptuneecho 1. Make space robot > todo_today.txt If we want to append data we need to use the >> command. echo 2. Make space robot v2 >> todo_today.txt The < can be used to redirect stdin (Standard input). Here, we are redirecting the contents of our todo.txt file to the wc command to print the number of lines, word count, and character count. wc < todo_today.txt# 2 9 43 The * (asterisk) can be used as a wildcard to match zero or more characters. ls *.txt# todo_today.txt The ? (question mark) can be used to match a single character. ls ????_?????.txt# todo_today.txt The [] (square brackets) can be used to match any number of characters inside them. ls t[o]do_*.???# todo_today.txt The ; (semicolon) can be used to write multiple commands on a single line, all we have to do is separate each command with a semicolon. cd ~/Desktop/neptune ; wc < todo.txt# 2 9 43 The $ (dollar) can be used to create and store values. echo $HOME# /Users/universeMyValue=99echo $MyValue# 99 The \ (backslash) can be used to escape a special character. echo \$MyValue# $MyValueecho \$$MyValue# $99 The cat command stands for Concatenate. It prints the contents of a file or files to stdout. Print content of a single file. cd ~/Desktop/neptunecat todo.txt# 1. Make space robot# 2. Make space robot v2 Print content of multiple files. cd ~/Desktop/neptuneecho FILE 1 > file_1.txtecho FILE 2 > file_2.txtecho FILE 3 > file_3.txtcat file_1.txt file_2.txt file_3.txt# FILE 1# FILE 2# FILE 3 The grep command stands for Global Regular Expression Print. It searches text inside the file specified with the given search pattern. By default, grep is case-sensitive. For case-incentive search, we can use the -i flag. cd ~/Desktop/neptunegrep "FILE" file_1.txt# FILE 1grep -i "file" file_1.txtFILE 1 The -r flag is used to search inside a directory recursively. Here it will search everything inside the current directory and its child directories. grep -r "FILE" .# ./file_1.txt:FILE 1# ./file_2.txt:FILE 2# ./file_3.txt:FILE 3 There are other flags that can be useful, like the -n flag will print matching lines with the line number, the -c flag will print the count of the matching lines. The | command or the pipe command is used to add two or more commands, where the output of the previous command is used as the input for the next command. command_1 | command_2 | .................. | command_N Here we are sorting the todo.txt file in reverse order by combining the cat and sort command. cat todo.txt | sort -r# 2. Make space robot v2# 1. Make space robot The commands head and tail can be used to print the content of a file to standard output. The flag -n is used to define how many lines we want to output. Now let’s print the first 1 line of a file. cd ~/Desktop/neptunehead -n 1 todo.txt# 1. Make space robot Print the last 1 line of a file. tail -n 1 todo.txt# 2. Make space robot v2 These commands can be useful when working with large files. The find command is used to search files. find dir -name search_pattern Let’s find all the text files in the current directory. cd ~/Desktop/neptunefind . -name "*.txt"# ./file_1.txt# ./todo.txt# ./file_2.txt# ./file_3.txt The open command can be used to open a file and open the directory using the Finder application. cd ~/Desktop/neptuneopen .open todo.txt Finally, we have the man command, which stands for Manual. It prints the user manual for a command. man cd Use up and down arrow keys to navigate through the documentation. Use the f key to move forward one page and the b key to go back one page — press q to quit. Congratulations! Now you know all these cool shell commands, which will help you to save time and effort. You can find all the shell commands I've discussed on my GitHub. Happy coding!
[ { "code": null, "e": 638, "s": 171, "text": "Most computer users interact via a graphical user interface because it’s an easy way to manipulate a machine. Even though GUI applications remain popular among vast users, a command-line interface gives users more control over their computer by running text commands. It’s a powerful way to interact with a computer. For example, you can run text commands to create 100 folders, but it will take more time and effort to achieve the same result via a GUI application." }, { "code": null, "e": 692, "s": 638, "text": "mkdir testcd testfor i in {1..100}do mkdir \"$i\"done" }, { "code": null, "e": 1212, "s": 692, "text": "To be able to run these commands, we need to use the Terminal application. This Terminal provides you with the shell. Shell is an environment where we can run our shell commands and shell scripts. It allows us to control command-line tools. The macOS X comes with the bash shell (Bourne Again shell), but you can change your shell to csh (C shell), zsh (Z shell), ksh (Korn Shell), tcsh (TENEX C Shell), etc. Now let’s go through some basic shell commands to see what is happening. List all available shells in macOS X." }, { "code": null, "e": 1228, "s": 1212, "text": "cat /etc/shells" }, { "code": null, "e": 1263, "s": 1228, "text": "To see which shell you’re running." }, { "code": null, "e": 1271, "s": 1263, "text": "echo $0" }, { "code": null, "e": 1296, "s": 1271, "text": "To change to bash shell." }, { "code": null, "e": 1314, "s": 1296, "text": "chsh -s /bin/bash" }, { "code": null, "e": 1338, "s": 1314, "text": "To change to zsh shell." }, { "code": null, "e": 1355, "s": 1338, "text": "chsh -s /bin/zsh" }, { "code": null, "e": 1563, "s": 1355, "text": "Depending on which shell you’re using, you’ll get different features. My choice of the shell is zsh. You’ll learn some basic shell commands from this post to improve daily workflow by saving time and effort." }, { "code": null, "e": 1677, "s": 1563, "text": "The pwd command stands for Print Working Directory. It will print the full path to the current working directory." }, { "code": null, "e": 1706, "s": 1677, "text": "pwd# /Users/universe/Desktop" }, { "code": null, "e": 1801, "s": 1706, "text": "The shell ignores a word if it starts with # (hash) and any remaining characters on that line." }, { "code": null, "e": 1827, "s": 1801, "text": "# /Users/universe/Desktop" }, { "code": null, "e": 1935, "s": 1827, "text": "The mkdir command stands for Make Directory. Here we are creating a directory on my Desktop called neptune." }, { "code": null, "e": 1949, "s": 1935, "text": "mkdir neptune" }, { "code": null, "e": 2005, "s": 1949, "text": "We can create multiple directories using the -p option." }, { "code": null, "e": 2028, "s": 2005, "text": "mkdir -p space/neptune" }, { "code": null, "e": 2318, "s": 2028, "text": "The above command will create a folder called space and a nested folder or subfolder neptune. If we want to create our third folder naiad under neptune, we can use the following command. We don’t have to provide the -p option for this command because the path space/neptune exists already." }, { "code": null, "e": 2344, "s": 2318, "text": "mkdir space/neptune/naiad" }, { "code": null, "e": 2469, "s": 2344, "text": "The cd command stands for Change Directory. Let’s use this command to access the space directory we have created previously." }, { "code": null, "e": 2496, "s": 2469, "text": "cd spacecd neptunecd naiad" }, { "code": null, "e": 2564, "s": 2496, "text": "Or you can use the following command to access the naiad directory." }, { "code": null, "e": 2587, "s": 2564, "text": "cd space/neptune/naiad" }, { "code": null, "e": 2676, "s": 2587, "text": "Both commands will produce the same result. Now we should be inside the naiad directory." }, { "code": null, "e": 2936, "s": 2676, "text": "The .. (two periods) represents or points to the directory that contains the current directory, also known as the parent directory. Here the parent directory of naiad is neptune. Let’s use the following command to move one level up in the directory hierarchy." }, { "code": null, "e": 3032, "s": 2936, "text": "pwd# /Users/universe/Desktop/space/neptune/naiadcd ..pwd# /Users/universe/Desktop/space/neptune" }, { "code": null, "e": 3112, "s": 3032, "text": "Moreover, we can move to multiple levels. In this case, let’s move 2 levels up." }, { "code": null, "e": 3149, "s": 3112, "text": "cd ../..pwd# /Users/universe/Desktop" }, { "code": null, "e": 3192, "s": 3149, "text": "Now, we are back to the Desktop directory." }, { "code": null, "e": 3450, "s": 3192, "text": "The . (single periods) represents or points to the current working directory. It’s helpful when we don’t want to write the full path when running a command. For example, if our command-line tool is in the current directory, we can use the following command." }, { "code": null, "e": 3464, "s": 3450, "text": "./space-robot" }, { "code": null, "e": 3601, "s": 3464, "text": "The ~ (tilda) or $HOME represents or points to the home directory. For macOS X, the user’s home directory is under the /Users directory." }, { "code": null, "e": 3654, "s": 3601, "text": "cd ~pwd# /Users/universecd $HOMEpwd# /Users/universe" }, { "code": null, "e": 3739, "s": 3654, "text": "By using this shorthand, you don’t have to type the full path to the home directory." }, { "code": null, "e": 3894, "s": 3739, "text": "Also, we can see a / (forward-slash) is used to separate the directories in a pathname. By using the following command, we can move to the root directory." }, { "code": null, "e": 3899, "s": 3894, "text": "cd /" }, { "code": null, "e": 3946, "s": 3899, "text": "Using the touch command, we can create a file." }, { "code": null, "e": 3982, "s": 3946, "text": "cd ~/Desktop/neptune touch todo.txt" }, { "code": null, "e": 4155, "s": 3982, "text": "The ls command stands for List. We can use it to list all the contents of the specified directory, if no path is specified it will list everything in the current directory." }, { "code": null, "e": 4207, "s": 4155, "text": "cd ~/Desktop/neptunemkdir todols# todo todo.txt" }, { "code": null, "e": 4257, "s": 4207, "text": "Use -a flag to list hidden files and directories." }, { "code": null, "e": 4263, "s": 4257, "text": "ls -a" }, { "code": null, "e": 4310, "s": 4263, "text": "Use -l flag to list with detailed information." }, { "code": null, "e": 4316, "s": 4310, "text": "ls -l" }, { "code": null, "e": 4336, "s": 4316, "text": "Or use it together." }, { "code": null, "e": 4343, "s": 4336, "text": "ls -al" }, { "code": null, "e": 4422, "s": 4343, "text": "We have been writing commands for a while, so let’s clear the Terminal screen." }, { "code": null, "e": 4428, "s": 4422, "text": "clear" }, { "code": null, "e": 4700, "s": 4428, "text": "The mv command stands for Move. We can use this command to move files and directories from one place to another. Also, we can use it to rename files and directories. The following command will move the todo.txt file from its current directory to its child directory todo." }, { "code": null, "e": 4746, "s": 4700, "text": "cd ~/Desktop/neptunemv todo.txt todo/todo.txt" }, { "code": null, "e": 4828, "s": 4746, "text": "Now let’s rename the file. Here we are renaming the todo.txt file to my-todo.txt." }, { "code": null, "e": 4859, "s": 4828, "text": "cd todomv todo.txt my-todo.txt" }, { "code": null, "e": 4953, "s": 4859, "text": "The cp command stands for Copy. Now, let’s copy our my-todo.txt file to the parent directory." }, { "code": null, "e": 5008, "s": 4953, "text": "cd ~/Desktop/neptunecp todo/my-todo.txt my-todo-bu.txt" }, { "code": null, "e": 5149, "s": 5008, "text": "We can use the -r flag to copy a directory. The following command will copy everything that is inside the todo folder to a folder called bu." }, { "code": null, "e": 5163, "s": 5149, "text": "cp -r todo bu" }, { "code": null, "e": 5345, "s": 5163, "text": "The rm command stands for Remove, and rmdir command stands for Remove Directory. The rmdir command can only delete a directory if it is empty. Now let’s remove a file and directory." }, { "code": null, "e": 5405, "s": 5345, "text": "cd ~/Desktop/neptunerm my-todo-bu.txtmkdir emptyrmdir empty" }, { "code": null, "e": 5458, "s": 5405, "text": "We can use the -r flag to delete a non-empty folder." }, { "code": null, "e": 5477, "s": 5458, "text": "rm -r burm -r todo" }, { "code": null, "e": 5693, "s": 5477, "text": "The > can be used to redirect stdout (Standard output). Here, we are adding a task to our todo.txt file. The echo command writes its arguments to stdout. This > command will overwrite the todo.txt if exists already." }, { "code": null, "e": 5755, "s": 5693, "text": "cd ~/Desktop/neptuneecho 1. Make space robot > todo_today.txt" }, { "code": null, "e": 5812, "s": 5755, "text": "If we want to append data we need to use the >> command." }, { "code": null, "e": 5858, "s": 5812, "text": "echo 2. Make space robot v2 >> todo_today.txt" }, { "code": null, "e": 6052, "s": 5858, "text": "The < can be used to redirect stdin (Standard input). Here, we are redirecting the contents of our todo.txt file to the wc command to print the number of lines, word count, and character count." }, { "code": null, "e": 6098, "s": 6052, "text": "wc < todo_today.txt# 2 9 43" }, { "code": null, "e": 6175, "s": 6098, "text": "The * (asterisk) can be used as a wildcard to match zero or more characters." }, { "code": null, "e": 6200, "s": 6175, "text": "ls *.txt# todo_today.txt" }, { "code": null, "e": 6263, "s": 6200, "text": "The ? (question mark) can be used to match a single character." }, { "code": null, "e": 6297, "s": 6263, "text": "ls ????_?????.txt# todo_today.txt" }, { "code": null, "e": 6381, "s": 6297, "text": "The [] (square brackets) can be used to match any number of characters inside them." }, { "code": null, "e": 6413, "s": 6381, "text": "ls t[o]do_*.???# todo_today.txt" }, { "code": null, "e": 6549, "s": 6413, "text": "The ; (semicolon) can be used to write multiple commands on a single line, all we have to do is separate each command with a semicolon." }, { "code": null, "e": 6612, "s": 6549, "text": "cd ~/Desktop/neptune ; wc < todo.txt# 2 9 43" }, { "code": null, "e": 6667, "s": 6612, "text": "The $ (dollar) can be used to create and store values." }, { "code": null, "e": 6722, "s": 6667, "text": "echo $HOME# /Users/universeMyValue=99echo $MyValue# 99" }, { "code": null, "e": 6783, "s": 6722, "text": "The \\ (backslash) can be used to escape a special character." }, { "code": null, "e": 6828, "s": 6783, "text": "echo \\$MyValue# $MyValueecho \\$$MyValue# $99" }, { "code": null, "e": 6953, "s": 6828, "text": "The cat command stands for Concatenate. It prints the contents of a file or files to stdout. Print content of a single file." }, { "code": null, "e": 7031, "s": 6953, "text": "cd ~/Desktop/neptunecat todo.txt# 1. Make space robot# 2. Make space robot v2" }, { "code": null, "e": 7064, "s": 7031, "text": "Print content of multiple files." }, { "code": null, "e": 7217, "s": 7064, "text": "cd ~/Desktop/neptuneecho FILE 1 > file_1.txtecho FILE 2 > file_2.txtecho FILE 3 > file_3.txtcat file_1.txt file_2.txt file_3.txt# FILE 1# FILE 2# FILE 3" }, { "code": null, "e": 7439, "s": 7217, "text": "The grep command stands for Global Regular Expression Print. It searches text inside the file specified with the given search pattern. By default, grep is case-sensitive. For case-incentive search, we can use the -i flag." }, { "code": null, "e": 7521, "s": 7439, "text": "cd ~/Desktop/neptunegrep \"FILE\" file_1.txt# FILE 1grep -i \"file\" file_1.txtFILE 1" }, { "code": null, "e": 7670, "s": 7521, "text": "The -r flag is used to search inside a directory recursively. Here it will search everything inside the current directory and its child directories." }, { "code": null, "e": 7750, "s": 7670, "text": "grep -r \"FILE\" .# ./file_1.txt:FILE 1# ./file_2.txt:FILE 2# ./file_3.txt:FILE 3" }, { "code": null, "e": 7913, "s": 7750, "text": "There are other flags that can be useful, like the -n flag will print matching lines with the line number, the -c flag will print the count of the matching lines." }, { "code": null, "e": 8068, "s": 7913, "text": "The | command or the pipe command is used to add two or more commands, where the output of the previous command is used as the input for the next command." }, { "code": null, "e": 8123, "s": 8068, "text": "command_1 | command_2 | .................. | command_N" }, { "code": null, "e": 8217, "s": 8123, "text": "Here we are sorting the todo.txt file in reverse order by combining the cat and sort command." }, { "code": null, "e": 8285, "s": 8217, "text": "cat todo.txt | sort -r# 2. Make space robot v2# 1. Make space robot" }, { "code": null, "e": 8483, "s": 8285, "text": "The commands head and tail can be used to print the content of a file to standard output. The flag -n is used to define how many lines we want to output. Now let’s print the first 1 line of a file." }, { "code": null, "e": 8543, "s": 8483, "text": "cd ~/Desktop/neptunehead -n 1 todo.txt# 1. Make space robot" }, { "code": null, "e": 8576, "s": 8543, "text": "Print the last 1 line of a file." }, { "code": null, "e": 8619, "s": 8576, "text": "tail -n 1 todo.txt# 2. Make space robot v2" }, { "code": null, "e": 8679, "s": 8619, "text": "These commands can be useful when working with large files." }, { "code": null, "e": 8721, "s": 8679, "text": "The find command is used to search files." }, { "code": null, "e": 8751, "s": 8721, "text": "find dir -name search_pattern" }, { "code": null, "e": 8807, "s": 8751, "text": "Let’s find all the text files in the current directory." }, { "code": null, "e": 8902, "s": 8807, "text": "cd ~/Desktop/neptunefind . -name \"*.txt\"# ./file_1.txt# ./todo.txt# ./file_2.txt# ./file_3.txt" }, { "code": null, "e": 8999, "s": 8902, "text": "The open command can be used to open a file and open the directory using the Finder application." }, { "code": null, "e": 9039, "s": 8999, "text": "cd ~/Desktop/neptuneopen .open todo.txt" }, { "code": null, "e": 9139, "s": 9039, "text": "Finally, we have the man command, which stands for Manual. It prints the user manual for a command." }, { "code": null, "e": 9146, "s": 9139, "text": "man cd" }, { "code": null, "e": 9304, "s": 9146, "text": "Use up and down arrow keys to navigate through the documentation. Use the f key to move forward one page and the b key to go back one page — press q to quit." } ]
Explain the pointers to unions in C language
A union is a memory location that is shared by several variables of different data types. The syntax for the pointers to unions in C programming is as follows − union uniontag{ datatype member 1; datatype member 2; ---- ---- datatype member n; }; The following example shows the usage of union of structure. union sample{ int a; float b; char c; }; Following is the declaration for union variable. It is of three types as follows − union sample{ int a; float b; char c; }s; union{ int a; float b; char c; }s; union sample{ int a; float b; char c; }; union sample s; When union is declared, the compiler automatically creates largest size variable type to hold variables in the union. When union is declared, the compiler automatically creates largest size variable type to hold variables in the union. At any time only one variable can be referred. At any time only one variable can be referred. Same syntax of structure is used to access a union member. Same syntax of structure is used to access a union member. The dot operator is for accessing members. The dot operator is for accessing members. The arrow operator ( ->) is used for accessing the members using pointer. The arrow operator ( ->) is used for accessing the members using pointer. We have pointers to unions and can access members using the arrow operator (->) just like structures. The following program shows the usage of pointers to union in C programming − Live Demo #include <stdio.h> union pointer { int num; char a; }; int main(){ union pointer p1; p1.num = 75; // p2 is a pointer to union p1 union pointer* p2 = &p1; // Accessing union members using pointer printf("%d %c", p2->num, p2->a); return 0; } When the above program is executed, it produces the following result − 75 K Consider the same example with different input. Live Demo #include <stdio.h> union pointer { int num; char a; }; int main(){ union pointer p1; p1.num = 90; // p2 is a pointer to union p1 union pointer* p2 = &p1; // Accessing union members using pointer printf("%d %c", p2->num, p2->a); return 0; } When the above program is executed, it produces the following result − 90 Z
[ { "code": null, "e": 1152, "s": 1062, "text": "A union is a memory location that is shared by several variables of different data types." }, { "code": null, "e": 1223, "s": 1152, "text": "The syntax for the pointers to unions in C programming is as follows −" }, { "code": null, "e": 1324, "s": 1223, "text": "union uniontag{\n datatype member 1;\n datatype member 2;\n ----\n ----\n datatype member n;\n};" }, { "code": null, "e": 1385, "s": 1324, "text": "The following example shows the usage of union of structure." }, { "code": null, "e": 1435, "s": 1385, "text": "union sample{\n int a;\n float b;\n char c;\n};" }, { "code": null, "e": 1518, "s": 1435, "text": "Following is the declaration for union variable. It is of three types as follows −" }, { "code": null, "e": 1569, "s": 1518, "text": "union sample{\n int a;\n float b;\n char c;\n}s;" }, { "code": null, "e": 1613, "s": 1569, "text": "union{\n int a;\n float b;\n char c;\n}s;" }, { "code": null, "e": 1679, "s": 1613, "text": "union sample{\n int a;\n float b;\n char c;\n};\nunion sample s;" }, { "code": null, "e": 1797, "s": 1679, "text": "When union is declared, the compiler automatically creates largest size variable type to hold variables in the union." }, { "code": null, "e": 1915, "s": 1797, "text": "When union is declared, the compiler automatically creates largest size variable type to hold variables in the union." }, { "code": null, "e": 1962, "s": 1915, "text": "At any time only one variable can be referred." }, { "code": null, "e": 2009, "s": 1962, "text": "At any time only one variable can be referred." }, { "code": null, "e": 2068, "s": 2009, "text": "Same syntax of structure is used to access a union member." }, { "code": null, "e": 2127, "s": 2068, "text": "Same syntax of structure is used to access a union member." }, { "code": null, "e": 2170, "s": 2127, "text": "The dot operator is for accessing members." }, { "code": null, "e": 2213, "s": 2170, "text": "The dot operator is for accessing members." }, { "code": null, "e": 2287, "s": 2213, "text": "The arrow operator ( ->) is used for accessing the members using pointer." }, { "code": null, "e": 2361, "s": 2287, "text": "The arrow operator ( ->) is used for accessing the members using pointer." }, { "code": null, "e": 2463, "s": 2361, "text": "We have pointers to unions and can access members using the arrow operator (->) just like structures." }, { "code": null, "e": 2541, "s": 2463, "text": "The following program shows the usage of pointers to union in C programming −" }, { "code": null, "e": 2552, "s": 2541, "text": " Live Demo" }, { "code": null, "e": 2819, "s": 2552, "text": "#include <stdio.h>\nunion pointer {\n int num;\n char a;\n};\nint main(){\n union pointer p1;\n p1.num = 75;\n // p2 is a pointer to union p1\n union pointer* p2 = &p1;\n // Accessing union members using pointer\n printf(\"%d %c\", p2->num, p2->a);\n return 0;\n}" }, { "code": null, "e": 2890, "s": 2819, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 2895, "s": 2890, "text": "75 K" }, { "code": null, "e": 2943, "s": 2895, "text": "Consider the same example with different input." }, { "code": null, "e": 2954, "s": 2943, "text": " Live Demo" }, { "code": null, "e": 3221, "s": 2954, "text": "#include <stdio.h>\nunion pointer {\n int num;\n char a;\n};\nint main(){\n union pointer p1;\n p1.num = 90;\n // p2 is a pointer to union p1\n union pointer* p2 = &p1;\n // Accessing union members using pointer\n printf(\"%d %c\", p2->num, p2->a);\n return 0;\n}" }, { "code": null, "e": 3292, "s": 3221, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 3297, "s": 3292, "text": "90 Z" } ]
Program for Celsius To Fahrenheit conversion in C++
Given with temperature ‘n’ in Celsius the challenge is to convert the given temperature to Fahrenheit and display it. Input 1-: 100.00 Output -: 212.00 Input 2-: -40 Output-: -40 For converting the temperature from Celsius to Fahrenheit there is a formula which is given below T(°F) = T(°C) × 9/5 + 32 Where, T(°C) is temperature in Celsius and T(°F) is temperature in Fahrenheit Input temperature in a float variable let’s say Celsius Apply the formula to convert the temperature into Fahrenheit Print Fahrenheit Start Step 1 -> Declare a function to convert Celsius to Fahrenheit void cal(float cel) use formula float fahr = (cel * 9 / 5) + 32 print cel fahr Step 2 -> In main() Declare variable as float Celsius Call function cal(Celsius) Stop Live Demo #include <stdio.h> //convert Celsius to fahrenheit void cal(float cel){ float fahr = (cel * 9 / 5) + 32; printf("%.2f Celsius = %.2f Fahrenheit", cel, fahr); } int main(){ float Celsius=100.00; cal(Celsius); return 0; } 100.00 Celsius = 212.00 Fahrenheit Live Demo #include <bits/stdc++.h> using namespace std; float cel(float n){ return ((n * 9.0 / 5.0) + 32.0); } int main(){ float n = 20.0; cout << cel(n); return 0; } 68
[ { "code": null, "e": 1180, "s": 1062, "text": "Given with temperature ‘n’ in Celsius the challenge is to convert the given temperature to Fahrenheit and display it." }, { "code": null, "e": 1247, "s": 1180, "text": "Input 1-: 100.00\n Output -: 212.00\nInput 2-: -40\n Output-: -40" }, { "code": null, "e": 1345, "s": 1247, "text": "For converting the temperature from Celsius to Fahrenheit there is a formula which is given below" }, { "code": null, "e": 1370, "s": 1345, "text": "T(°F) = T(°C) × 9/5 + 32" }, { "code": null, "e": 1448, "s": 1370, "text": "Where, T(°C) is temperature in Celsius and T(°F) is temperature in Fahrenheit" }, { "code": null, "e": 1504, "s": 1448, "text": "Input temperature in a float variable let’s say Celsius" }, { "code": null, "e": 1565, "s": 1504, "text": "Apply the formula to convert the temperature into Fahrenheit" }, { "code": null, "e": 1582, "s": 1565, "text": "Print Fahrenheit" }, { "code": null, "e": 1836, "s": 1582, "text": "Start\nStep 1 -> Declare a function to convert Celsius to Fahrenheit\n void cal(float cel)\n use formula float fahr = (cel * 9 / 5) + 32\n print cel fahr\nStep 2 -> In main()\n Declare variable as float Celsius\n Call function cal(Celsius)\nStop" }, { "code": null, "e": 1847, "s": 1836, "text": " Live Demo" }, { "code": null, "e": 2082, "s": 1847, "text": "#include <stdio.h>\n//convert Celsius to fahrenheit\nvoid cal(float cel){\n float fahr = (cel * 9 / 5) + 32;\n printf(\"%.2f Celsius = %.2f Fahrenheit\", cel, fahr);\n}\nint main(){\n float Celsius=100.00;\n cal(Celsius);\n return 0;\n}" }, { "code": null, "e": 2117, "s": 2082, "text": "100.00 Celsius = 212.00 Fahrenheit" }, { "code": null, "e": 2128, "s": 2117, "text": " Live Demo" }, { "code": null, "e": 2297, "s": 2128, "text": "#include <bits/stdc++.h>\nusing namespace std;\nfloat cel(float n){\n return ((n * 9.0 / 5.0) + 32.0);\n}\nint main(){\n float n = 20.0;\n cout << cel(n);\n return 0;\n}" }, { "code": null, "e": 2300, "s": 2297, "text": "68" } ]
MomentJS - Days in Month
This method will give the numbers of days in the current month. moment().daysInMonth(); var a = moment().daysInMonth(); Let us check the days in a month for a given date using this method. Use the following code for this purpose − var a = moment([2016, 1]).daysInMonth(); For February in 2016, it displays days as 29. Print Add Notes Bookmark this page
[ { "code": null, "e": 2024, "s": 1960, "text": "This method will give the numbers of days in the current month." }, { "code": null, "e": 2049, "s": 2024, "text": "moment().daysInMonth();\n" }, { "code": null, "e": 2081, "s": 2049, "text": "var a = moment().daysInMonth();" }, { "code": null, "e": 2192, "s": 2081, "text": "Let us check the days in a month for a given date using this method. Use the following code for this purpose −" }, { "code": null, "e": 2233, "s": 2192, "text": "var a = moment([2016, 1]).daysInMonth();" }, { "code": null, "e": 2279, "s": 2233, "text": "For February in 2016, it displays days as 29." }, { "code": null, "e": 2286, "s": 2279, "text": " Print" }, { "code": null, "e": 2297, "s": 2286, "text": " Add Notes" } ]
How can we return a tuple from a Python function?
We can return a tuple from a python function in many ways. For the given tuple, we define a function as shown below. def foo(): str = "tutorialspoint" x = 30 return (str, x); print foo() ('tutorialspoint', 30)
[ { "code": null, "e": 1180, "s": 1062, "text": "We can return a tuple from a python function in many ways. For the given tuple, we define a function as shown below." }, { "code": null, "e": 1276, "s": 1180, "text": "def foo():\n str = \"tutorialspoint\"\n x = 30\n return (str, x); \nprint foo()" }, { "code": null, "e": 1299, "s": 1276, "text": "('tutorialspoint', 30)" } ]
3Sum Smaller in C++
Suppose we have an array of n integers called nums and we also have a target, we have to find the number of index triplets (i, j, k) here i, j, k all are in range 0 to n - 1 and that satisfy the condition nums[i] + nums[j] + nums[k] < target. So, if the input is like nums = [-2,0,1,3], and target = 2, then the output will be 2, as there are two triplets which sums are less than 2: [-2,0,1] and [-2,0,3]. To solve this, we will follow these steps − ret := 0 ret := 0 sort the array a sort the array a n := size of a n := size of a for initialize i := 0, when i < n - 2, update (increase i by 1), do −left := i + 1, right := n - 1while left < right, do −sum := a[i] + a[left] + a[right]if sum < t, then −ret := ret + right - left(increase left by 1)Otherwise(decrease right by 1) for initialize i := 0, when i < n - 2, update (increase i by 1), do − left := i + 1, right := n - 1 left := i + 1, right := n - 1 while left < right, do −sum := a[i] + a[left] + a[right]if sum < t, then −ret := ret + right - left(increase left by 1)Otherwise(decrease right by 1) while left < right, do − sum := a[i] + a[left] + a[right] sum := a[i] + a[left] + a[right] if sum < t, then −ret := ret + right - left(increase left by 1) if sum < t, then − ret := ret + right - left ret := ret + right - left (increase left by 1) (increase left by 1) Otherwise(decrease right by 1) Otherwise (decrease right by 1) (decrease right by 1) return ret return ret Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: int threeSumSmaller(vector<int<& a, int t) { int ret = 0; sort(a.begin(), a.end()); int n = a.size(); for (int i = 0; i < n - 2; i++) { int left = i + 1; int right = n - 1; while (left < right) { int sum = a[i] + a[left] + a[right]; if (sum < t) { ret += right - left; left++; } else right--; } } return ret; } }; main(){ Solution ob; vector<int< v = {-2,0,1,3}; cout << (ob.threeSumSmaller(v,2)); } [-2,0,1,3] 2 2
[ { "code": null, "e": 1305, "s": 1062, "text": "Suppose we have an array of n integers called nums and we also have a target, we have to find the number of index triplets (i, j, k) here i, j, k all are in range 0 to n - 1 and that satisfy the condition nums[i] + nums[j] + nums[k] < target." }, { "code": null, "e": 1469, "s": 1305, "text": "So, if the input is like nums = [-2,0,1,3], and target = 2, then the output will be 2, as there are two triplets which sums are less than 2: [-2,0,1] and [-2,0,3]." }, { "code": null, "e": 1513, "s": 1469, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1522, "s": 1513, "text": "ret := 0" }, { "code": null, "e": 1531, "s": 1522, "text": "ret := 0" }, { "code": null, "e": 1548, "s": 1531, "text": "sort the array a" }, { "code": null, "e": 1565, "s": 1548, "text": "sort the array a" }, { "code": null, "e": 1580, "s": 1565, "text": "n := size of a" }, { "code": null, "e": 1595, "s": 1580, "text": "n := size of a" }, { "code": null, "e": 1843, "s": 1595, "text": "for initialize i := 0, when i < n - 2, update (increase i by 1), do −left := i + 1, right := n - 1while left < right, do −sum := a[i] + a[left] + a[right]if sum < t, then −ret := ret + right - left(increase left by 1)Otherwise(decrease right by 1)" }, { "code": null, "e": 1913, "s": 1843, "text": "for initialize i := 0, when i < n - 2, update (increase i by 1), do −" }, { "code": null, "e": 1943, "s": 1913, "text": "left := i + 1, right := n - 1" }, { "code": null, "e": 1973, "s": 1943, "text": "left := i + 1, right := n - 1" }, { "code": null, "e": 2123, "s": 1973, "text": "while left < right, do −sum := a[i] + a[left] + a[right]if sum < t, then −ret := ret + right - left(increase left by 1)Otherwise(decrease right by 1)" }, { "code": null, "e": 2148, "s": 2123, "text": "while left < right, do −" }, { "code": null, "e": 2181, "s": 2148, "text": "sum := a[i] + a[left] + a[right]" }, { "code": null, "e": 2214, "s": 2181, "text": "sum := a[i] + a[left] + a[right]" }, { "code": null, "e": 2278, "s": 2214, "text": "if sum < t, then −ret := ret + right - left(increase left by 1)" }, { "code": null, "e": 2297, "s": 2278, "text": "if sum < t, then −" }, { "code": null, "e": 2323, "s": 2297, "text": "ret := ret + right - left" }, { "code": null, "e": 2349, "s": 2323, "text": "ret := ret + right - left" }, { "code": null, "e": 2370, "s": 2349, "text": "(increase left by 1)" }, { "code": null, "e": 2391, "s": 2370, "text": "(increase left by 1)" }, { "code": null, "e": 2422, "s": 2391, "text": "Otherwise(decrease right by 1)" }, { "code": null, "e": 2432, "s": 2422, "text": "Otherwise" }, { "code": null, "e": 2454, "s": 2432, "text": "(decrease right by 1)" }, { "code": null, "e": 2476, "s": 2454, "text": "(decrease right by 1)" }, { "code": null, "e": 2487, "s": 2476, "text": "return ret" }, { "code": null, "e": 2498, "s": 2487, "text": "return ret" }, { "code": null, "e": 2568, "s": 2498, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2579, "s": 2568, "text": " Live Demo" }, { "code": null, "e": 3230, "s": 2579, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n int threeSumSmaller(vector<int<& a, int t) {\n int ret = 0;\n sort(a.begin(), a.end());\n int n = a.size();\n for (int i = 0; i < n - 2; i++) {\n int left = i + 1;\n int right = n - 1;\n while (left < right) {\n int sum = a[i] + a[left] + a[right];\n if (sum < t) {\n ret += right - left;\n left++;\n }\n else\n right--;\n }\n }\n return ret;\n }\n};\nmain(){\n Solution ob;\n vector<int< v = {-2,0,1,3};\n cout << (ob.threeSumSmaller(v,2));\n}" }, { "code": null, "e": 3243, "s": 3230, "text": "[-2,0,1,3] 2" }, { "code": null, "e": 3245, "s": 3243, "text": "2" } ]
System.exit() in Java
10 Jul, 2016 The java.lang.System.exit() method exits current program by terminating running Java virtual machine. This method takes a status code. A non-zero value of status code is generally used to indicate abnormal termination. This is similar exit in C/C++. Following is the declaration for java.lang.System.exit() method: public static void exit(int status) exit(0) : Generally used to indicate successful termination.exit(1) or exit(-1) or any other non-zero value – Generally indicates unsuccessful termination. Note : This method does not return any value. The following example shows the usage of java.lang.System.exit() method. // A Java program to demonstrate working of exit()import java.util.*;import java.lang.*; class GfG{ public static void main(String[] args) { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; for (int i = 0; i < arr.length; i++) { if (arr[i] >= 5) { System.out.println("exit..."); // Terminate JVM System.exit(0); } else System.out.println("arr["+i+"] = " + arr[i]); } System.out.println("End of Program"); }} Output: arr[0] = 1 arr[1] = 2 arr[2] = 3 arr[3] = 4 exit... Reference :https://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html This article is contributed by Amit Khandelwal .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. Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n10 Jul, 2016" }, { "code": null, "e": 303, "s": 53, "text": "The java.lang.System.exit() method exits current program by terminating running Java virtual machine. This method takes a status code. A non-zero value of status code is generally used to indicate abnormal termination. This is similar exit in C/C++." }, { "code": null, "e": 368, "s": 303, "text": "Following is the declaration for java.lang.System.exit() method:" }, { "code": null, "e": 404, "s": 368, "text": "public static void exit(int status)" }, { "code": null, "e": 560, "s": 404, "text": "exit(0) : Generally used to indicate successful termination.exit(1) or exit(-1) or any other non-zero value – Generally indicates unsuccessful termination." }, { "code": null, "e": 606, "s": 560, "text": "Note : This method does not return any value." }, { "code": null, "e": 679, "s": 606, "text": "The following example shows the usage of java.lang.System.exit() method." }, { "code": "// A Java program to demonstrate working of exit()import java.util.*;import java.lang.*; class GfG{ public static void main(String[] args) { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; for (int i = 0; i < arr.length; i++) { if (arr[i] >= 5) { System.out.println(\"exit...\"); // Terminate JVM System.exit(0); } else System.out.println(\"arr[\"+i+\"] = \" + arr[i]); } System.out.println(\"End of Program\"); }}", "e": 1262, "s": 679, "text": null }, { "code": null, "e": 1270, "s": 1262, "text": "Output:" }, { "code": null, "e": 1323, "s": 1270, "text": "arr[0] = 1\narr[1] = 2\narr[2] = 3\narr[3] = 4\nexit...\n" }, { "code": null, "e": 1399, "s": 1323, "text": "Reference :https://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html" }, { "code": null, "e": 1702, "s": 1399, "text": "This article is contributed by Amit Khandelwal .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": 1827, "s": 1702, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 1832, "s": 1827, "text": "Java" }, { "code": null, "e": 1837, "s": 1832, "text": "Java" } ]
SciPy - Linalg
SciPy is built using the optimized ATLAS LAPACK and BLAS libraries. It has very fast linear algebra capabilities. All of these linear algebra routines expect an object that can be converted into a two-dimensional array. The output of these routines is also a two-dimensional array. A scipy.linalg contains all the functions that are in numpy.linalg. Additionally, scipy.linalg also has some other advanced functions that are not in numpy.linalg. Another advantage of using scipy.linalg over numpy.linalg is that it is always compiled with BLAS/LAPACK support, while for NumPy this is optional. Therefore, the SciPy version might be faster depending on how NumPy was installed. The scipy.linalg.solve feature solves the linear equation a * x + b * y = Z, for the unknown x, y values. As an example, assume that it is desired to solve the following simultaneous equations. x + 3y + 5z = 10 2x + 5y + z = 8 2x + 3y + 8z = 3 To solve the above equation for the x, y, z values, we can find the solution vector using a matrix inverse as shown below. $$\begin{bmatrix} x\\ y\\ z \end{bmatrix} = \begin{bmatrix} 1 & 3 & 5\\ 2 & 5 & 1\\ 2 & 3 & 8 \end{bmatrix}^{-1} \begin{bmatrix} 10\\ 8\\ 3 \end{bmatrix} = \frac{1}{25} \begin{bmatrix} -232\\ 129\\ 19 \end{bmatrix} = \begin{bmatrix} -9.28\\ 5.16\\ 0.76 \end{bmatrix}.$$ However, it is better to use the linalg.solve command, which can be faster and more numerically stable. The solve function takes two inputs ‘a’ and ‘b’ in which ‘a’ represents the coefficients and ‘b’ represents the respective right hand side value and returns the solution array. Let us consider the following example. #importing the scipy and numpy packages from scipy import linalg import numpy as np #Declaring the numpy arrays a = np.array([[3, 2, 0], [1, -1, 0], [0, 5, 1]]) b = np.array([2, 4, -1]) #Passing the values to the solve function x = linalg.solve(a, b) #printing the result array print x The above program will generate the following output. array([ 2., -2., 9.]) The determinant of a square matrix A is often denoted as |A| and is a quantity often used in linear algebra. In SciPy, this is computed using the det() function. It takes a matrix as input and returns a scalar value. Let us consider the following example. #importing the scipy and numpy packages from scipy import linalg import numpy as np #Declaring the numpy array A = np.array([[1,2],[3,4]]) #Passing the values to the det function x = linalg.det(A) #printing the result print x The above program will generate the following output. -2.0 The eigenvalue-eigenvector problem is one of the most commonly employed linear algebra operations. We can find the Eigen values (λ) and the corresponding Eigen vectors (v) of a square matrix (A) by considering the following relation − Av = λv scipy.linalg.eig computes the eigenvalues from an ordinary or generalized eigenvalue problem. This function returns the Eigen values and the Eigen vectors. Let us consider the following example. #importing the scipy and numpy packages from scipy import linalg import numpy as np #Declaring the numpy array A = np.array([[1,2],[3,4]]) #Passing the values to the eig function l, v = linalg.eig(A) #printing the result for eigen values print l #printing the result for eigen vectors print v The above program will generate the following output. array([-0.37228132+0.j, 5.37228132+0.j]) #--Eigen Values array([[-0.82456484, -0.41597356], #--Eigen Vectors [ 0.56576746, -0.90937671]]) A Singular Value Decomposition (SVD) can be thought of as an extension of the eigenvalue problem to matrices that are not square. The scipy.linalg.svd factorizes the matrix ‘a’ into two unitary matrices ‘U’ and ‘Vh’ and a 1-D array ‘s’ of singular values (real, non-negative) such that a == U*S*Vh, where ‘S’ is a suitably shaped matrix of zeros with the main diagonal ‘s’. Let us consider the following example. #importing the scipy and numpy packages from scipy import linalg import numpy as np #Declaring the numpy array a = np.random.randn(3, 2) + 1.j*np.random.randn(3, 2) #Passing the values to the eig function U, s, Vh = linalg.svd(a) # printing the result print U, Vh, s The above program will generate the following output. ( array([ [ 0.54828424-0.23329795j, -0.38465728+0.01566714j, -0.18764355+0.67936712j], [-0.27123194-0.5327436j , -0.57080163-0.00266155j, -0.39868941-0.39729416j], [ 0.34443818+0.4110186j , -0.47972716+0.54390586j, 0.25028608-0.35186815j] ]), array([ 3.25745379, 1.16150607]), array([ [-0.35312444+0.j , 0.32400401+0.87768134j], [-0.93557636+0.j , -0.12229224-0.33127251j]
[ { "code": null, "e": 2303, "s": 2021, "text": "SciPy is built using the optimized ATLAS LAPACK and BLAS libraries. It has very fast linear algebra capabilities. All of these linear algebra routines expect an object that can be converted into a two-dimensional array. The output of these routines is also a two-dimensional array." }, { "code": null, "e": 2698, "s": 2303, "text": "A scipy.linalg contains all the functions that are in numpy.linalg. Additionally, scipy.linalg also has some other advanced functions that are not in numpy.linalg. Another advantage of using scipy.linalg over numpy.linalg is that it is always compiled with BLAS/LAPACK support, while for NumPy this is optional. Therefore, the SciPy version might be faster depending on how NumPy was installed." }, { "code": null, "e": 2804, "s": 2698, "text": "The scipy.linalg.solve feature solves the linear equation a * x + b * y = Z, for the unknown x, y values." }, { "code": null, "e": 2892, "s": 2804, "text": "As an example, assume that it is desired to solve the following simultaneous equations." }, { "code": null, "e": 2909, "s": 2892, "text": "x + 3y + 5z = 10" }, { "code": null, "e": 2925, "s": 2909, "text": "2x + 5y + z = 8" }, { "code": null, "e": 2942, "s": 2925, "text": "2x + 3y + 8z = 3" }, { "code": null, "e": 3065, "s": 2942, "text": "To solve the above equation for the x, y, z values, we can find the solution vector using a matrix inverse as shown below." }, { "code": null, "e": 3345, "s": 3065, "text": "$$\\begin{bmatrix}\nx\\\\ \ny\\\\ \nz\n\\end{bmatrix} = \\begin{bmatrix}\n1 & 3 & 5\\\\ \n2 & 5 & 1\\\\ \n2 & 3 & 8\n\\end{bmatrix}^{-1} \\begin{bmatrix}\n10\\\\ \n8\\\\ \n3\n\\end{bmatrix} = \\frac{1}{25} \\begin{bmatrix}\n-232\\\\ \n129\\\\ \n19\n\\end{bmatrix} = \\begin{bmatrix}\n-9.28\\\\ \n5.16\\\\ \n0.76\n\\end{bmatrix}.$$" }, { "code": null, "e": 3449, "s": 3345, "text": "However, it is better to use the linalg.solve command, which can be faster and more numerically stable." }, { "code": null, "e": 3626, "s": 3449, "text": "The solve function takes two inputs ‘a’ and ‘b’ in which ‘a’ represents the coefficients and ‘b’ represents the respective right hand side value and returns the solution array." }, { "code": null, "e": 3665, "s": 3626, "text": "Let us consider the following example." }, { "code": null, "e": 3954, "s": 3665, "text": "#importing the scipy and numpy packages\nfrom scipy import linalg\nimport numpy as np\n\n#Declaring the numpy arrays\na = np.array([[3, 2, 0], [1, -1, 0], [0, 5, 1]])\nb = np.array([2, 4, -1])\n\n#Passing the values to the solve function\nx = linalg.solve(a, b)\n\n#printing the result array\nprint x" }, { "code": null, "e": 4008, "s": 3954, "text": "The above program will generate the following output." }, { "code": null, "e": 4031, "s": 4008, "text": "array([ 2., -2., 9.])\n" }, { "code": null, "e": 4248, "s": 4031, "text": "The determinant of a square matrix A is often denoted as |A| and is a quantity often used in linear algebra. In SciPy, this is computed using the det() function. It takes a matrix as input and returns a scalar value." }, { "code": null, "e": 4287, "s": 4248, "text": "Let us consider the following example." }, { "code": null, "e": 4516, "s": 4287, "text": "#importing the scipy and numpy packages\nfrom scipy import linalg\nimport numpy as np\n\n#Declaring the numpy array\nA = np.array([[1,2],[3,4]])\n\n#Passing the values to the det function\nx = linalg.det(A)\n\n#printing the result\nprint x" }, { "code": null, "e": 4570, "s": 4516, "text": "The above program will generate the following output." }, { "code": null, "e": 4576, "s": 4570, "text": "-2.0\n" }, { "code": null, "e": 4811, "s": 4576, "text": "The eigenvalue-eigenvector problem is one of the most commonly employed linear algebra operations. We can find the Eigen values (λ) and the corresponding Eigen vectors (v) of a square matrix (A) by considering the following relation −" }, { "code": null, "e": 4819, "s": 4811, "text": "Av = λv" }, { "code": null, "e": 4975, "s": 4819, "text": "scipy.linalg.eig computes the eigenvalues from an ordinary or generalized eigenvalue problem. This function returns the Eigen values and the Eigen vectors." }, { "code": null, "e": 5014, "s": 4975, "text": "Let us consider the following example." }, { "code": null, "e": 5311, "s": 5014, "text": "#importing the scipy and numpy packages\nfrom scipy import linalg\nimport numpy as np\n\n#Declaring the numpy array\nA = np.array([[1,2],[3,4]])\n\n#Passing the values to the eig function\nl, v = linalg.eig(A)\n\n#printing the result for eigen values\nprint l\n\n#printing the result for eigen vectors\nprint v" }, { "code": null, "e": 5365, "s": 5311, "text": "The above program will generate the following output." }, { "code": null, "e": 5511, "s": 5365, "text": "array([-0.37228132+0.j, 5.37228132+0.j]) #--Eigen Values\narray([[-0.82456484, -0.41597356], #--Eigen Vectors\n [ 0.56576746, -0.90937671]])\n" }, { "code": null, "e": 5641, "s": 5511, "text": "A Singular Value Decomposition (SVD) can be thought of as an extension of the eigenvalue problem to matrices that are not square." }, { "code": null, "e": 5885, "s": 5641, "text": "The scipy.linalg.svd factorizes the matrix ‘a’ into two unitary matrices ‘U’ and ‘Vh’ and a 1-D array ‘s’ of singular values (real, non-negative) such that a == U*S*Vh, where ‘S’ is a suitably shaped matrix of zeros with the main diagonal ‘s’." }, { "code": null, "e": 5924, "s": 5885, "text": "Let us consider the following example." }, { "code": null, "e": 6194, "s": 5924, "text": "#importing the scipy and numpy packages\nfrom scipy import linalg\nimport numpy as np\n\n#Declaring the numpy array\na = np.random.randn(3, 2) + 1.j*np.random.randn(3, 2)\n\n#Passing the values to the eig function\nU, s, Vh = linalg.svd(a)\n\n# printing the result\nprint U, Vh, s" }, { "code": null, "e": 6248, "s": 6194, "text": "The above program will generate the following output." } ]
Python | Remove empty tuples from a list
04 Jul, 2022 In this article, we will see how can we remove an empty tuple from a given list of tuples. We will find various ways, in which we can perform this task of removing tuples using various methods and ways in Python. Examples: Input : tuples = [(), ('ram','15','8'), (), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('',''),()] Output : [('ram', '15', '8'), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('', '')] Input : tuples = [('','','8'), (), ('0', '00', '000'), ('birbal', '', '45'), (''), (), ('',''),()] Output : [('', '', '8'), ('0', '00', '000'), ('birbal', '', '45'), ('', '')] Method 1: Using the concept of List Comprehension Python3 # Python program to remove empty tuples from a# list of tuples function to remove empty tuples# using list comprehensiondef Remove(tuples): tuples = [t for t in tuples if t] return tuples # Driver Codetuples = [(), ('ram','15','8'), (), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('',''),()]print(Remove(tuples)) Output: [('ram', '15', '8'), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('', '')] Method 2: Using the filter() method Using the inbuilt method filter() in Python, we can filter out the empty elements by passing the None as the parameter. This method works in both Python 2 and Python 3 and above, but the desired output is only shown in Python 2 because Python 3 returns a generator. filter() is the faster than the method of list comprehension. Let’s see what happens when we run the program in Python 2. Python # Python2 program to remove empty tuples# from a list of tuples function to remove# empty tuples using filterdef Remove(tuples): tuples = filter(None, tuples) return tuples # Driver Codetuples = [(), ('ram','15','8'), (), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('',''),()]print Remove(tuples) Output: [('ram', '15', '8'), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('', '')] Now let’s see what happens when we try running the program in Python 3 and above. On running the program in Python 3, as mentioned a generator is returned. Python3 # Python program to remove empty tuples from# a list of tuples function to remove empty# tuples using filterdef Remove(tuples): tuples = filter(None, tuples) return tuples # Driver Codetuples = [(), ('ram','15','8'), (), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('',''),()]print (Remove(tuples)) Output: <filter object at 0x7fe26eb0f3c8> Method #3 : Using len() method Python3 # Python program to remove empty tuples from a# list of tuples function to remove empty tuples# using len()def Remove(tuples): for i in tuples: if(len(i)==0): tuples.remove(i) return tuples# Driver Codetuples = [(), ('ram','15','8'), (), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('',''),()]print(Remove(tuples)) [('ram', '15', '8'), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('', '')] kogantibhavya Python list-programs python-tuple Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Jul, 2022" }, { "code": null, "e": 275, "s": 52, "text": "In this article, we will see how can we remove an empty tuple from a given list of tuples. We will find various ways, in which we can perform this task of removing tuples using various methods and ways in Python. Examples:" }, { "code": null, "e": 704, "s": 275, "text": "Input : tuples = [(), ('ram','15','8'), (), ('laxman', 'sita'), \n ('krishna', 'akbar', '45'), ('',''),()]\nOutput : [('ram', '15', '8'), ('laxman', 'sita'), \n ('krishna', 'akbar', '45'), ('', '')]\n\nInput : tuples = [('','','8'), (), ('0', '00', '000'), \n ('birbal', '', '45'), (''), (), ('',''),()]\nOutput : [('', '', '8'), ('0', '00', '000'), ('birbal', '', \n '45'), ('', '')]" }, { "code": null, "e": 755, "s": 704, "text": "Method 1: Using the concept of List Comprehension " }, { "code": null, "e": 763, "s": 755, "text": "Python3" }, { "code": "# Python program to remove empty tuples from a# list of tuples function to remove empty tuples# using list comprehensiondef Remove(tuples): tuples = [t for t in tuples if t] return tuples # Driver Codetuples = [(), ('ram','15','8'), (), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('',''),()]print(Remove(tuples))", "e": 1096, "s": 763, "text": null }, { "code": null, "e": 1104, "s": 1096, "text": "Output:" }, { "code": null, "e": 1211, "s": 1104, "text": "[('ram', '15', '8'), ('laxman', 'sita'), ('krishna', \n 'akbar', '45'), ('', '')]" }, { "code": null, "e": 1636, "s": 1211, "text": "Method 2: Using the filter() method Using the inbuilt method filter() in Python, we can filter out the empty elements by passing the None as the parameter. This method works in both Python 2 and Python 3 and above, but the desired output is only shown in Python 2 because Python 3 returns a generator. filter() is the faster than the method of list comprehension. Let’s see what happens when we run the program in Python 2. " }, { "code": null, "e": 1643, "s": 1636, "text": "Python" }, { "code": "# Python2 program to remove empty tuples# from a list of tuples function to remove# empty tuples using filterdef Remove(tuples): tuples = filter(None, tuples) return tuples # Driver Codetuples = [(), ('ram','15','8'), (), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('',''),()]print Remove(tuples)", "e": 1960, "s": 1643, "text": null }, { "code": null, "e": 1968, "s": 1960, "text": "Output:" }, { "code": null, "e": 2047, "s": 1968, "text": "[('ram', '15', '8'), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('', '')]" }, { "code": null, "e": 2204, "s": 2047, "text": "Now let’s see what happens when we try running the program in Python 3 and above. On running the program in Python 3, as mentioned a generator is returned. " }, { "code": null, "e": 2212, "s": 2204, "text": "Python3" }, { "code": "# Python program to remove empty tuples from# a list of tuples function to remove empty# tuples using filterdef Remove(tuples): tuples = filter(None, tuples) return tuples # Driver Codetuples = [(), ('ram','15','8'), (), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('',''),()]print (Remove(tuples))", "e": 2530, "s": 2212, "text": null }, { "code": null, "e": 2538, "s": 2530, "text": "Output:" }, { "code": null, "e": 2572, "s": 2538, "text": "<filter object at 0x7fe26eb0f3c8>" }, { "code": null, "e": 2603, "s": 2572, "text": "Method #3 : Using len() method" }, { "code": null, "e": 2611, "s": 2603, "text": "Python3" }, { "code": "# Python program to remove empty tuples from a# list of tuples function to remove empty tuples# using len()def Remove(tuples): for i in tuples: if(len(i)==0): tuples.remove(i) return tuples# Driver Codetuples = [(), ('ram','15','8'), (), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('',''),()]print(Remove(tuples))", "e": 2961, "s": 2611, "text": null }, { "code": null, "e": 3040, "s": 2961, "text": "[('ram', '15', '8'), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('', '')]" }, { "code": null, "e": 3054, "s": 3040, "text": "kogantibhavya" }, { "code": null, "e": 3075, "s": 3054, "text": "Python list-programs" }, { "code": null, "e": 3088, "s": 3075, "text": "python-tuple" }, { "code": null, "e": 3095, "s": 3088, "text": "Python" }, { "code": null, "e": 3193, "s": 3095, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3235, "s": 3193, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3257, "s": 3235, "text": "Enumerate() in Python" }, { "code": null, "e": 3283, "s": 3257, "text": "Python String | replace()" }, { "code": null, "e": 3315, "s": 3283, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3344, "s": 3315, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3371, "s": 3344, "text": "Python Classes and Objects" }, { "code": null, "e": 3392, "s": 3371, "text": "Python OOPs Concepts" }, { "code": null, "e": 3428, "s": 3392, "text": "Convert integer to string in Python" }, { "code": null, "e": 3451, "s": 3428, "text": "Introduction To PYTHON" } ]
Why React uses className over class attribute ?
26 Aug, 2021 To all the regular DOM and SVG elements like <button>, <li>, <a>, <div>, etc. , if we want to apply the CSS classes, we use className attribute instead of class in React. That’s why it warns you every time when you mistakenly write class instead of className. In fact, in earlier times before React 16, if you wrote JSX with an unknown element that does not recognize by React, it would simply skip it. For example: <div myatrribute="xyz" /> The above line of code would render an empty div to the DOM in React 15, // React 15 output <div /> But in React 16, this unknown attribute “xyz” will end up in the DOM as well. // React 16 output <div myatrribute="xyz" /> That’s why, in React 15, when you use class to specify a css class to any element, it would just warn you and ignore that. But now due to the new DOM attributes handling in React 16, it still warns but converts values to strings and passes them through as well. Creating React Application: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Project Structure: It will look like the following. Project Structure Example 1: Now, Let’s understand this with some practical implementation, suppose we simply render a heading <h1> with some text in its inner HTML from our default component App.js. App.js import "./App.css"; function App() { return <h1 class="heading1">This is an example code</h1>;} export default App; Output: In the above code, we have used class instead of className and hence in the console, we received a warning which says: “Invalid DOM property ‘class’, Did you mean ‘className’? ” But it only warns you in React 16, and that is why output in above code has not get affected by it. Example 2: You can get rid of the above example’s warning by simply using the className in place of class, as done in below example: App.js import "./App.css"; function App() { return <h1 className="heading1">This is an example code</h1>;} export default App; Output: Explanation: The only reason behind the fact that it uses className over class is that the class is a reserved keyword in JavaScript and since we use JSX in React which itself is the extension of JavaScript, so we have to use className instead of class attribute. However, there are very less few scenarios where the DOM property for a given HTML attribute uses a different name. For example class as className. But nothing has changed with it, the semantic meaning of both className and class is the same, when JSX is rendered, the className attribute is automatically rendered as a class attribute. simmytarika5 Picked 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 do crud operations in ReactJS ? How to create a multi-page website using React.js ? 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": "\n26 Aug, 2021" }, { "code": null, "e": 313, "s": 52, "text": "To all the regular DOM and SVG elements like <button>, <li>, <a>, <div>, etc. , if we want to apply the CSS classes, we use className attribute instead of class in React. That’s why it warns you every time when you mistakenly write class instead of className. " }, { "code": null, "e": 470, "s": 313, "text": "In fact, in earlier times before React 16, if you wrote JSX with an unknown element that does not recognize by React, it would simply skip it. For example: " }, { "code": null, "e": 496, "s": 470, "text": "<div myatrribute=\"xyz\" />" }, { "code": null, "e": 571, "s": 496, "text": " The above line of code would render an empty div to the DOM in React 15, " }, { "code": null, "e": 598, "s": 571, "text": "// React 15 output\n<div />" }, { "code": null, "e": 677, "s": 598, "text": "But in React 16, this unknown attribute “xyz” will end up in the DOM as well. " }, { "code": null, "e": 722, "s": 677, "text": "// React 16 output\n<div myatrribute=\"xyz\" />" }, { "code": null, "e": 984, "s": 722, "text": "That’s why, in React 15, when you use class to specify a css class to any element, it would just warn you and ignore that. But now due to the new DOM attributes handling in React 16, it still warns but converts values to strings and passes them through as well." }, { "code": null, "e": 1012, "s": 984, "text": "Creating React Application:" }, { "code": null, "e": 1076, "s": 1012, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 1108, "s": 1076, "text": "npx create-react-app foldername" }, { "code": null, "e": 1208, "s": 1108, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 1222, "s": 1208, "text": "cd foldername" }, { "code": null, "e": 1274, "s": 1222, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 1292, "s": 1274, "text": "Project Structure" }, { "code": null, "e": 1474, "s": 1292, "text": "Example 1: Now, Let’s understand this with some practical implementation, suppose we simply render a heading <h1> with some text in its inner HTML from our default component App.js." }, { "code": null, "e": 1481, "s": 1474, "text": "App.js" }, { "code": "import \"./App.css\"; function App() { return <h1 class=\"heading1\">This is an example code</h1>;} export default App;", "e": 1600, "s": 1481, "text": null }, { "code": null, "e": 1886, "s": 1600, "text": "Output: In the above code, we have used class instead of className and hence in the console, we received a warning which says: “Invalid DOM property ‘class’, Did you mean ‘className’? ” But it only warns you in React 16, and that is why output in above code has not get affected by it." }, { "code": null, "e": 2019, "s": 1886, "text": "Example 2: You can get rid of the above example’s warning by simply using the className in place of class, as done in below example:" }, { "code": null, "e": 2026, "s": 2019, "text": "App.js" }, { "code": "import \"./App.css\"; function App() { return <h1 className=\"heading1\">This is an example code</h1>;} export default App;", "e": 2149, "s": 2026, "text": null }, { "code": null, "e": 2157, "s": 2149, "text": "Output:" }, { "code": null, "e": 2758, "s": 2157, "text": "Explanation: The only reason behind the fact that it uses className over class is that the class is a reserved keyword in JavaScript and since we use JSX in React which itself is the extension of JavaScript, so we have to use className instead of class attribute. However, there are very less few scenarios where the DOM property for a given HTML attribute uses a different name. For example class as className. But nothing has changed with it, the semantic meaning of both className and class is the same, when JSX is rendered, the className attribute is automatically rendered as a class attribute." }, { "code": null, "e": 2771, "s": 2758, "text": "simmytarika5" }, { "code": null, "e": 2778, "s": 2771, "text": "Picked" }, { "code": null, "e": 2794, "s": 2778, "text": "React-Questions" }, { "code": null, "e": 2802, "s": 2794, "text": "ReactJS" }, { "code": null, "e": 2819, "s": 2802, "text": "Web Technologies" }, { "code": null, "e": 2917, "s": 2819, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2955, "s": 2917, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 2982, "s": 2955, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 3021, "s": 2982, "text": "How to install bootstrap in React.js ?" }, { "code": null, "e": 3060, "s": 3021, "text": "How to do crud operations in ReactJS ?" }, { "code": null, "e": 3112, "s": 3060, "text": "How to create a multi-page website using React.js ?" }, { "code": null, "e": 3145, "s": 3112, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3207, "s": 3145, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3268, "s": 3207, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3318, "s": 3268, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Java Program to Get the Size of a Directory
27 Apr, 2021 The size of files in Java can be obtained using the File class. The in-built function of ‘fileName.length()’ is used to find size of file in Bytes. The directory may contain ‘N’ number of files, for calculating the size of the directory summation of the size of all the files is required. length() Method: length() method in the object of the file class is returning the file size in long(datatype) format. The file size is in a unit of Byte. Return Type: long Syntax: java.io.File file = new java.io.File("file_name.txt"); file.length(); Working: If the file exists then the function return the size of the fileElse the function returns null. If the file exists then the function return the size of the file Else the function returns null. However, the size of the file can be display in Mega, Kilo units using unit conversion. Java // Java program to Get the size of a directory import java.io.File; class GFG { private static long getFolderSize(File folder) { long length = 0; // listFiles() is used to list the // contents of the given folder File[] files = folder.listFiles(); int count = files.length; // loop for traversing the directory for (int i = 0; i < count; i++) { if (files[i].isFile()) { length += files[i].length(); } else { length += getFolderSize(files[i]); } } return length; } // Driver Code public static void main(String[] args) { // Creating an instances of file class File file1 = new File("/home/mayur/Downloads"); long size = getFolderSize(file1); // Size of folder in Bytes System.out.println("Size of " + file1 + " is " + size + " B"); // Size of folder in Kilobytes System.out.println("Size of " + file1 + " is " + (double)size / 1024 + " KB"); // Size of folder in Megabytes System.out.println("Size of " + file1 + " is " + (double)size / (1024 * 1024) + " MB"); }} sweetyty Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Introduction to Java Exceptions in Java Java Programming Examples Java Programming Examples Implementing a Linked List in Java using Class Program to print ASCII Value of a character Traverse Through a HashMap in Java Convert Double to Integer in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Apr, 2021" }, { "code": null, "e": 317, "s": 28, "text": "The size of files in Java can be obtained using the File class. The in-built function of ‘fileName.length()’ is used to find size of file in Bytes. The directory may contain ‘N’ number of files, for calculating the size of the directory summation of the size of all the files is required." }, { "code": null, "e": 334, "s": 317, "text": "length() Method:" }, { "code": null, "e": 471, "s": 334, "text": "length() method in the object of the file class is returning the file size in long(datatype) format. The file size is in a unit of Byte." }, { "code": null, "e": 489, "s": 471, "text": "Return Type: long" }, { "code": null, "e": 497, "s": 489, "text": "Syntax:" }, { "code": null, "e": 567, "s": 497, "text": "java.io.File file = new java.io.File(\"file_name.txt\");\nfile.length();" }, { "code": null, "e": 576, "s": 567, "text": "Working:" }, { "code": null, "e": 672, "s": 576, "text": "If the file exists then the function return the size of the fileElse the function returns null." }, { "code": null, "e": 737, "s": 672, "text": "If the file exists then the function return the size of the file" }, { "code": null, "e": 769, "s": 737, "text": "Else the function returns null." }, { "code": null, "e": 857, "s": 769, "text": "However, the size of the file can be display in Mega, Kilo units using unit conversion." }, { "code": null, "e": 862, "s": 857, "text": "Java" }, { "code": "// Java program to Get the size of a directory import java.io.File; class GFG { private static long getFolderSize(File folder) { long length = 0; // listFiles() is used to list the // contents of the given folder File[] files = folder.listFiles(); int count = files.length; // loop for traversing the directory for (int i = 0; i < count; i++) { if (files[i].isFile()) { length += files[i].length(); } else { length += getFolderSize(files[i]); } } return length; } // Driver Code public static void main(String[] args) { // Creating an instances of file class File file1 = new File(\"/home/mayur/Downloads\"); long size = getFolderSize(file1); // Size of folder in Bytes System.out.println(\"Size of \" + file1 + \" is \" + size + \" B\"); // Size of folder in Kilobytes System.out.println(\"Size of \" + file1 + \" is \" + (double)size / 1024 + \" KB\"); // Size of folder in Megabytes System.out.println(\"Size of \" + file1 + \" is \" + (double)size / (1024 * 1024) + \" MB\"); }}", "e": 2161, "s": 862, "text": null }, { "code": null, "e": 2170, "s": 2161, "text": "sweetyty" }, { "code": null, "e": 2175, "s": 2170, "text": "Java" }, { "code": null, "e": 2189, "s": 2175, "text": "Java Programs" }, { "code": null, "e": 2194, "s": 2189, "text": "Java" }, { "code": null, "e": 2292, "s": 2194, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2307, "s": 2292, "text": "Stream In Java" }, { "code": null, "e": 2328, "s": 2307, "text": "Constructors in Java" }, { "code": null, "e": 2349, "s": 2328, "text": "Introduction to Java" }, { "code": null, "e": 2368, "s": 2349, "text": "Exceptions in Java" }, { "code": null, "e": 2394, "s": 2368, "text": "Java Programming Examples" }, { "code": null, "e": 2420, "s": 2394, "text": "Java Programming Examples" }, { "code": null, "e": 2467, "s": 2420, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 2511, "s": 2467, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 2546, "s": 2511, "text": "Traverse Through a HashMap in Java" } ]
JQuery | Change the text of a span element
23 May, 2019 Given an HTML document and the task is to change the text content of a <span> element. There are various methods used to change the span elements which are discussed below: jQuery text() Method: This method set/return the text content of specified elements. If this method is used to return content, it returns the text content of all matched elements (HTML tags will be removed). If this method is used to set content, it overwrites the content of all matched elements.Syntax:It returns the text content.$(selector).text()It sets the text content.$(selector).text(content)Set text content using a function.$(selector).text(function(index, curContent))Parameters:content: It is required parameter. It specifies the new text content for the selected elements.function(index, curContent): It is optional parameter. It specifies the function that returns the new text content for the selected elements.index: It returns the index position of element in the set.curContent: It returns the current content of selected elements. Syntax: It returns the text content.$(selector).text() $(selector).text() It sets the text content.$(selector).text(content) $(selector).text(content) Set text content using a function.$(selector).text(function(index, curContent)) $(selector).text(function(index, curContent)) Parameters: content: It is required parameter. It specifies the new text content for the selected elements. function(index, curContent): It is optional parameter. It specifies the function that returns the new text content for the selected elements. index: It returns the index position of element in the set. curContent: It returns the current content of selected elements. jQuery html() Method: This method set/return the content (HTML) of the specified elements. If this method is used to return content, it returns the content of the first matched element. If this method is used to set content, it overwrites the content of all matched elements.Syntax:Return content$(selector).html() Set content$(selector).html(content) Set content using a function$(selector).html(function(index, curContent)) Parameters:content: It is required parameter. It specifies the new text content for the selected elements containing the HTML tags.function(index, curContent): It is optional parameter. It specifies the function that returns the new content for the selected elements.index: It returns the index position of element in the set.curContent: It returns the current HTML content of selected elements. Syntax: Return content$(selector).html() $(selector).html() Set content$(selector).html(content) $(selector).html(content) Set content using a function$(selector).html(function(index, curContent)) $(selector).html(function(index, curContent)) Parameters: content: It is required parameter. It specifies the new text content for the selected elements containing the HTML tags. function(index, curContent): It is optional parameter. It specifies the function that returns the new content for the selected elements. index: It returns the index position of element in the set. curContent: It returns the current HTML content of selected elements. Example 1: This example changes the content by using JQuery’s text() method . <!DOCTYPE HTML> <html> <head> <title> JQuery | Change the text of a span element </title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> </head> <body style = "text-align:center;" id = "body"> <h1 style = "color:green;" > GeeksForGeeks </h1> <span id="GFG_Span" style = "font-size: 15px; font-weight: bold;"> This is text of Span element. </span> <br><br> <button> Change </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> $('button').on('click', function() { $('#GFG_Span').text("New Span text content"); $('#GFG_DOWN').text("Span content changed"); }); </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This example changes the content by using JQuery’s html() method . <!DOCTYPE HTML> <html> <head> <title> JQuery | Change the text of a span element </title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> </head> <body style = "text-align:center;" id = "body"> <h1 style = "color:green;" > GeeksForGeeks </h1> <span id="GFG_Span" style = "font-size: 15px; font-weight: bold;"> This is text of Span element. </span> <br><br> <button> Change </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> $('button').on('click', function() { $('#GFG_Span').html("<p>New Span text content</p>"); $('#GFG_DOWN').text("Span content changed"); }); </script> </body> </html> Output: Before clicking on the button: After clicking on the button: jQuery-Misc Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 May, 2019" }, { "code": null, "e": 201, "s": 28, "text": "Given an HTML document and the task is to change the text content of a <span> element. There are various methods used to change the span elements which are discussed below:" }, { "code": null, "e": 1051, "s": 201, "text": "jQuery text() Method: This method set/return the text content of specified elements. If this method is used to return content, it returns the text content of all matched elements (HTML tags will be removed). If this method is used to set content, it overwrites the content of all matched elements.Syntax:It returns the text content.$(selector).text()It sets the text content.$(selector).text(content)Set text content using a function.$(selector).text(function(index, curContent))Parameters:content: It is required parameter. It specifies the new text content for the selected elements.function(index, curContent): It is optional parameter. It specifies the function that returns the new text content for the selected elements.index: It returns the index position of element in the set.curContent: It returns the current content of selected elements." }, { "code": null, "e": 1059, "s": 1051, "text": "Syntax:" }, { "code": null, "e": 1106, "s": 1059, "text": "It returns the text content.$(selector).text()" }, { "code": null, "e": 1125, "s": 1106, "text": "$(selector).text()" }, { "code": null, "e": 1176, "s": 1125, "text": "It sets the text content.$(selector).text(content)" }, { "code": null, "e": 1202, "s": 1176, "text": "$(selector).text(content)" }, { "code": null, "e": 1282, "s": 1202, "text": "Set text content using a function.$(selector).text(function(index, curContent))" }, { "code": null, "e": 1328, "s": 1282, "text": "$(selector).text(function(index, curContent))" }, { "code": null, "e": 1340, "s": 1328, "text": "Parameters:" }, { "code": null, "e": 1436, "s": 1340, "text": "content: It is required parameter. It specifies the new text content for the selected elements." }, { "code": null, "e": 1578, "s": 1436, "text": "function(index, curContent): It is optional parameter. It specifies the function that returns the new text content for the selected elements." }, { "code": null, "e": 1638, "s": 1578, "text": "index: It returns the index position of element in the set." }, { "code": null, "e": 1703, "s": 1638, "text": "curContent: It returns the current content of selected elements." }, { "code": null, "e": 2525, "s": 1703, "text": "jQuery html() Method: This method set/return the content (HTML) of the specified elements. If this method is used to return content, it returns the content of the first matched element. If this method is used to set content, it overwrites the content of all matched elements.Syntax:Return content$(selector).html()\nSet content$(selector).html(content)\nSet content using a function$(selector).html(function(index, curContent))\nParameters:content: It is required parameter. It specifies the new text content for the selected elements containing the HTML tags.function(index, curContent): It is optional parameter. It specifies the function that returns the new content for the selected elements.index: It returns the index position of element in the set.curContent: It returns the current HTML content of selected elements." }, { "code": null, "e": 2533, "s": 2525, "text": "Syntax:" }, { "code": null, "e": 2567, "s": 2533, "text": "Return content$(selector).html()\n" }, { "code": null, "e": 2587, "s": 2567, "text": "$(selector).html()\n" }, { "code": null, "e": 2625, "s": 2587, "text": "Set content$(selector).html(content)\n" }, { "code": null, "e": 2652, "s": 2625, "text": "$(selector).html(content)\n" }, { "code": null, "e": 2727, "s": 2652, "text": "Set content using a function$(selector).html(function(index, curContent))\n" }, { "code": null, "e": 2774, "s": 2727, "text": "$(selector).html(function(index, curContent))\n" }, { "code": null, "e": 2786, "s": 2774, "text": "Parameters:" }, { "code": null, "e": 2907, "s": 2786, "text": "content: It is required parameter. It specifies the new text content for the selected elements containing the HTML tags." }, { "code": null, "e": 3044, "s": 2907, "text": "function(index, curContent): It is optional parameter. It specifies the function that returns the new content for the selected elements." }, { "code": null, "e": 3104, "s": 3044, "text": "index: It returns the index position of element in the set." }, { "code": null, "e": 3174, "s": 3104, "text": "curContent: It returns the current HTML content of selected elements." }, { "code": null, "e": 3252, "s": 3174, "text": "Example 1: This example changes the content by using JQuery’s text() method ." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> JQuery | Change the text of a span element </title> <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> </head> <body style = \"text-align:center;\" id = \"body\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <span id=\"GFG_Span\" style = \"font-size: 15px; font-weight: bold;\"> This is text of Span element. </span> <br><br> <button> Change </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> $('button').on('click', function() { $('#GFG_Span').text(\"New Span text content\"); $('#GFG_DOWN').text(\"Span content changed\"); }); </script> </body> </html> ", "e": 4268, "s": 3252, "text": null }, { "code": null, "e": 4276, "s": 4268, "text": "Output:" }, { "code": null, "e": 4307, "s": 4276, "text": "Before clicking on the button:" }, { "code": null, "e": 4337, "s": 4307, "text": "After clicking on the button:" }, { "code": null, "e": 4415, "s": 4337, "text": "Example 2: This example changes the content by using JQuery’s html() method ." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> JQuery | Change the text of a span element </title> <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> </head> <body style = \"text-align:center;\" id = \"body\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <span id=\"GFG_Span\" style = \"font-size: 15px; font-weight: bold;\"> This is text of Span element. </span> <br><br> <button> Change </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> $('button').on('click', function() { $('#GFG_Span').html(\"<p>New Span text content</p>\"); $('#GFG_DOWN').text(\"Span content changed\"); }); </script> </body> </html> ", "e": 5438, "s": 4415, "text": null }, { "code": null, "e": 5446, "s": 5438, "text": "Output:" }, { "code": null, "e": 5477, "s": 5446, "text": "Before clicking on the button:" }, { "code": null, "e": 5507, "s": 5477, "text": "After clicking on the button:" }, { "code": null, "e": 5519, "s": 5507, "text": "jQuery-Misc" }, { "code": null, "e": 5536, "s": 5519, "text": "Web Technologies" }, { "code": null, "e": 5563, "s": 5536, "text": "Web technologies Questions" } ]
JavaScript Project on Todo List
29 Jan, 2021 Introduction: TODO List are the lists that we generally use to maintain our day to day tasks or list of everything that we have to do, with the most important tasks at the top of the list, and the least important tasks at the bottom. It is helpful in planning our daily schedules. We can add more tasks any time and delete a task which is completed. The four major tasks that we can perform in a TODO list are: Add tasksUpdate tasksRead tasksDelete tasks Add tasks Update tasks Read tasks Delete tasks Example: index.html app.js <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="app.js"></script> <title>To Do List</title></head> <body> <header class="bg-success text-white p-5"> <div class="container"> <div class="row"> <div class="col-lg-12 col-md-12 col-sm-12"> <font face="Comic sans MS" size="11" color="black"> <strong>ToDo List</strong> </font> </div> </div> </div> </header> <div class="container mt-3"> <h2>Add Items</h2> <label id="lblsuccess" class="text-success" style="display: none;"> </label> <form id="addForm"> <div class="row"> <div class="col-lg-7 col-md-7 col-sm-7"> <input type="text" onkeyup= "toggleButton(this, 'submit')" class="form-control" id="item"> </div> <div class="col-lg-5 col-md-5 col-sm-5"> <input type="submit" class="btn btn-dark" id="submit" value="Submit" disabled> </div> </div> </form> <h3 class="mt-4">Tasks</h3> <form id="addForm"> <ul class="list-group" id="items"></ul> </form> </div></body> </html> window.onload = () => { const form1 = document.querySelector("#addForm"); let items = document.getElementById("items"); let submit = document.getElementById("submit"); let editItem = null; form1.addEventListener("submit", addItem); items.addEventListener("click", removeItem);}; function addItem(e) { e.preventDefault(); if (submit.value != "Submit") { console.log("Hello"); editItem.target.parentNode.childNodes[0].data = document.getElementById("item").value; submit.value = "Submit"; document.getElementById("item").value = ""; document.getElementById("lblsuccess").innerHTML = "Text edited successfully"; document.getElementById("lblsuccess") .style.display = "block"; setTimeout(function() { document.getElementById("lblsuccess") .style.display = "none"; }, 3000); return false; } let newItem = document.getElementById("item").value; if (newItem.trim() == "" || newItem.trim() == null) return false; else document.getElementById("item").value = ""; let li = document.createElement("li"); li.className = "list-group-item"; let deleteButton = document.createElement("button"); deleteButton.className = "btn-danger btn btn-sm float-right delete"; deleteButton.appendChild(document.createTextNode("Delete")); let editButton = document.createElement("button"); editButton.className = "btn-success btn btn-sm float-right edit"; editButton.appendChild(document.createTextNode("Edit")); li.appendChild(document.createTextNode(newItem)); li.appendChild(deleteButton); li.appendChild(editButton); items.appendChild(li);} function removeItem(e) { e.preventDefault(); if (e.target.classList.contains("delete")) { if (confirm("Are you Sure?")) { let li = e.target.parentNode; items.removeChild(li); document.getElementById("lblsuccess").innerHTML = "Text deleted successfully"; document.getElementById("lblsuccess") .style.display = "block"; setTimeout(function() { document.getElementById("lblsuccess") .style.display = "none"; }, 3000); } } if (e.target.classList.contains("edit")) { document.getElementById("item").value = e.target.parentNode.childNodes[0].data; submit.value = "EDIT"; editItem = e; }} function toggleButton(ref, btnID) { document.getElementById(btnID).disabled = false;} Output: Bootstrap-Misc CSS-Misc HTML-Misc JavaScript-Misc Technical Scripter 2020 Bootstrap CSS HTML JavaScript Technical Scripter Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Jan, 2021" }, { "code": null, "e": 465, "s": 54, "text": "Introduction: TODO List are the lists that we generally use to maintain our day to day tasks or list of everything that we have to do, with the most important tasks at the top of the list, and the least important tasks at the bottom. It is helpful in planning our daily schedules. We can add more tasks any time and delete a task which is completed. The four major tasks that we can perform in a TODO list are:" }, { "code": null, "e": 509, "s": 465, "text": "Add tasksUpdate tasksRead tasksDelete tasks" }, { "code": null, "e": 519, "s": 509, "text": "Add tasks" }, { "code": null, "e": 532, "s": 519, "text": "Update tasks" }, { "code": null, "e": 543, "s": 532, "text": "Read tasks" }, { "code": null, "e": 556, "s": 543, "text": "Delete tasks" }, { "code": null, "e": 565, "s": 556, "text": "Example:" }, { "code": null, "e": 576, "s": 565, "text": "index.html" }, { "code": null, "e": 583, "s": 576, "text": "app.js" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\"> <script src=\"app.js\"></script> <title>To Do List</title></head> <body> <header class=\"bg-success text-white p-5\"> <div class=\"container\"> <div class=\"row\"> <div class=\"col-lg-12 col-md-12 col-sm-12\"> <font face=\"Comic sans MS\" size=\"11\" color=\"black\"> <strong>ToDo List</strong> </font> </div> </div> </div> </header> <div class=\"container mt-3\"> <h2>Add Items</h2> <label id=\"lblsuccess\" class=\"text-success\" style=\"display: none;\"> </label> <form id=\"addForm\"> <div class=\"row\"> <div class=\"col-lg-7 col-md-7 col-sm-7\"> <input type=\"text\" onkeyup= \"toggleButton(this, 'submit')\" class=\"form-control\" id=\"item\"> </div> <div class=\"col-lg-5 col-md-5 col-sm-5\"> <input type=\"submit\" class=\"btn btn-dark\" id=\"submit\" value=\"Submit\" disabled> </div> </div> </form> <h3 class=\"mt-4\">Tasks</h3> <form id=\"addForm\"> <ul class=\"list-group\" id=\"items\"></ul> </form> </div></body> </html>", "e": 2342, "s": 583, "text": null }, { "code": "window.onload = () => { const form1 = document.querySelector(\"#addForm\"); let items = document.getElementById(\"items\"); let submit = document.getElementById(\"submit\"); let editItem = null; form1.addEventListener(\"submit\", addItem); items.addEventListener(\"click\", removeItem);}; function addItem(e) { e.preventDefault(); if (submit.value != \"Submit\") { console.log(\"Hello\"); editItem.target.parentNode.childNodes[0].data = document.getElementById(\"item\").value; submit.value = \"Submit\"; document.getElementById(\"item\").value = \"\"; document.getElementById(\"lblsuccess\").innerHTML = \"Text edited successfully\"; document.getElementById(\"lblsuccess\") .style.display = \"block\"; setTimeout(function() { document.getElementById(\"lblsuccess\") .style.display = \"none\"; }, 3000); return false; } let newItem = document.getElementById(\"item\").value; if (newItem.trim() == \"\" || newItem.trim() == null) return false; else document.getElementById(\"item\").value = \"\"; let li = document.createElement(\"li\"); li.className = \"list-group-item\"; let deleteButton = document.createElement(\"button\"); deleteButton.className = \"btn-danger btn btn-sm float-right delete\"; deleteButton.appendChild(document.createTextNode(\"Delete\")); let editButton = document.createElement(\"button\"); editButton.className = \"btn-success btn btn-sm float-right edit\"; editButton.appendChild(document.createTextNode(\"Edit\")); li.appendChild(document.createTextNode(newItem)); li.appendChild(deleteButton); li.appendChild(editButton); items.appendChild(li);} function removeItem(e) { e.preventDefault(); if (e.target.classList.contains(\"delete\")) { if (confirm(\"Are you Sure?\")) { let li = e.target.parentNode; items.removeChild(li); document.getElementById(\"lblsuccess\").innerHTML = \"Text deleted successfully\"; document.getElementById(\"lblsuccess\") .style.display = \"block\"; setTimeout(function() { document.getElementById(\"lblsuccess\") .style.display = \"none\"; }, 3000); } } if (e.target.classList.contains(\"edit\")) { document.getElementById(\"item\").value = e.target.parentNode.childNodes[0].data; submit.value = \"EDIT\"; editItem = e; }} function toggleButton(ref, btnID) { document.getElementById(btnID).disabled = false;}", "e": 5031, "s": 2342, "text": null }, { "code": null, "e": 5039, "s": 5031, "text": "Output:" }, { "code": null, "e": 5054, "s": 5039, "text": "Bootstrap-Misc" }, { "code": null, "e": 5063, "s": 5054, "text": "CSS-Misc" }, { "code": null, "e": 5073, "s": 5063, "text": "HTML-Misc" }, { "code": null, "e": 5089, "s": 5073, "text": "JavaScript-Misc" }, { "code": null, "e": 5113, "s": 5089, "text": "Technical Scripter 2020" }, { "code": null, "e": 5123, "s": 5113, "text": "Bootstrap" }, { "code": null, "e": 5127, "s": 5123, "text": "CSS" }, { "code": null, "e": 5132, "s": 5127, "text": "HTML" }, { "code": null, "e": 5143, "s": 5132, "text": "JavaScript" }, { "code": null, "e": 5162, "s": 5143, "text": "Technical Scripter" }, { "code": null, "e": 5179, "s": 5162, "text": "Web Technologies" }, { "code": null, "e": 5184, "s": 5179, "text": "HTML" } ]